That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
so simple :
outline-color : blue !important;
the whole CSS for my react-boostrap button is:
.custom-btn { font-size:1.9em; background: #2f5bff; border: 2px solid #78e4ff; border-radius: 3px; padding: 50px 70px; outline-color : blue !important; text-transform: uppercase; user-select: auto; -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2); -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2); -webkit-border-radius: 3px; -moz-border-radius: 3px; }
You can't directly call a function in another shell script.
You can move your function definitions into a separate file and then load them into your script using the .
command, like this:
. /path/to/functions.sh
This will interpret functions.sh
as if it's content were actually present in your file at this point. This is a common mechanism for implementing shared libraries of shell functions.
#1- Run this to configure the region once and for all:
aws configure set region us-east-1 --profile admin
Change admin
next to the profile if it's different.
Change us-east-1
if your region is different.
#2- Run your command again:
aws ecs list-container-instances --cluster default
I had a similar problem when trying to use boost unit testing in Visual Studio 2015 (Community Edition):
fatal error LNK1104: libboost_unit_test_framework-vc140-mt-1_57
so I thought I'd share my solution.
You can create a boost unit testing project in of of two ways (and this solution works for both):
Here are the steps I followed to get both projects to work:
First, download the desired boost version (for example, boost_1_57_0). You can either download boost with the correct binaries (compiled using msvc v140), or extract the binaries yourself by running the following commands from command line:
Where msvc-14.0 specifies that we require the Visual Studio 2015 version (VS 2015 = v14.0 = v140), and address-model=32 specifies that we require platform 32 (but the same can be done for 64 bit).
Once you have the binaries, go to Visual Studio, select the Boost Unit Testing project you have created. Go to Project properties > configuration (from the main menu) and make the following choices:
Set the "General > Platform Toolset" to Visual Studio 2015 (v140).
Include the path to the boost folder (e.g. C:\boost_1_57_0) and the path to the subfolder containing the binary files (e.g. C:\boost_1_57_0\stage\lib) in:
The solution with removing the license information from the registry also works with Visual Studio 2013, but as described in the answer above, it is important to execute a "repair" on Visual Studio.
Here's a sed
version:
sed -e '\|include "/configs/projectname.conf"|h; ${x;s/incl//;{g;t};a\' -e 'include "/configs/projectname.conf"' -e '}' file
If your string is in a variable:
string='include "/configs/projectname.conf"'
sed -e "\|$string|h; \${x;s|$string||;{g;t};a\\" -e "$string" -e "}" file
its possible if you already have a python installed (pip) you could do a upgrade on mac by
brew upgrade python
(SELECT CASE WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE WHEN ISNULL(ChequeNo,0) IS NOT NULL THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE AND (Month= 1) AND (Year = 2020) AND )END AS Stat)
If you want to round the decimal, look at Math.Round()
Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header
#include <math.h>
then you can use pow().
you can do it in two ways using
Serializable
Parcelable.
This examle will show you how to implement it with serializable
class Customer implements Serializable
{
// properties, getter setters & constructor
}
// This is your custom object
Customer customer = new Customer(name, address, zip);
Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);
// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Customer customer = (Customer)extras.getSerializable("customer");
// do something with the customer
}
Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.
Look at this.. This discussion will let you know which is much better way to implement it.
Thanks.
Ok, I just figured out where was the problem - in Bootstrap is set up as a default value width
for select
element, thus, the solution is:
tr. something {
td {
select {
width: 90px;
}
}
}
Anything else doesn't work me.
Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins
folder.
When you have done that go to
Window -> Preferences -> General -> Appearance
And change the theme from GTK (or what ever it is currently) to Dark Juno
(or Dark).
That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.
This adds a "Color Theme" menu item under
Window -> Preferences -> Appearance
Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark
Simple method to get the records count:
df.count()[0]
I think there is no one right way. There are a lot of different ways to iterate, and each has its own niche.
each
is sufficient for many usages, since I don't often care about the indexes. each_ with _index
acts like Hash#each - you get the value and the index.each_index
- just the indexes. I don't use this one often. Equivalent to "length.times".map
is another way to iterate, useful when you want to transform one array into another.select
is the iterator to use when you want to choose a subset.inject
is useful for generating sums or products, or collecting a single result. It may seem like a lot to remember, but don't worry, you can get by without knowing all of them. But as you start to learn and use the different methods, your code will become cleaner and clearer, and you'll be on your way to Ruby mastery.
If your application needs to handle money values up to a trillion then this should work: 13,2 If you need to comply with GAAP (Generally Accepted Accounting Principles) then use: 13,4
Usually you should sum your money values at 13,4 before rounding of the output to 13,2.
If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.
To further generalize @Alexander's example, outer
is relevant in cases where a function must compute itself on each pair of vector values:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
outer(vars1,vars2,mult_one)
gives:
> outer(vars1, vars2, mult_one)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 20 40 60
[3,] 30 60 90
This how I manage with very big file (tested with up to 100G). And it's faster than fgets()
$block =1024*1024;//1MB or counld be any higher than HDD block_size*2
if ($fh = fopen("file.txt", "r")) {
$left='';
while (!feof($fh)) {// read the file
$temp = fread($fh, $block);
$fgetslines = explode("\n",$temp);
$fgetslines[0]=$left.$fgetslines[0];
if(!feof($fh) )$left = array_pop($lines);
foreach ($fgetslines as $k => $line) {
//do smth with $line
}
}
}
fclose($fh);
This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().
In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:
lastEditText.setOnKeyListener { v, keyCode, event ->
var setOnKeyListener = false
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
try {
val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
nextET.isFocusableInTouchMode = true
nextET.requestFocus()
} catch (e: Exception) {
// do nothing
}
setOnKeyListener = true
}
setOnKeyListener
}
add the fun getViewByPosition() after fun getView() as below:
private fun getViewByPosition(pos: Int, listView: ListView): View? {
val firstListItemPosition: Int = listView.firstVisiblePosition
val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
return if (pos < firstListItemPosition || pos > lastListItemPosition) {
listView.adapter.getView(pos, null, listView)
} else {
val childIndex = pos + listView.headerViewsCount - firstListItemPosition
listView.getChildAt(childIndex)
}
}
This is from Apple doc
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
You get the error message Class "HomeCell" has no initializers because your variables is in an indeterminate state. Either you create initializers or you make them optional types, using ! or ?
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub Example()
DownloadFile$ = "someFile.ext" 'here the name with extension
URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub
I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.
This was helpful because our organization has Kaspersky AV which blocks active
FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!
Download the Print.js from http://printjs.crabbly.com/
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
You can't "open" a directory using the open
function. This function is meant to be used to open files.
Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join
function will let you do that by joining parts of the path (the directory and the file name):
fpath = os.path.join(direct, "5_1.txt")
You can then open the file:
f = open(fpath)
And read its content:
content = f.read()
Additionally, I believe that on Windows, using open
on a directory does return a PermissionDenied
exception, although that's not really the case.
You shouldn't really be de-encrypting passwords.
You should be encrypting the password entered into your application and comparing against the encrypted password from the database.
Edit - and if this is because the password has been forgotten, then setup a mechanism to create a new password.
To summarize:
p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"
Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.
You can find creation/deletion of environments in the Anaconda documentation.
Hope this helped.
The top answer is great.
I would just add, that it becomes easy to understand if you think about remotes as locations other than your computer that you may want to move your code to.
Some very good examples are:
So you can certainly have multiple remotes. A very common pattern is to use GitHub to store your code, and a server to host your application (if it's a web application). Then you would have 2 remotes (possibly more if you have other environments).
Try opening your git config by typing git config -e
Note: press escape, then :, then q then enter to quit out
Here's what you might see in your git configs if you had 3 remotes. In this example, 1 remote (called 'origin') is GitHub, another remote (called 'staging') is a staging server, and the third (called 'heroku') is a production server.
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = https://github.com/username/reponame.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[remote "heroku"]
url = https://git.heroku.com/appname.git
fetch = +refs/heads/*:refs/remotes/heroku/*
[remote "staging"]
url = https://git.heroku.com/warm-bedlands-98000.git
fetch = +refs/heads/*:refs/remotes/staging/*
The three lines starting with [remote ...
show us the remotes we can push to.
Running git push origin
will push to the url for '[remote "origin"]', i.e. to GitHub
But similarly, we could push to another remote, say, '[remote "staging"]', with git push staging
, then it would push to https://git.heroku.com/warm-bedlands-98000.git
.
In the example above, we can see the 3 remotes with git remote
:
git remote
heroku
origin
staging
origin
Remotes are simply places on the internet that you may have a reason to send your code to. GitHub is an obvious place, as are servers that host your app, and you may have other locations too. git push origin
simply means it will push to 'origin', which is the name GitHub chooses to default to.
branchname
branchname
is simply what you're push
ing to the remote. According the git push help docs, the branchname
argument is technically a refspec
, which, for practical purposes, is the branch you want to push.
git push
by running: git push --help
Adding the following line in the head tag fixed my issue.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.
Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.
Using List<String> list = new LinkedList()
will get you rawtype warnings.
A web site for coloration with lots of languages. http://hilite.me/
You can host one yourself since it is open source. The code is on github.
On PostgreSQL manual
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.
I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html
On the ASP.NET page, inside the form tags.
Put the following into your ~/.Rprofile
file:
exclude <- function(blah) {
"excluded block"
}
Now, you can exclude blocks like follows:
stuffiwant
exclude({
stuffidontwant
morestuffidontwant
})
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedOr you can do this way :
((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");
Angular 4 empty data if else
if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}
And if all else fails, such as ensuring that the target frameworks are the same, and you are dealing with a WPF class library in VS2010, simply restart Visual Studio. That did it for me.
you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/
First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript
@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver
program on all your old classes. put these serialVersionUID
values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID
on all Serializable
classes)
if the new versions are not serial compatible, then you need to do some magic with a custom readObject
implementation (you would only need a custom writeObject
if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.
Of course, even if the new class is serial compatible, you may still want a custom readObject
implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).
If you're hosting the page and the iframe on the same domain you can listen for the iframe's Window.DOMContentLoaded
event. You have to wait for the original page to fire DOMContentLoaded
first, then attach a DOMContentLoaded
event listener on the iframe's Window
.
Given you have an iframe as follows,
<iframe id="iframe-id" name="iframe-name" src="..."></iframe>
the next snippet will allow you to hook into the iframe's DOMContentLoaded
event:
document.addEventListener('DOMContentLoaded', function () {
var iframeWindow = frames['iframe-name'];
// var iframeWindow = document.querySelector('#iframe-id').contentWindow
// var iframeWindow = document.getElementById('iframe-id').contentWindow
iframeWindow.addEventListener('DOMContentLoaded', function () {
console.log('iframe DOM is loaded!');
});
});
Converting a date String of the format "2011-06-23T15:11:32" to our time zone.
private String getDate(String ourDate)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
ourDate = dateFormatter.format(value);
//Log.d("ourDate", ourDate);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}
As answered in other posts, you have two different options for different platforms. What I do is:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
// Mock device.platform property if not available
if (!window.device) {
window.device = { platform: 'Browser' };
}
handleExternalURLs();
}
function handleExternalURLs() {
// Handle click events for all external URLs
if (device.platform.toUpperCase() === 'ANDROID') {
$(document).on('click', 'a[href^="http"]', function (e) {
var url = $(this).attr('href');
navigator.app.loadUrl(url, { openExternal: true });
e.preventDefault();
});
}
else if (device.platform.toUpperCase() === 'IOS') {
$(document).on('click', 'a[href^="http"]', function (e) {
var url = $(this).attr('href');
window.open(url, '_system');
e.preventDefault();
});
}
else {
// Leave standard behaviour
}
}
So as you can see I am checking the device platform and depending on that I am using a different method. In case of a standard browser, I leave standard behaviour. From now on the solution will work fine on Android, iOS and in a browser, while HTML page won't be changed, so that it can have URLs represented as standard anchor
<a href="http://stackoverflow.com">
The solution requires InAppBrowser and Device plugins
Considering this as a general programming problem, some possible causes are:
The service could be temporarily broken
You could have a problem with a firewall. These could be local or they could be implemented by your ISPs.
Your proxy HTTP settings (if you need one) could be incorrect. This Answer explains how to adjust the Eclipse-internal proxy settings ... if that is where the problem lies.
It is possible that your access may be blocked by over-active antivirus software.
The service could have blacklisted some net range and your hosts IP address is "collateral damage".
Try connecting to that URL with a web browser to try to see if it is just Eclipse that is affected ... or a broader problem.
Considering this in the context of the Eclipse Marketplace service, first address any local proxy / firewall / AV issues, if they apply. If that doesn't help, the best thing that you can do is to be patient.
It has been observed that the Eclipse Marketplace service does sometimes go down. It doesn't happen often, and when it does happen the problem does get fixed relatively quickly. (Hours, not days ...)
I can't find a "service status" page or feed or similar for the Eclipse services. (If you know of one, please add it as a comment below.)
There may be an "outage" notice on the Eclipse front page. Check for that.
Try to connect to the service URL (refer to the exception message!) using a web browser and/or from other locations. If you succeed, the real problem may be a networking issue at your end.
If you feel the need to complain about Eclipse's services, please don't do it here!! (It is off topic.)
If you have the option of using fetchAll() then if there are no rows returned it will just be and empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You cannot exactly get a list of commands started with nohup
but you can see them along with your other processes by using the command ps x
. Commands started with nohup
will have a question mark in the TTY column.
WARNING: It should be noted that this solution will block the calling thread.
If you want to process exceptions thrown by the task, then it is generally better to use Callable
rather than Runnable
.
Callable.call()
is permitted to throw checked exceptions, and these get propagated back to the calling thread:
Callable task = ...
Future future = executor.submit(task);
try {
future.get();
} catch (ExecutionException ex) {
ex.getCause().printStackTrace();
}
If Callable.call()
throws an exception, this will be wrapped in an ExecutionException
and thrown by Future.get()
.
This is likely to be much preferable to subclassing ThreadPoolExecutor
. It also gives you the opportunity to re-submit the task if the exception is a recoverable one.
Where is the sparkContext object defined, is it inside the main function?
I too faced the same problem, the mistake which i did was i initiated the sparkContext outside the main function and inside the class.
When I initiated it inside the main function, it worked fine.
std::map<Key, Value>
? SortedDictionary<TKey, TValue>
std::unordered_map<Key, Value>
? Dictionary<TKey, TValue>
Sample
var yourString = "first line \n second line \n third line"
In case, you don't find the + operator suitable
This error indicates that the two tables have the 1 or more column names that have the same column name. The error message translates to: "I can see the same column in both tables but you haven't told me to rename either before bringing one of them in"
You either want to delete one of the columns before bringing it in from the other on using del df['column name'], or use lsuffix to re-write the original column, or rsuffix to rename the one that is being brought it.
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:
.dropdown-menu li {
position: relative;
}
I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).
Here is the full less/css change (replace the above with this):
.dropdown-menu li {
position: relative;
[class^="icon-"] {
float: right;
}
&:hover {
// Switch to white icons on hover
[class^="icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
}
}
Wikipedia never lets down:
Michael Krelin's answer is close is not entirely safe, since it can be wrong in rare situations. The problem is that intervals in PostgreSQL do not have context with regards to things like daylight savings. Intervals store things internally as months, days, and seconds. Months aren't an issue in this case since subtracting two timestamps just use days and seconds but 'days' can be a problem.
If your subtraction involves daylight savings change-overs, a particular day might be considered 23 or 25 hours respectively. The interval will take that into account, which is useful for knowing the amount of days that passed in the symbolic sense but it would give an incorrect number of the actual hours that passed. Epoch on the interval will just multiply all days by 24 hours.
For example, if a full 'short' day passes and an additional hour of the next day, the interval will be recorded as one day and one hour. Which converted to epoch/3600 is 25 hours. But in reality 23 hours + 1 hour should be a total of 24 hours.
So the safer method is:
(EXTRACT(EPOCH FROM current_timestamp) - EXTRACT(EPOCH FROM somedate))/3600
As Michael mentioned in his follow-up comment, you'll also probably want to use floor() or round() to get the result as an integer value.
Change %
to %%
for use in batch file, for %~ta
syntax enter call /?
for %a in (MyFile.txt) do set FileDate=%~ta
Sample output:
for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM
for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
To style for many smartphones with smaller screens, you could write:
@media screen and (max-width:480px) { … }
To block older browsers from seeing an iPhone or Android phone style sheet, you could write:
@media only screen and (max-width: 480px;) { … }
Read this article for more http://webdesign.about.com/od/css3/a/css3-media-queries.htm
I stumbled upon this recently to free up resource in my cluster. here is the command to delete them all.
kubectl get pods --all-namespaces | grep Terminating | while read line; do
pod_name=$(echo $line | awk '{print $2}' ) name_space=$(echo $line | awk
'{print $1}' ); kubectl delete pods $pod_name -n $name_space --grace-period=0 --force;
done
hope this help someone who read this
Dim M As Range
Set M = Selection
If application.CountIf(M, "<>0") < 2 Then
MsgBox "Nothing selected, please select first BOM or Next BOM"
Else
'Your code here
End If
From experience I just learned you could do:
If Selection.Rows.Count < 2
Then End If`
Clarification to be provided a bit later (right now I'm working)
The value for BYTES PER CLUSTER - 65536 = 64K
C:\temp>fsutil fsinfo drives
Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\ N:\ O:\ P:\ S:\
C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number : 0xfe5a90935a9049f3
NTFS Version : 3.1
LFS Version : 2.0
Number Sectors : 0x00000002e15befff
Total Clusters : 0x000000005c2b7dff
Free Clusters : 0x000000005c2a15f0
Total Reserved : 0x0000000000000000
Bytes Per Sector : 512
Bytes Per Physical Sector : 512
Bytes Per Cluster : 4096
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x0000000000040000
Mft Start Lcn : 0x00000000000c0000
Mft2 Start Lcn : 0x0000000000000002
Mft Zone Start : 0x00000000000c0000
Mft Zone End : 0x00000000000cc820
Resource Manager Identifier : 560F51B2-CEFA-11E5-80C9-98BE94F91273
C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number : 0x36acd4b1acd46d3d
NTFS Version : 3.1
LFS Version : 2.0
Number Sectors : 0x00000002e15befff
Total Clusters : 0x0000000005c2b7df
Free Clusters : 0x0000000005c2ac28
Total Reserved : 0x0000000000000000
Bytes Per Sector : 512
Bytes Per Physical Sector : 512
Bytes Per Cluster : 65536
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x0000000000010000
Mft Start Lcn : 0x000000000000c000
Mft2 Start Lcn : 0x0000000000000001
Mft Zone Start : 0x000000000000c000
Mft Zone End : 0x000000000000cca0
Resource Manager Identifier : 560F51C3-CEFA-11E5-80C9-98BE94F91273
It will return 18 results starting on record #9 and finishing on record #26.
Start by reading the query from offset
. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.
Check this out.
And also the official documentation.
Use:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
Always use the above command to enable to executing PowerShell in the current session.
A rather separable way of doing this is to use
import tensorflow as tf
from keras import backend as K
num_cores = 4
if GPU:
num_GPU = 1
num_CPU = 1
if CPU:
num_CPU = 1
num_GPU = 0
config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
inter_op_parallelism_threads=num_cores,
allow_soft_placement=True,
device_count = {'CPU' : num_CPU,
'GPU' : num_GPU}
)
session = tf.Session(config=config)
K.set_session(session)
Here, with booleans
GPU
and CPU
, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU
and num_CPU
define this value. num_cores
then sets the number of CPU cores available for usage via intra_op_parallelism_threads
and inter_op_parallelism_threads
.
The intra_op_parallelism_threads
variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads
variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).
allow_soft_placement
allows for operations to be run on the CPU if any of the following criterion are met:
there is no GPU implementation for the operation
there are no GPU devices known or registered
there is a need to co-locate with other inputs from the CPU
All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.
Note: This requires tensorflow-gpu
and cuda
/cudnn
to be installed because the option is given to use a GPU.
Refs:
You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:
// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
final char[] buf = new char[32];
for (int i = 31; i >= 0; i--) {
buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
}
return new String(buf);
}
I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".
Sample code:
var fs = require('fs')
, split = require('split')
;
var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
var json = JSON.parse(chunk);
// ...
});
The solutions provided here can only be applied if the user defined types are used in table definitions only, and if the UDT columns are not indexed.
Some developers also have SP's and functions using UDT parameters, which is not covered either. (see comments on Robin's link and in the Connect entry)
The Connect entry from 2007 has finally been closed after 3 years:
Thank you for submitting this suggestion, but given its priority relative to the many other items in our queue, it is unlikely that we will actually complete it. As such, we are closing this suggestion as “won’t fix”.
I tried to solve a similiar problem ALTERing XML SCHEMA COLLECTIONS, and the steps seem to mostly apply to ALTER TYPE, too:
To drop a UDT, the following steps are necessary:
You need to use v-bind:
or its alias :
. For example,
<a v-bind:href="'/job/'+ r.id">
or
<a :href="'/job/' + r.id">
I supose the "opposite" would be to simulate an event. You could use .createEvent()
Following Mozilla's example:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var cancelled = !cb.dispatchEvent(evt);
if(cancelled) {
// A handler called preventDefault
alert("cancelled");
} else {
// None of the handlers called preventDefault
alert("not cancelled");
}
}
Ref: document.createEvent
jQuery has .trigger()
so you can trigger events on elements -- sometimes useful.
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
I've run into a same error in Eclipse recently, i.e., the Eclipse IDE couldn't find the Unit test class no matter how I change the configurations. Learning from the previous posts here and in other web sites, I've double checked and triple checked the classpath and source info, and move up and down the source folder and libraries, in both the "Run Configuration" and the "Java Build Path" config windows, and I've also cleaned the Project and rebuilt it, but none of the tricks work for me. The specific Java project is an old ANT compiled project and have lots of jars included in Eclipse library.
Then, I changed the unit test class to add a main() method and right click it to "Run As" a Java Application instead of JUnit test, and suddenly, Eclipse seems to wake up and identified the class correctly. Afterwards, I switched it back to a Unit test application, and it is still working.
This seems to be a bug in Eclipse, I am guessing the large number of libraries (>260) may confused the JVM's ability to locate my JUnit class.
for frequency distribution of a variable with excessive values you can collapse down the values in classes,
Here I excessive values for employrate
variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
.. ... ... ...
208 Vietnam 71.000000 3.91
209 West Bank and Gaza 32.000000
210 Yemen, Rep. 39.000000 .2
211 Zambia 61.000000 3.56
212 Zimbabwe 66.800003 4.96
[213 rows x 3 columns]
frequency distribution with values_count(normalize=True)
with no classification,length of result here is 139 (seems meaningless as a frequency distribution):
print(gm["employrate"].value_counts(sort=False,normalize=True))
50.500000 0.005618
61.500000 0.016854
46.000000 0.011236
64.500000 0.005618
63.500000 0.005618
58.599998 0.005618
63.799999 0.011236
63.200001 0.005618
65.599998 0.005618
68.300003 0.005618
Name: employrate, Length: 139, dtype: float64
putting classification we put all values with a certain range ie.
0-10 as 1, 11-20 as 2 21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))
after classification we have a clear frequency distribution.
here we can easily see, that 37.64%
of countries have employ rate between 51-60%
and 11.79%
of countries have employ rate between 71-80%
5.000000 0.376404
7.000000 0.117978
4.000000 0.179775
6.000000 0.264045
8.000000 0.033708
3.000000 0.028090
Name: employrate, dtype: float64
To Angular 4, many of the options no longer work. Update July 2017 Two posibilities:
1) The simplest one is to open the package.json of our project and to check the versions used, among them the one of Angular.
2) After executing ng serve, we open the inspector of elements of the explorer that we use and we can observe the version as in the following image.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Chain
You can now use the chain
feature in packed
mode as describe in Eugene's answer.
Guideline
You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<android.support.design.widget.TextInputLayout
android:id="@+id/client_id_input_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/login_client_id"
android:inputType="textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/authenticate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/login_auth"
app:layout_constraintTop_toTopOf="@+id/guideline"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"/>
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
</android.support.constraint.ConstraintLayout>
git reset <hash> # you need to know the last good hash, so you can remove all your local commits
git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f
voila, now your fork is back to same as upstream.
Another reason could be because the filepath is empty where you are trying to write which is why it can't find it. just another reason why this error occurs.
To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx
ActionResult is an abstract class, and it's base class for ViewResult class.
In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.
And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.
It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.
In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like
class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
...
}
then just issue the command
Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName
and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:
Update-Database -ConfigurationTypeName MyNewContextConfiguration
Done.
You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.
You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
If you want to use PathLocationStrategy :
Single page application with Java EE/Wildfly: server-side configuration
You can use JsonConvert from Newtonsoft library. To serialize an object and write to a file in json format:
File.WriteAllText(filePath, JsonConvert.SerializeObject(obj));
And to deserialize it back into object:
var obj = JsonConvert.DeserializeObject<ObjType>(File.ReadAllText(filePath));
If you're running into this error from a downloaded powershell script, you can unblock the script this way:
Right-click on the .ps1
file in question, and select Properties
Click Unblock in the file properties
Click OK
Pure Bash, no external utilities
This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.
pad=$(printf '%0.1s' "-"{1..60})
padlength=40
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
printf '%s' "$string1"
printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
printf '%s\n' "$string2"
string2=${string2:1}
done
Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:
padlimit=60
pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}
So the pad (padlimit
and padlength
) could be based on terminal width ($COLUMNS
) or computed from the length of the longest data string.
Output:
a--------------------------------bbbbbbb
aa--------------------------------bbbbbb
aaaa-------------------------------bbbbb
aaaaaaaa----------------------------bbbb
Without subtracting the length of the second string:
a---------------------------------------bbbbbbb
aa--------------------------------------bbbbbb
aaaa------------------------------------bbbbb
aaaaaaaa--------------------------------bbbb
The first line could instead be the equivalent (similar to sprintf
):
printf -v pad '%0.1s' "-"{1..60}
or similarly for the more dynamic technique:
printf -v pad '%*s' "$padlimit"
You can do the printing all on one line if you prefer:
printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"
Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.
$myForm.find(':input:not(:disabled)').prop('disabled',true)
My problem was overwriting my query string parameters with default values:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = ""}
);
No matter what I plugged into query string or how only key=""
results.
Then got rid of default overwrites using UrlParameter.Optional:
routes.MapRoute(
"apiRoute",
"api/{action}/{key}",
new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);
now
prices/{key}
or
prices?key={key}
both work fine.
Here is my implementation for python 3 and pycrypto
from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())
x = key.encrypt(b"dddddd",32)
print(x)
z = key1.decrypt(x)
print(z)
If you are building an app, you just need the @babel/preset-env
and @babel/polyfill
:
npm i -D @babel/preset-env
npm i @babel/polyfill
(Note: you don't need to install the core-js
and regenerator-runtime
packages because they both will have been installed by the @babel/polyfill)
Then in .babelrc
:
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry" // this is the key. use 'usage' for further codesize reduction, but it's still 'experimental'
}
]
]
}
Now set your target environments. Here, we do it in the .browserslistrc
file:
# Browsers that we support
>0.2%
not dead
not ie <= 11
not op_mini all
Finally, if you went with useBuiltIns: "entry"
, put import @babel/polyfill
at the top of your entry file. Otherwise, you are done.
Using this method will selectively import those polyfills and the 'regenerator-runtime' file(fixing your regeneratorRuntime is not defined
issue here) ONLY if they are needed by any of your target environments/browsers.
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
As another answer here stated:
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
Is a possible solution: Some comments here, myself included, had issues with permissions while using this command. A little change to the following solved those for me.
pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 sudo -H pip install -U
Note the added sudo -H
which allowed the command to run with root permissions.
Use:
date.format("MM/DD/YYYY") or date.format("MM-DD-YYYY")}
Other Supported formats for reference:
M 1 2 ... 11 12
Mo 1st 2nd ... 11th 12th
MM 01 02 ... 11 12
MMM Jan Feb ... Nov Dec
MMMM January February ... November December
d 0 1 ... 5 6
do 0th 1st ... 5th 6th
dd Su Mo ... Fr Sa
ddd Sun Mon ... Fri Sat
dddd Sunday Monday ... Friday Saturday
YY 70 71 ... 29 30
YYYY 1970 1971 ... 2029 2030
Y 1970 1971 ... 9999 +10000 +10001
You can use unequal comparison -ne
instead of -eq
:
wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -ne 0 ]]; then
echo "Sorry you are Offline"
exit 1
fi
You can also get this information from the command line using the xcodebuild command with the -showBuildSettings switch:
$ xcodebuild -project myProj.xcodeproj -target "myTarg" -showBuildSettings
This will dump a list like the one shown above to the standard output.
Here is the official answer from Microsoft: http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx
Summary if you'd rather not click through:
Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:
MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
Install the DirectX SDK (June 2010)
Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB2565063 with a security fix.
Windows SDK: The Windows SDK 7.1 has exactly the same issue as noted in KB 2717426.
Recent IntelliJ versions allows automatic creation of desktop entry. See this gist
Just because I made this mistake every time when using the submit function.
This is the full code you need:
Add the id "yourid" to the HTML form tag.
<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>
the jQuery code:
$('#yourid').submit(function() {
// do something
});
It can now be changed to lambda version
@Override
public void actionPerformed(ActionEvent e) {
Platform.runLater(() -> {
try {
//an event with a button maybe
System.out.println("button is clicked");
} catch (IOException | COSVisitorException ex) {
Exceptions.printStackTrace(ex);
}
});
}
You'll have to parse again if you want it in actual JSON:
JSON.parse(JSON.stringify(object))
Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.
Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).
function append_output(suffix, value) {
$("#output_"+suffix).append(value)
}
function kickOff() {
let start = new Promise((resolve, reject) => {
append_output("now", "start")
resolve("start")
})
let middle = new Promise((resolve, reject) => {
setTimeout(() => {
append_output("now", " middle")
resolve(" middle")
}, 1000)
})
let end = new Promise((resolve, reject) => {
append_output("now", " end")
resolve(" end")
})
Promise.all([start, middle, end]).then(results => {
results.forEach(
result => append_output("later", result))
})
}
kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
You want options(warn=-1)
. However, note that warn=0
is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:
oldw <- getOption("warn")
options(warn = -1)
[your "silenced" code]
options(warn = oldw)
This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.
$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email` != "" AND `email` IS NOT NULL
');
This is just additional information for this answer.
If you are using nginx
, you would add proxy_set_header X-Real-IP $remote_addr;
to the location block for the site. /etc/nginx/sites-available/www.example.com
for example. Here is a example server block.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.1.1:3080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
After restarting nginx
, you will be able to access the ip in your node
/express
application routes with req.headers['x-real-ip'] || req.connection.remoteAddress;
I will group the options based on output. Assume the following vector for all the examples.
v <- c('z', 'a','b','a','e')
For checking presence:
%in%
> 'a' %in% v
[1] TRUE
any()
> any('a'==v)
[1] TRUE
is.element()
> is.element('a', v)
[1] TRUE
For finding first occurance:
match()
> match('a', v)
[1] 2
For finding all occurances as vector of indices:
which()
> which('a' == v)
[1] 2 4
For finding all occurances as logical vector:
==
> 'a' == v
[1] FALSE TRUE FALSE TRUE FALSE
Edit: Removing grep() and grepl() from the list for reason mentioned in comments
MySQL has discontinued drop database command from mysql client shell. Need to use mysqladmin to drop a database.
select * from Tran_LibraryBooksTrans LBT left join
Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN' AND
LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
ELSE 0 END`enter code here`select * from Tran_LibraryBooksTrans LBT
left join Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
1 ELSE 0 END
Try:
2**3*2
and
2*3*2
to see the difference.
**
is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.
Easiest way to find address path in Excel 2010:
File - info - properties (on right) - (drop-down menu) - advanced properties - general tab
You will get to the same properties box that was so simple to find in Excel 2003.
I like polymorphism instead of manually checking for something:
use MooseX::Declare;
class Foo {
use MooseX::MultiMethods;
multi method foo (ArrayRef $arg){ say "arg is an array" }
multi method foo (HashRef $arg) { say "arg is a hash" }
multi method foo (Any $arg) { say "arg is something else" }
}
Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else
This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.
Your type library:
package MyApp::Types;
use MooseX::Types -declare => ['EvenNumberLessThan42'];
use MooseX::Types::Moose qw(Num);
subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };
Then make Foo support this (in that class definition):
class Foo {
use MyApp::Types qw(EvenNumberLessThan42);
multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}
Then Foo->new->foo(40)
prints arg is an even number less than 42
instead of arg is something else
.
Maintainable.
Try this:
SELECT CONVERT(DATE, STUFF(STUFF('01012020', 5, 0, '-'), 3, 0, '-'), 103);
It works with SQL Server 2016.
The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
That's my way to bind to code behind (see property DataTemplateSelector
)
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataTemplateSelector = new MyDataTemplateSelector();
InitializeComponent();
// ... more initializations ...
}
public DataTemplateSelector DataTemplateSelector { get; }
// ... more code stuff ...
}
In XAML will referenced by RelativeSource
via Ancestors up to containing Window
, so I'm at my Window
class and use the property via Path
declaration:
<GridViewColumn Header="Value(s)"
CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>
Setting of property DataTemplateSelector
before call InitializeComponent
depends on missing implementation of IPropertyChanged
or use of implementation with DependencyProperty
so no communication run on change of property DataTemplateSelector
.
You Could Do The same as abatishchev but without the UAC
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
You can make it with jQuery a less lines:
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
With $(':checkbox[required]') you select all checkboxes with the attribute required, then, with the .change method applied to this group of checkboxes, you can execute the function you want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the required attribute for all of the checkboxes that are part of the selected group.
I hope this helps.
Farewell.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
Also, there is the solution for IvyDE users. Right click on project -> Ivy -> resolve It's necessary to set ivy.mirror property in build.properties
Just wanted to contribute the three methods I've bounced back and forth with.
Method 1:
var record = ctx.Records.FirstOrDefault();
ctx.Records.Remove(record);
ctx.SaveChanges();
Method 2:
var record = ctx.Records.FirstOfDefault();
ctx.Entry(record).State = EntityState.Deleted;
ctx.SaveChanges();
ctx.Entry(record).State = EntityState.Detached;
One of the reasons why I prefer to go with Method 2 is because in the case of setting EF or EFCore to QueryTrackingBehavior.NoTracking
, it's safer to do.
Then there's Method 3:
var record = ctx.Records.FirstOrDefault();
var entry = ctx.Entry(record);
record.DeletedOn = DateTimeOffset.Now;
entry.State = EntityState.Modified;
ctx.SaveChanges();
entry.State = EntityState.Detached;
This utilizes a soft delete approach by setting the record's DeletedOn
property, and still being able to keep the record for future use, what ever that may be. Basically, putting it in the Recycle Bin.
Also, in regards to Method 3, instead of setting the entire record to being modified:
entry.State = EntityState.Modified;
You would also simply set only the column DeletedOn
as modified:
entry.Property(x => x.DeletedOn).IsModified = true;
Just call the activity again itself using the intent. For example to refresh the layout of MainActivity, do like this:
startActivity(new Intent(MainActivity.this, MainActivity.class));
You need to use AND statement in your formula
=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")
And if both conditions are met, return 1.
You could also add more conditions in your AND statement.
None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):
var clicker = null;
$('a').click(function(e){
clicker=$(this); // capture the clicked dom object
/* ... do something ... */
e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.
It is ^
http://msdn.microsoft.com/en-us/library/ms190277.aspx
See also some code here in the middle of the page How to flip a bit in SQL Server by using the Bitwise NOT operator
Wrapping the assignment in an eval
is working for me.
# dependency on .PHONY prevents Make from
# thinking there's `nothing to be done`
set_opts: .PHONY
$(eval DOCKER_OPTS = -v $(shell mktemp -d -p /scratch):/output)
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
We can use following code
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
"Text"
– the property of textbox model
– the model object enter code here "Name"
– the value of model which to bind the textbox.Most modern tablets run honeycomb aka 3.x No phones run 3.x by default. Most tablets that currently run 2.x have less capacity and might be better of when presented with a mobile site anyway. I know it 's not flawless.. but I guess it 's a lot more accurate than the absence of mobile..
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Adding absolute will give better results
var datesArray =[
{"some":"data1","date": "2018-06-30T13:40:31.493Z"},
{"some":"data2","date": "2018-07-04T13:40:31.493Z"},
{"some":"data3","date": "2018-06-27T13:40:54.394Z"}
]
var sortedJsObjects = datesArray.sort(function(a,b){
return Math.abs(new Date(a.date) - new Date(b.date))
});
Hibernate 4 / 5:
Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));
Here is an example where both the FULL OUTER JOIN and CROSS JOIN return the same result set without NULL returned. Please note the 1 = 1 in the ON clause for the FULL OUTER JOIN:
declare @table1 table ( col1 int, col2 int )
declare @table2 table ( col1 int, col2 int )
insert into @table1 select 1, 11 union all select 2, 22
insert into @table2 select 10, 101 union all select 2, 202
select *
from @table1 t1 full outer join @table2 t2
on 1 = 1
(2 row(s) affected) (2 row(s) affected) col1 col2 col1 col2 ----------- ----------- ----------- ----------- 1 11 10 101 2 22 10 101 1 11 2 202 2 22 2 202
select *
from @table1 t1 cross join @table2 t2
col1 col2 col1 col2 ----------- ----------- ----------- ----------- 1 11 10 101 2 22 10 101 1 11 2 202 2 22 2 202 (4 row(s) affected)
Try adding this after your save call.
ConfigurationManager.RefreshSection( "appSettings" );
tmp = Regex.Replace(n, @"\W+", "");
\w
matches letters, digits, and underscores, \W
is the negated version.
Simply wrap the content using RecyclerView with the Grid Layout
Image: Recycler as GridView layout
Just use the GridLayoutManager like this:
RecyclerView.LayoutManager mRecyclerGrid=new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false);
mRecyclerView.setLayoutManager(mRecyclerGrid);
You can set how many items should appear on a row (replace the 3).
There are two ways to achieve this.
1- As already proposed u can set the background of your spinner as custom 9 patch Image with all the adjustments made into it .
android:background="@drawable/btn_dropdown"
android:clickable="true"
android:dropDownVerticalOffset="-10dip"
android:dropDownHorizontalOffset="0dip"
android:gravity="center"
If you want your Spinner to show With various different background colors i would recommend making the drop down image transparent, & loading that spinner in a relative layout with your color set in.
btn _dropdown is as:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/spinner_default" />
<item
android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/spinner_default" />
<item
android:state_pressed="true"
android:drawable="@drawable/spinner_pressed" />
<item
android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/spinner_pressed" />
<item
android:state_enabled="true"
android:drawable="@drawable/spinner_default" />
<item
android:state_focused="true"
android:drawable="@drawable/spinner_pressed" />
<item
android:drawable="@drawable/spinner_default" />
</selector>
where the various states of pngwould define your various States of spinner seleti
At the root context of the namespace is a binding with the name "comp", which is bound to a subtree reserved for component-related bindings. The name "comp" is short for component. There are no other bindings at the root context. However, the root context is reserved for the future expansion of the policy, specifically for naming resources that are tied not to the component itself but to other types of entities such as users or departments. For example, future policies might allow you to name users and organizations/departments by using names such as "java:user/alice" and "java:org/engineering".
In the "comp" context, there are two bindings: "env" and "UserTransaction". The name "env" is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor. "env" is short for environment. The J2EE recommends (but does not require) the following structure for the "env" namespace.
So the binding you did from spring or, for example, from a tomcat context descriptor go by default under java:comp/env/
For example, if your configuration is:
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="foo"/>
</bean>
Then you can access it directly using:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/foo");
or you could make an intermediate step so you don't have to specify "java:comp/env" for every resource you retrieve:
Context ctx = new InitialContext();
Context envCtx = (Context)ctx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("foo");
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
Definitely compact
is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:
[1, nil, 3, nil, nil] - [nil]
=> [1, 3]
$@
is the name of the target being generated, and $<
the first prerequisite (usually a source file). You can find a list of all these special variables in the GNU Make manual.
For example, consider the following declaration:
all: library.cpp main.cpp
In this case:
$@
evaluates to all
$<
evaluates to library.cpp
$^
evaluates to library.cpp main.cpp
For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.
# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)
# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]
# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]
# or this
v1, v2 = my_tuple_fun()
Hope this clears things up further for those that need it.
A quick definition of the "permanent generation":
"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]
In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space
if an application loads a large number of classes and/or on redeployment).
Note that PermSize
is additional to the -Xmx
value set by the user on the JVM options. But MaxPermSize
allows for the JVM to be able to grow the PermSize
to the amount specified. Initially when the VM is loaded, the MaxPermSize
will still be the default value (32mb for -client
and 64mb for -server
) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize
and MaxPermSize
to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx
setting.
You can do it inline like this
<div style="margin:0px auto"></div>
or you can do it via class
<div class="x"><div>
in your css file or between <style></style>
add this .x{margin:0px auto}
or you can simply use the center tag
<center>
<div></div>
</center>
or if you using absolute position, you can do
.x{
width: 140px;
position: absolute;
top: 0px;
left: 50%;
margin-left: -70px; /*half the size of width*/
}
From the terminal run:
sudo apt-get install python3-numpy
This package contains Numpy for Python 3.
For scipy:
sudo apt-get install python3-scipy
For for plotting graphs use pylab:
sudo apt-get install python3-matplotlib
How about jQuery cssHooks?
Maybe I do not understand the question, but what you are searching for is easily done with cssHooks
, without changing css()
function.
copy from documentation:
(function( $ ) {
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
// If not, output an error message
throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
$.cssHooks[ "someCSSProp" ] = {
get: function( elem, computed, extra ) {
// Handle getting the CSS property
},
set: function( elem, value ) {
// Handle setting the CSS value
}
};
});
})( jQuery );
Your if statements are checking for int values. raw_input
returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
A, = np.array(M.T)
depends what you mean by elegance i suppose but thats what i would do
Are we talking about standard java.io.FileReader
? Won't work, but it's not hard without it.
/src/main/resources
maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:
InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");
If the result is not null
(resource not found), feel free to wrap it in a reader:
Reader reader = new InputStreamReader(is);
It may be more useful to use a http client library like such as this
There are more things like access denied , document moved etc to handle when dealing with http.
(though, it is unlikely in this case)
I ran into this problem when trying to pull a third party package which was apparently including windows.h somewhere in it's mess of headers. Defining _WINSOCKAPI_
at the project level was much easier (not to mention more maintainable) than wading through their soup and fixing the problematic include.
If table1 is large and you don't want to lock it for the duration of the copy process, you can do a dump-and-load instead:
CREATE TABLE table2 LIKE table1;
SELECT * INTO OUTFILE '/tmp/table1.txt' FROM table1;
LOAD DATA INFILE '/tmp/table1.txt' INTO TABLE table2;
If you want to ensure bar/
ends up identical to foo/
, use rsync
instead:
rsync -a --delete foo/ bar/
If just a few things have changed, this will execute much faster than removing and re-copying the whole directory.
-a
is 'archive mode', which copies faithfully files in foo/
to bar/
--delete
removes extra files not in foo/
from bar/
as well, ensuring bar/
ends up identical-vh
for verbose and human-readablefoo
is required, otherwise rsync
will copy foo/
to bar/foo/
rather than overwriting bar/
itself.
foo/
onto the contents of bar/
, we use a slash on both. It's confusing because it won't work as expected with a slash on neither, though; rsync sneakily always interprets the destination path as though it has a slash, even though it honors an absence of a slash on the source path. So we need a slash on the source path to make it match the auto-added slash on the destination path, if we want to copy the contents of foo/
into bar/
, rather than the directory foo/
itself landing into bar/
as bar/foo
.)rsync
is very powerful and useful, if you're curious look around for what else it can do (such as copying over ssh).
CREATE TABLE #tempww (
LoginName nvarchar(max),
DBname nvarchar(max),
Username nvarchar(max),
AliasName nvarchar(max)
)
INSERT INTO #tempww
EXEC master..sp_msloginmappings
-- display results
declare @col varchar(1000)
declare @sql varchar(2000)
select @col = COALESCE(@col + ', ','') + QUOTENAME(DBname)
from #tempww Group by DBname
Set @sql='select * from (select LoginName,Username,AliasName,DBname,row_number() over(order by (select 0)) rn from #tempww) src
PIVOT (Max(rn) FOR DBname
IN ('+@col+')) pvt'
EXEC(@sql)
-- cleanup
DROP TABLE #tempww
Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing
property on yer h4
tags like this.
h4 {
-webkit-font-smoothing: antialiased;
}
You can also use subpixel-antialiased
, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.
Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.
To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.
Pretty much everything can be transported through TCP though.
(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)
In addition to what the asker's own answer already stated, it may be worth noting the following. The reason this happens is because it is possible for a class to have a method with the same signature as an interface method without implementing that method. The following code illustrates that:
public interface IFoo
{
void DoFoo();
}
public class Foo : IFoo
{
public void DoFoo() { Console.WriteLine("This is _not_ the interface method."); }
void IFoo.DoFoo() { Console.WriteLine("This _is_ the interface method."); }
}
Foo foo = new Foo();
foo.DoFoo(); // This calls the non-interface method
IFoo foo2 = foo;
foo2.DoFoo(); // This calls the interface method
You can use Class.isArray()
public static boolean isArray(Object obj)
{
return obj!=null && obj.getClass().isArray();
}
This works for both object and primitive type arrays.
For toString take a look at Arrays.toString
. You'll have to check the array type and call the appropriate toString
method.
You're trying to create a directory you don't have root access to.
For testing mongodb, I just use a directory from my user directory like:
cd
mkdir -p temp/
mongod --dbpath .
This will make a mongo database in temp/ from your current working directory
I know this post is realy old but now that some time and ant versions passed there is a way to do this with basic ant features and i thought i should share it.
It's done via a recursive macrodef that calls nested tasks (even other macros may be called). The only convention is to use a fixed variable name (element here).
<project name="iteration-test" default="execute" xmlns="antlib:org.apache.tools.ant" xmlns:if="ant:if" xmlns:unless="ant:unless">
<macrodef name="iterate">
<attribute name="list" />
<element name="call" implicit="yes" />
<sequential>
<local name="element" />
<local name="tail" />
<local name="hasMoreElements" />
<!-- unless to not get a error on empty lists -->
<loadresource property="element" unless:blank="@{list}" >
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="([^;]*).*" replace="\1" />
</filterchain>
</loadresource>
<!-- call the tasks that handle the element -->
<call />
<!-- recursion -->
<condition property="hasMoreElements">
<contains string="@{list}" substring=";" />
</condition>
<loadresource property="tail" if:true="${hasMoreElements}">
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="[^;]*;(.*)" replace="\1" />
</filterchain>
</loadresource>
<iterate list="${tail}" if:true="${hasMoreElements}">
<call />
</iterate>
</sequential>
</macrodef>
<target name="execute">
<fileset id="artifacts.fs" dir="build/lib">
<include name="*.jar" />
<include name="*.war" />
</fileset>
<pathconvert refid="artifacts.fs" property="artifacts.str" />
<echo message="$${artifacts.str}: ${artifacts.str}" />
<!-- unless is required for empty lists to not call the enclosed tasks -->
<iterate list="${artifacts.str}" unless:blank="${artifacts.str}">
<echo message="I see:" />
<echo message="${element}" />
</iterate>
<!-- local variable is now empty -->
<echo message="${element}" />
</target>
</project>
The key features needed where:
I didnt manage to make the delimiter variabel, but this may not be a major downside.
I created this class that uses RNGCryptoServiceProvider and it is flexible. Example:
var generator = new PasswordGenerator(minimumLengthPassword: 8,
maximumLengthPassword: 15,
minimumUpperCaseChars: 2,
minimumNumericChars: 3,
minimumSpecialChars: 2);
string password = generator.Generate();
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.
See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println("okay1");
FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
System.out.println("okay2");
if (fileInputStream != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
engine.eval(reader);
System.out.println("okay3");
// Invocable javascriptEngine = null;
System.out.println("okay4");
Invocable invocableEngine = (Invocable)engine;
System.out.println("okay5");
int x=0;
System.out.println("invocableEngine is : "+invocableEngine);
Object object = invocableEngine.invokeFunction("backend_message",x);
System.out.println("okay6");
}
}catch(Exception e) {
System.out.println("erroe when calling js function"+ e);
}
I was playing around with this for a little while. Turns out that the favicon is apparently handled by a node module called @scematics (at least in Angular5).
You can change your favicon in this folder:
[YourProjectName]\node_modules\@schematics\angular\application\files\__sourcedir__
In that folder there should be a favicon.ico, that's the one that is loaded. Im pretty shure this doesnt apply to everyone but it worked out for me.
Hope this helped. Happy coding! :D
without considering this to be a good idea...
select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))
Function
-- Author: bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50))
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int
Select @i=CHARINDEX('.',@NumStr)
if @i=0
begin
set @i=LEN(@NumStr)
Set @Outstr=''
end
else
begin
Set @Outstr=SUBSTRING(@NUmStr,@i,50)
Set @i=@i -1
end
Set @run=0
While @i>0
begin
if @Run=3
begin
Set @Outstr=','+@Outstr
Set @run=0
end
Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr
Set @i=@i-1
Set @run=@run + 1
end
RETURN @OutStr
END
GO
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
I just add this line exactly as it appears below (if you need a second delay):
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// Process exception
}
I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).
Yes,
You are trying to access an element of the list that does not exist.
MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
Have you got an off-by-one error?
An executor service can be used to manage multiple threads including status and completion. See http://programmingexamples.wikidot.com/executorservice
You can create a method like
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
This method will return the number of days between the 2 days.
None of the above answers satisfied me. I found the best solution is to include a hidden input before each checkbox input with the same name.
<input type="hidden" name="foo[]" value="off"/>
<input type="checkbox" name="foo[]"/>
Then on the server side, using a little algorithm you can get something more like HTML should provide.
function checkboxHack(array $checkbox_input): array
{
$foo = [];
foreach($checkbox_input as $value) {
if($value === 'on') {
array_pop($foo);
}
$foo[] = $value;
}
return $foo;
}
This will be the raw input
array (
0 => 'off',
1 => 'on',
2 => 'off',
3 => 'off',
4 => 'on',
5 => 'off',
6 => 'on',
),
And the function will return
array (
0 => 'on',
1 => 'off',
2 => 'on',
3 => 'on',
)
probably you need to sudo
into an account registered with relevant env settings :)
A simple way to do it without the use of such a complicated draw statement:
//Make a backup so that we can reset our graphics object after using it.
AffineTransform backup = g2d.getTransform();
//rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
//is the angle to rotate the image. If you want to rotate around the center of an image,
//use the image's center x and y coordinates for rx and ry.
AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
//Set our Graphics2D object to the transform
g2d.setTransform(a);
//Draw our image like normal
g2d.drawImage(image, x, y, null);
//Reset our graphics object so we can draw with it again.
g2d.setTransform(backup);
If your code must run under Python2 and Python3, use the 2to3 six library like this:
import six
six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)'
According to the API Reference:
By default the height is calculated from the offset height of the containing element. Defaults to null.
So, you can control it's height
according to the parent div using redraw
event, which is called when it changes it's size.
References
As a fallback solution, you could wrap your classes in a parent element like this:
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<div>
<!-- first-child / first-of-type starts from here -->
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
</div>
Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.
You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.
Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.
I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.
Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.
I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.
In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.
Good luck!
This could help;
Path.GetDirectoryName(Application.ExecutablePath);
also here is the reference
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :
System.setProperty("jsse.enableSNIExtension", "false");
(Courtesy to many stackoverflow answers combined together to figure this out)
The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
public static ClientConfig configureClient()
{
System.setProperty("jsse.enableSNIExtension", "false");
TrustManager[] certs = new TrustManager[]
{
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
}
};
SSLContext ctx = null;
try
{
ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
}
catch (java.security.GeneralSecurityException ex)
{
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
ClientConfig config = new DefaultClientConfig();
try
{
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
},
ctx));
}
catch (Exception e)
{
}
return config;
}
public static Client createClient()
{
return Client.create(ClientHelper.configureClient());
}
Accepted answer gives me a compiler error in Kotlin 1.3+
, I had to explicitly mention the this
keyword before ::
. Below is the working code.
lateinit var file: File
if (this::file.isInitialized) {
// file is not null
}
Or use this:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Add your UI elements inside the inner most linear layout -->
</LinearLayout>
</ScrollView>
This is a pretty old question, but perhaps this answer can still help someone else.
You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:
class Foo {
// This is a private constant
final public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.
To get nearly exactly what Alex was looking for the following code can be used:
final class Constants {
public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
class Foo {
static public app()
{
return new Constants();
}
}
The emulated constant value would be accessible like this:
Foo::app()->MYCONSTANT();
Try this
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"Login"];
[[UIApplication sharedApplication].keyWindow setRootViewController:vc];
All you need to do is, add one key in .Entitlements File.
APS Environment this key needs to be added and value should be Developement or Production as per your purpose .
Kindly check uploaded image
Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)
a <- 1:10
b <- 4
FunctionIntervalM <- function(a,b) {
seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}
FunctionIntervalM(a,b)
# 1.00 3.25 5.50 7.75 10.00
Therefore you have 4 intervals:
1.00 - 3.25
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00
You can also use a cut function
cut(a, 4)
# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5] (3.25,5.5] (5.5,7.75]
# (5.5,7.75] (7.75,10] (7.75,10] (7.75,10]
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]
Your for
loop is iterating over all of the properties of the object obj
. propt
is defined in the first line of your for loop. It is a string that is a name of a property of the obj
object. In the first iteration of the loop, propt
would be "name".
Since NumPy version 1.13 it contains an isnat
function:
>>> import numpy as np
>>> np.isnat(np.datetime64('nat'))
True
It also works for arrays:
>>> np.isnat(np.array(['nat', 1, 2, 3, 4, 'nat', 5], dtype='datetime64[D]'))
array([ True, False, False, False, False, True, False], dtype=bool)
You can simply set the window state
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
In case you are behind corporate proxy then try using following command
pip install --proxy=http://www-YOUR_PROXY_URL.com:PROXY_PORT BeautifulSoup4
You have just add FormsModule
and import the FormsModule
in your app.module.ts
file.
import { FormsModule } from '@angular/forms';
imports: [
BrowserModule, FormsModule
],
Just add the above two lines in your app.module.ts
. It's working fine.
I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.
You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.
if( param.indexOf != undefined ) {
// we have a string or other object that
// happens to have a function named indexOf
}
You can test this in your browser console:
> (3).indexOf == undefined;
true
> "".indexOf == undefined;
false
Do I really have to manually call datetime(d.year, d.month, d.day)
No, you'd rather like to call
date_to_datetime(dt)
which you can implement once in some utils/time.py
in your project:
from typing import Optional
from datetime import date, datetime
def date_to_datetime(
dt: date,
hour: Optional[int] = 0,
minute: Optional[int] = 0,
second: Optional[int] = 0) -> datetime:
return datetime(dt.year, dt.month, dt.day, hour, minute, second)
In httpd.conf file you need to remove #
#LoadModule rewrite_module modules/mod_rewrite.so
after removing # line will look like this:
LoadModule rewrite_module modules/mod_rewrite.so
And Apache restart
I just patch nginx binary replacing path /var/log/nginx/error.log
and other with local path.
$ perl -pi \
-e 's@/var/log/nginx/@_var_log_nginx/@g;' \
-e 's@/var/lib/nginx/@_var_lib_nginx/@g;' \
-e 's@/var/run/nginx.pid@_var_run/nginx.pid@g;' \
-e 's@/run/nginx.pid@_run/nginx.pid@g;' \
< /usr/sbin/nginx > nginx
$ chmod +x nginx
$ mkdir _var_log_nginx _var_lib_nginx _var_run _run
$ ./nginx -p . -c nginx.conf
It works for testing.
I used this library called Parser. It worked for what I needed.
import React, { Component } from 'react';
import Parser from 'html-react-parser';
class MyComponent extends Component {
render() {
<div>{Parser(this.state.message)}</div>
}
};
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.
If you are adding different UIGestureRecognizer
on different UIView
s and want to distinguish in the action method then you can check the property view in the sender parameter which will give you the sender view.
Try this..
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
Try the element:
$(td).find('a').attr('disabled', 'disabled');
Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.
Firefox doesn't seem to play nice. This example works:
<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>
$('#a1').attr('disabled', 'disabled');
$(document).on('click', 'a', function(e) {
if ($(this).attr('disabled') == 'disabled') {
e.preventDefault();
}
});
Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.
It's the "null coalescing operator", added in php 7.0. The definition of how it works is:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
So it's actually just isset()
in a handy operator.
Those two are equivalent1:
$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';
Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce
In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
And original RFC https://wiki.php.net/rfc/isset_ternary
EDIT: As this answer gets a lot of views, little clarification:
1There is a difference: In case of ??
, the first expression is evaluated only once, as opposed to ? :
, where the expression is first evaluated in the condition section, then the second time in the "answer" section.