sudo eclipse
The issue for me was related to @maximilianus's question - in that eclipse was unable to locate the artifacts on my machine.
Turns out all I had to do was run ubuntu as super user, and eclipse could access the /root/.m2/ directory
(Not sure this is good practice, but it solved a problem I've spent hours on)
Edit: This is not definitely good practice, instead I setup my environment all over again, as a normal user rather than root, and it worked fine! (Learning Linux)
Hosting asp.net 4.5/4.5.1 Web application on Local IIS 1)Be Sure IIS Installation before Visual Installation Installataion then aspnet_regiis will already registerd with IIS
If Not Install IIS and then Register aspnet_regiis with IIS by cmd Editor
For VS2012 and 32 bit OS Run Below code on command editor :
1)Install IIS First & then
2)
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i
For VS2012 and 64 bit OS Below code on command editor:
1)Install IIS First & then
2)
cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i
BY Following Above Steps Current Version of VS2012 registered with IIS Hosting (VS2012 Web APP)
Create VS2012 Web Application(WebForm/MVC) then Build Application Right Click On WebApplication(WebForm/MVC) go to 'Properties' Click On 'Web' Tab on then 'Use Local IIS Web Server' Then Uncheck 'Use IIS Express' (If Visul Studio 2013 Select 'Local IIS' from Dropdown) Provide Project Url like "http://localhost/MvcDemoApp" Then Click On 'Create Virtual Directory' Button Then Open IIS by Prssing 'Window + R' Run Command and type 'inetmgr' and 'Enter' (or 'OK' Button) Then Expand 'Sites->Default Web Site' you Hosted Successfully. If Still Gets any Server Error like 'The resource cannot be found.' Then Include following code in web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
And Run Application
If still problem occurs Check application pool by : In iis Right click on application->Manage Application->Advanced setting->General. you see the application pool. then close advance setting window. click on 'Application Pools' you will see the all application pools in middle window. Right click on application pool in which application hosted(DefaultAppPool). click 'Basic Setting' -> Change .Net FrameWork Version to->.Net FrameWork v4.0.30349
There are 3 sources of variables in Ansible:
Variables gathered from facts. You can get them by running command: ansible -m setup hostname
Built-in (pre-defined) Ansible variables (AKA 'magic' variables). They are documented in Ansible documentation: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts
Here is the list extracted from Ansible 1.9 documentation:
Apart from the other already mentioned valid use cases std::weak_ptr
is an awesome tool in a multithreaded environment, because
std::shared_ptr
in conjunction with std::weak_ptr
is safe against dangling pointers - in opposite to std::unique_ptr
in conjunction with raw pointers std::weak_ptr::lock()
is an atomic operation (see also About thread-safety of weak_ptr)Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join()
etc is omitted, the threads would have to be handled differently in a real implementation etc)
// a simplified class to hold the thumbnail and data
struct ImageData {
std::string path;
std::unique_ptr<YourFavoriteImageLibData> image;
};
// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
for( auto& imageData : imagesToLoad )
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas =
splitImageDatas( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.
You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas
field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.
The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad
would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr
in conjunction with std::weak_ptr
.
// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
for( auto& imageDataWeak : imagesToLoad ) {
std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
if( !imageData )
continue;
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas =
splitImageDatasToWeak( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.
If you want to finish and just add a resultCode
(without data), you can call setResult(int resultCode)
before finish()
.
For example:
...
if (everything_OK) {
setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
finish();
}
else {
setResult(Activity.RESULT_CANCELED); // some error ...
finish();
}
...
Then in your calling activity, check the resultCode
, to see if we're OK.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == someCustomRequestCode) {
if (resultCode == Activity.RESULT_OK) {
// OK!
}
else if (resultCode = Activity.RESULT_CANCELED) {
// something went wrong :-(
}
}
}
Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode)
.
Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -V
Python 3.5.3
The following bash code will pass $file to command where $file will represent every file in /dir
for file in /dir/*
do
cmd [option] "$file" >> results.out
done
Example
el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
Well done, you've only just started using MVC and you've found its first major flaw.
You don't really want to be converting it to JSON in the view, and you don't really want to convert it in the controller, as neither of these locations make sense. Unfortunately, you're stuck with this situation.
The best thing I've found to do is send the JSON to the view in a ViewModel, like this:
var data = somedata;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);
return View("viewname", viewModel);
then use
<%= Model.JsonData %>
in your view. Be aware that the standard .NET JavaScriptSerializer is pretty crap.
doing it in the controller at least makes it testable (although not exactly like the above - you probably want to take an ISerializer as a dependency so you can mock it)
Update also, regarding your JavaScript, it would be good practice to wrap ALL the widget JS you have above like so:
(
// all js here
)();
this way if you put multiple widgets on a page, you won't get conflicts (unless you need to access the methods from elsewhere in the page, but in that case you should be registering the widget with some widget framework anyway). It may not be a problem now, but it would be good practice to add the brackets now to save yourself muchos effort in the future when it becomes a requirement, it's also good OO practice to encapsulate the functionality.
Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true
In Sender
Sender.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
“includeViewParams=true”
in return String of click button event
Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrDataSender.xhtml
<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
<p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??"
ajax="false"/>
</p:dataTable>
In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID
Sender_MB.java
public String clickBtnDetail(sender_DTO sender_dto) {
this._strID = sender_dto.getStrID();
return "Receiver?faces-redirect=true&includeViewParams=true";
}
The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*
In Recever
Receiver.xhtml
<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>
It will get param ID from sender View and assign to receiver_MB._strID
Receiver.xhtml
<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />
into f:metadata tag
Receiver.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
type="preRenderView" />
</f:metadata>
Now we want to use this param in our read database method, it is available to use
Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
if (FacesContext.getCurrentInstance().isPostback()) {
return;
}
readFromDatabase();
}
private void readFromDatabase() {
//use _strID to read and set property
}
One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:
npm cache clean
And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.
This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.
For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.
It seems c:if
cannot by itself be followed by c:otherwise
.
The correct solution is as follows:
<c:choose>
<c:when test="#{some.test}">
<p>some.test is true</p>
</c:when>
<c:otherwise>
<p>some.test is not true</p>
</c:otherwise>
</c:choose>
You can add additional c:when
tests in as necessary.
For Bootstrap 4 it could be done with class="form-group" style="display: flex"
<div class="form-group" style="display: flex">
<label>Topjava comment:</label>
<input class="form-control" type="checkbox"/>
</div>
Nowadays - using C++11 - you can use enum class for this:
enum class Color { RED, BLUE, WHITE };
AFAII this does exactly what you want.
Is there an option like "treat ^M as newline when diffing" ?
There will be one with Git 2.16 (Q1 2018), as the "diff
" family of commands learned to ignore differences in carriage return at the end of line.
See commit e9282f0 (26 Oct 2017) by Junio C Hamano (gitster
).
Helped-by: Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 10f65c2, 27 Nov 2017)
diff:
--ignore-cr-at-eol
A new option
--ignore-cr-at-eol
tells the diff machinery to treat a carriage-return at the end of a (complete) line as if it does not exist.Just like other "
--ignore-*
" options to ignore various kinds of whitespace differences, this will help reviewing the real changes you made without getting distracted by spuriousCRLF<->LF
conversion made by your editor program.
Plain old Javascript:
<script type="text/javascript">
function changeHiddenInput (objDropDown)
{
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
}
</script>
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.
It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR
warning and problem at starting Firefox using Xfvb.
After adding +extension RANDR
it worked again.
$ vim /etc/init/xvfb.conf
#!upstart
description "Xvfb Server as a daemon"
start on filesystem and started networking
stop on shutdown
respawn
env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid
exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1
You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:
<?php
$mail = new PHPMailer(true);
// Send mail using Gmail
if($send_using_gmail){
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "[email protected]"; // GMAIL username
$mail->Password = "your-gmail-password"; // GMAIL password
}
// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";
try{
$mail->Send();
echo "Success!";
} catch(Exception $e){
// Something went bad
echo "Fail :(";
}
?>
Read more about PHPMailer
here.
From git checkout
's usage:
-2, --ours checkout our version for unmerged files
-3, --theirs checkout their version for unmerged files
-m, --merge perform a 3-way merge with the new branch
When resolving merge conflicts, you can do git checkout --theirs some_file
, and git checkout --ours some_file
to reset the file to the current version and the incoming versions respectively.
If you've done git checkout --ours some_file
or git checkout --theirs some_file
and would like to reset the file to the 3-way merge version of the file, you can do git checkout --merge some_file
.
Connect to the database with the "system" user, and execute the following command:
show parameter service_name
It is used to log (anything you pass it) to the Firebug console. The main usage would be to debug your JavaScript code.
Export a certificate from a keystore:
keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
The output file needs to be opened in binary mode:
f = open('varstor.txt','w')
needs to be:
f = open('varstor.txt','wb')
Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.
This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.
Maybe you can now understand why your approach so far could never work out.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
I believe this would work. It takes const char*'s as a parameter.
//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
//ASSERT(find != NULL);
//ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
//search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
//replace the found string with the replacement
source.replace( pos, findLen, replace );
//the next line keeps you from searching your replace string,
//so your could replace "hello" with "hello world"
//and not have it blow chunks.
pos += replaceLen;
}
}
This is working
<form name="myform" ng-submit="create()">
<input type="number"
name="price_field"
ng-model="price"
require
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
<span ng-show="myform.price_field.$error.pattern">Not valid number!</span>
<input type="submit" class="btn">
</form>
I struggled to make this work as well, but here are some pointers:
http
, e.g. http://example.com/*
Once all of this above was resolved, the maps displayed as expected.
On top of all the other explanations, I believe you're using equal "="
sign, instead of colon ":"
:
<span style="border:1px solid red;text-align=center">
It should be:
<span style="border:1px solid red;text-align:center">
CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)
You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.
A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/
You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.
In my case, database returned latin1
, when my browser expected utf8
.
So for MySQLi I did:
mysqli_set_charset($dblink, "utf8");
See http://php.net/manual/en/mysqli.set-charset.php for more info
You can create a getter and then override that getter. It's particularly useful if the variable you are overriding is a sub-class of itself. Imagine your super class has an Object
member but in your sub-class this is now more defined to be an Integer
.
class Dad
{
private static final String me = "dad";
protected String getMe() {
return me;
}
public void printMe()
{
System.out.println(getMe());
}
}
class Son extends Dad
{
private static final String me = "son";
@Override
protected String getMe() {
return me;
}
}
public void doIt()
{
new Son().printMe(); //Prints "son"
}
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))
You can use "transparent" as a colour. In some versions of IE, that comes up as black, but I've not tested it out since the IE6 days.
http://www.researchkitchen.de/blog/archives/css-bordercolor-transparent.php
Click Run
Click Debug ...
New Java Application
Click Arguments tab
in the 2nd box (VM Arguments) add the -D entry
-Xdebug -verbose:gc -Xbootclasspath/p:jar/vbjorb.jar;jar/oracle9.jar;classes;jar/mq.jar;jar/xml4j.jar -classpath -DORBInitRef=NameService=iioploc://10.101.2.94:8092/NameService
etc...
I had a similar problem. I got an exception "Type is not resolved for member 'Microsoft.IdentityModel.Claims.ClaimsPrincipal, Microsoft.IdentityModel, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35'.".
I tried to run the ASP.NET application from Visual Studio, which was a reference to a local copy of Microsoft.IdentityModel.dll.
I did not want to install the SDK and I had to copy the library to the directory "C: \ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0" and restart Visual Studio.
if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.
If you don't understand anything then download vcredist_x86.exe from http://www.microsoft.com/en-us/download/details.aspx?id=8328 . It will solve your problem.
Maybe it's interesting to check out Google Collections, e.g. the videos that they have on their page. They provide various ways to initialize maps and sets, and provide immutable collections as well.
Update: This library is now named Guava.
This would work:
curl -I somesite.com | perl -n -e '/^Location: (.*)$/ && print "$1\n"'
The actual code to cast away the const-ness of your pointer would be:
BoxT<T> * nonConstObj = const_cast<BoxT<T> *>(constObj);
But note that this really is cheating. A better solution would either be to figure out why you want to modify a const object, and redesign your code so you don't have to.... or remove the const declaration from your vector, if it turns out you don't really want those items to be read-only after all.
I am using Idea 8. in your module dependancies tab (in the project structure dialog). Add a "Module Library". There you can select a Jar Directory to add. Then make sure the run profile is using the Classpath and JDK of the correct module when it runs (this is in the run config dialog.
This method checks if a String contains a special character (based on your definition).
/**
* Returns true if s contains any character other than
* letters, numbers, or spaces. Returns false otherwise.
*/
public boolean containsSpecialCharacter(String s) {
return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");
}
You can use the same logic to count special characters in a string like this:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
theCount++;
}
}
return theCount;
}
Another approach is to put all the special chars in a String and use String.contains:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
String specialChars = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
for (int i = 0; i < s.length(); i++) {
if (specialChars.contains(s.substring(i, 1))) {
theCount++;
}
}
return theCount;
}
NOTE: You must escape the backslash and "
character with a backslashes.
The above are examples of how to approach this problem in general.
For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.
ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.setMessage("loading");
pd.show();
And that's all you need.
I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon
@click="method1(); $emit('emit1'); $emit('emit2');"
Do you have the SSH2 extension available?
Docs: http://www.php.net/manual/en/function.ssh2-exec.php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
The actual problem is with your
showList function.
There is an extra ')'
after 'visible'.
Remove that and it will work fine.
function showList()
{
if (document.getElementById("favSports").style.visibility == "hidden")
{
// document.getElementById("favSports").style.visibility = "visible");
// your code
document.getElementById("favSports").style.visibility = "visible";
// corrected code
}
}
You can't use CSS to disable autocomplete, but you can use HTML:
<input type="text" autocomplete="false" />
Technically you can replace false
with any invalid value and it'll work. This iOS the only solution I've found which also works in Edge.
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
Use the File.WriteAllText
method. It creates the file if it doesn't exist and overwrites it if it exists.
lst[-1]
is the best approach, but with general iterables, consider more_itertools.last
:
Code
import more_itertools as mit
mit.last([0, 1, 2, 3])
# 3
mit.last(iter([1, 2, 3]))
# 3
mit.last([], "some default")
# 'some default'
Here's a solution for find/replace in all files of a given directory. Basically I took the answer provided by sepp2k and expanded it.
# First set the files to search/replace in
files = Dir.glob("/PATH/*")
# Then set the variables for find/replace
@original_string_or_regex = /REGEX/
@replacement_string = "STRING"
files.each do |file_name|
text = File.read(file_name)
replace = text.gsub!(@original_string_or_regex, @replacement_string)
File.open(file_name, "w") { |file| file.puts replace }
end
I use this solution and it works fine on all devices:
if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
//is_mobile
}
This is a bit late but I know it will help someone:
If you are using datetimepicker
make sure you include the right CSS and JS files. datetimepicker
uses(Take note of their names);
and
On the above question asked by @mindfreak,The main problem is due to the imported files.
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
By default, the access modifier for a class is internal
. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.
You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:
Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.
If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:
... and the digits are actually the id-s of the different attribute values, that you want to set.
Swift 4 and Constraints
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
$_SERVER["PHP_SELF"];
will give you the current filename and its path, but basename(__FILE__)
should give you the filename that it is called from.
So
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
should do it.
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
Look at the keys and indentation in your print_r
:
echo $myarray[0]['email'];
echo $myarray[0]['gender'];
...etc
Try using:
@ECHO off
ECHO Hello World!
START /MAX D:\SA\pro\hello.txt
I had the same problem - and I have read all these answers, but unfortunately none of them worked for me. Eventually I tried removing this line
%\usepackage[latin1]{inputenc}
and all errors disappeared.
like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:
-- create a test table
create table test (
a text
)
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works:
update test set a = cast ( a as nvarchar(max)) + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added
hope that helps
Try this
div{_x000D_
display: block;_x000D_
display: -webkit-box;_x000D_
height: 20px;_x000D_
margin: 3px auto;_x000D_
font-size: 14px;_x000D_
line-height: 1.4;_x000D_
-webkit-line-clamp: 1;_x000D_
-webkit-box-orient: vertical;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
the property text-overflow: ellipsis add ... and line-clamp show the number of lines.
I have a folder /fields full of files with a single class each, ex:
fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class
Drop this in fields/index.js to export each class:
var collectExports, fs, path,
__hasProp = {}.hasOwnProperty;
fs = require('fs');
path = require('path');
collectExports = function(file) {
var func, include, _results;
if (path.extname(file) === '.js' && file !== 'index.js') {
include = require('./' + file);
_results = [];
for (func in include) {
if (!__hasProp.call(include, func)) continue;
_results.push(exports[func] = include[func]);
}
return _results;
}
};
fs.readdirSync('./fields/').forEach(collectExports);
This makes the modules act more like they would in Python:
var text = new Fields.Text()
var checkbox = new Fields.Checkbox()
Maybe my answer is too late but this can help others.
You can enclose it with another select statement and use where clause to it.
SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0
calcAlias is the alias column that was calculated.
An additional note. If you check uncompressed javascript file, you will find the condition:
if(window.Tether === undefined) {
throw new Error('Bootstrap tooltips require Tether (http://github.hubspot.com/tether)')
}
So the error message contains the required information.
You can download the archive from that link.
Uncompressed version:
https://rawgit.com/HubSpot/tether/master/src/js/tether.js https://rawgit.com/HubSpot/tether/master/dist/css/tether.css
I've written just this to execute compiling and run the file after, plus fileinputname = fileoutputname on windowsmashines, if your compilerpath is registred in the windows PATH-var:
NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
set LEN~ strrfind $(FILE_NAME) .
set EXENAME ~ substr 0 $(LEN) $(FILE_NAME)
set $(EXENAME) = $(EXENAME).exe
c++.exe "$(FILE_NAME)" -o "$(EXENAME)"
"$(EXENAME)"
should work for any compiler if you change c++.exe to what you want
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
You should check for (args == null || args.length == 0)
. Although the null
check isn't really needed, it is a good practice.
Full days between end of month and start of today, including the last day of the month:
SELECT LAST_DAY (TRUNC(SysDate)) - TRUNC(SysDate) + 1 FROM dual
Days between using exact time:
SELECT SysDate - TO_DATE('2018-01-01','YYYY-MM-DD') FROM dual
Bash allows you to place strings adjacently, and they'll just end up being glued together.
So this:
$ echo "Hello"', world!'
produces
Hello, world!
The trick is to alternate between single and double-quoted strings as required. Unfortunately, it quickly gets very messy. For example:
$ echo "I like to use" '"double quotes"' "sometimes"
produces
I like to use "double quotes" sometimes
In your example, I would do it something like this:
$ dbtable=example
$ dbload='load data local infile "'"'gfpoint.csv'"'" into '"table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"'"'"' LINES "'TERMINATED BY "'"'\n'"'" IGNORE 1 LINES'
$ echo $dbload
which produces the following output:
load data local infile "'gfpoint.csv'" into table example FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "'\n'" IGNORE 1 LINES
It's difficult to see what's going on here, but I can annotate it using Unicode quotes. The following won't work in bash – it's just for illustration:
dbload=
‘load data local infile "
’“'gfpoint.csv'
”‘" into
’“table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '
”‘"
’“' LINES
”‘TERMINATED BY "
’“'\n'
”‘" IGNORE 1 LINES
’
The quotes like “ ‘ ’ ” in the above will be interpreted by bash. The quotes like " '
will end up in the resulting variable.
If I give the same treatment to the earlier example, it looks like this:
$ echo
“I like to use
”‘
"double quotes"
’“
sometimes
”
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Using padding in the layout of Child View.
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/backage_text"
android:textColor="#999999"
>
</TextView>
backage_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"/>
<corners android:radius="2dp"/>
<stroke
android:width="1dp"
android:color="#999999"/>
<padding
android:bottom="5dp"
android:left="10dp"
android:right="10dp"
android:top="5dp" />
</shape>
That would be the modulo operator, which produces the remainder of the division of two numbers.
if you wanna remove attributes for all files in all folders on whole flash drive do this:
attrib -r -s -h /S /D
this command will remove attrubutes for all files folders and subfolders:
-read only -system file -is hidden -Processes matching files and all subfolders. -Processes folders as well
you can use:
define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";
Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.
static
change the performance?The line in question:
uint64_t size = atol(argv[1])<<20;
I would look at the assembly generated for accessing size
and see if there are extra steps of pointer indirection involved for the non-static version.
Since there is only one copy of the variable whether it was declared static
or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.
Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static
? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.
When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.
For port 80 (which was the original question), Daniel is exactly right. I recently moved to https
and had to switch from iptables
to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I
Created an SSL Certificate Signing Request (CSR) via OpenSSL
openssl genrsa 2048 > private-key.pem
openssl req -new -key private-key.pem -out csr.pem
Changed the location
in /etc/nginx/conf.d/example_ssl.conf
to
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
}
Formatted the cert for nginx by cat
-ing the individual certs together and linked to it in my nginx example_ssl.conf
file (and uncommented stuff, got rid of 'example' in the name,...)
ssl_certificate /etc/nginx/ssl/cert_bundle.cert;
ssl_certificate_key /etc/nginx/ssl/private-key.pem;
Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.
The max length of a string on my machine is 1,073,741,791.
You see, Strings aren't limited by integer as is commonly believed.
Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.
Now, here's something you're welcome to try yourself.
Create a new C# console app in Visual Studio and then copy/paste the main method here:
static void Main(string[] args)
{
Console.WriteLine("String test, by Nicholas John Joseph Taylor");
Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");
Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");
Console.WriteLine("\nThe test starts ...now:\n");
int Length = 0;
string s = "";
int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.
LoopPoint:
// Make a string appendage the length of the value of Increment
StringBuilder StringAppendage = new StringBuilder();
for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
{
StringAppendage.Append("0");
}
// Repeatedly append string appendage until an out of memory exception is thrown.
try
{
if (Increment > 0)
while (Length < int.MaxValue)
{
Length += Increment;
s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment
Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
}
}
catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
{
Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Length -= Increment;
Increment /= 10;
Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");
}
catch (Exception ex2)
{
Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Console.WriteLine("Press a key to continue...");
Console.ReadKey();
}
if (Increment > 0)
{
goto LoopPoint;
}
Console.WriteLine("Test complete.");
Console.WriteLine("\nThe max length of a string is " + s.Length + ".");
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
My results were as follows:
String test, by Nicholas John Joseph Taylor
Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.
This is a quickish test to narrow down results to find the max supported length of a string.
The test starts ...now:
s.Length = 1000000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.
The max length of a string is 1073741791.
Press any key to continue.
The max length of a string on my machine is 1073741791.
I'd appreciate it very much if people could post their results as a comment below.
It will be interesting to learn if people get the same or different results.
A way that has worked for me personally, is using the recyclerview's adapter methods to deal with changes in it's items.
It would go in a way similar to this, create a method in your custom recycler's view somewhat like this:
public void modifyItem(final int position, final Model model) {
mainModel.set(position, model);
notifyItemChanged(position);
}
As you are dealing with a string array, have you considered Join?
If Len(Join(FileNamesList)) > 0 Then
Let's think a little different, You can use static parameters:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function func() {
echo global::$foo;
}
As for this question, I'd say the wiki has already provided detailed and easy-understanding explanations. I will just quote the most significant here.
In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
- Using a service locator pattern Using dependency injection, for example Constructor injection Parameter injection Setter injection Interface injection;
- Using a contextualized lookup;
- Using template method design pattern;
- Using strategy design pattern
As for Dependency Injection
dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
A compilation in C++ is done in 2 major phases:
The first is the compilation of "source" text files into binary "object" files: The CPP file is the compiled file and is compiled without any knowledge about the other CPP files (or even libraries), unless fed to it through raw declaration or header inclusion. The CPP file is usually compiled into a .OBJ or a .O "object" file.
The second is the linking together of all the "object" files, and thus, the creation of the final binary file (either a library or an executable).
Where does the HPP fit in all this process?
The compilation of each CPP file is independent from all other CPP files, which means that if A.CPP needs a symbol defined in B.CPP, like:
// A.CPP
void doSomething()
{
doSomethingElse(); // Defined in B.CPP
}
// B.CPP
void doSomethingElse()
{
// Etc.
}
It won't compile because A.CPP has no way to know "doSomethingElse" exists... Unless there is a declaration in A.CPP, like:
// A.CPP
void doSomethingElse() ; // From B.CPP
void doSomething()
{
doSomethingElse() ; // Defined in B.CPP
}
Then, if you have C.CPP which uses the same symbol, you then copy/paste the declaration...
Yes, there is a problem. Copy/pastes are dangerous, and difficult to maintain. Which means that it would be cool if we had some way to NOT copy/paste, and still declare the symbol... How can we do it? By the include of some text file, which is commonly suffixed by .h, .hxx, .h++ or, my preferred for C++ files, .hpp:
// B.HPP (here, we decided to declare every symbol defined in B.CPP)
void doSomethingElse() ;
// A.CPP
#include "B.HPP"
void doSomething()
{
doSomethingElse() ; // Defined in B.CPP
}
// B.CPP
#include "B.HPP"
void doSomethingElse()
{
// Etc.
}
// C.CPP
#include "B.HPP"
void doSomethingAgain()
{
doSomethingElse() ; // Defined in B.CPP
}
include
work?Including a file will, in essence, parse and then copy-paste its content in the CPP file.
For example, in the following code, with the A.HPP header:
// A.HPP
void someFunction();
void someOtherFunction();
... the source B.CPP:
// B.CPP
#include "A.HPP"
void doSomething()
{
// Etc.
}
... will become after inclusion:
// B.CPP
void someFunction();
void someOtherFunction();
void doSomething()
{
// Etc.
}
In the current case, this is not needed, and B.HPP has the doSomethingElse
function declaration, and B.CPP has the doSomethingElse
function definition (which is, by itself a declaration). But in a more general case, where B.HPP is used for declarations (and inline code), there could be no corresponding definition (for example, enums, plain structs, etc.), so the include could be needed if B.CPP uses those declaration from B.HPP. All in all, it is "good taste" for a source to include by default its header.
The header file is thus necessary, because the C++ compiler is unable to search for symbol declarations alone, and thus, you must help it by including those declarations.
One last word: You should put header guards around the content of your HPP files, to be sure multiple inclusions won't break anything, but all in all, I believe the main reason for existence of HPP files is explained above.
#ifndef B_HPP_
#define B_HPP_
// The declarations in the B.hpp file
#endif // B_HPP_
or even simpler (although not standard)
#pragma once
// The declarations in the B.hpp file
python 3.2
>>>> from itertools import chain
>>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
[7, 6, 5, 4, 3, 2, 1]
##### eg contain 2 list within a list. so if you want to use set() function
you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]
>>> res= list(chain(*eg)) # [1, 2, 3, 4, 4, 5, 6, 7]
>>> res1= set(res) # [1, 2, 3, 4, 5, 6, 7]
>>> res1= sorted(res1,reverse=True)
If all the cells are under one column, you could just filter the column and then select "(blank)" and then insert any value into the cells. But be careful, press "alt + 4" to make sure you are inserting value into the visible cells only.
there are two ways to do this in jquery depending what you are looking for..
using jquery you can do
//this will wait for the text assets to be loaded before calling this (the dom.. css.. js)
$(document).ready(function(){...});
//this will wait for all the images and text assets to finish loading before executing
$(window).load(function(){...});
This with no warnings!
HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
for (Object o : meMap.keySet()) {
Toast.makeText(getBaseContext(), meMap.get(o.toString()),
Toast.LENGTH_SHORT).show();
}
If you want to run the script in adb shell, then I am trying to do the same, but with an application. I think you can use "am start" command
usage: am [subcommand] [options]
start an Activity: am start [-D] [-W] <INTENT>
-D: enable debugging
-W: wait for launch to complete
**start a Service: am startservice <INTENT>**
send a broadcast Intent: am broadcast <INTENT>
start an Instrumentation: am instrument [flags] <COMPONENT>
-r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
-e <NAME> <VALUE>: set argument <NAME> to <VALUE>
-p <FILE>: write profiling data to <FILE>
-w: wait for instrumentation to finish before returning
start profiling: am profile <PROCESS> start <FILE>
stop profiling: am profile <PROCESS> stop
start monitoring: am monitor [--gdb <port>]
--gdb: start gdbserv on the given port at crash/ANR
<INTENT> specifications include these flags:
[-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
[-c <CATEGORY> [-c <CATEGORY>] ...]
[-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
[--esn <EXTRA_KEY> ...]
[--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
[-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
[-n <COMPONENT>] [-f <FLAGS>]
[--grant-read-uri-permission] [--grant-write-uri-permission]
[--debug-log-resolution]
[--activity-brought-to-front] [--activity-clear-top]
[--activity-clear-when-task-reset] [--activity-exclude-from-recents]
[--activity-launched-from-history] [--activity-multiple-task]
[--activity-no-animation] [--activity-no-history]
[--activity-no-user-action] [--activity-previous-is-top]
[--activity-reorder-to-front] [--activity-reset-task-if-needed]
[--activity-single-top]
[--receiver-registered-only] [--receiver-replace-pending]
[<URI>]
Code::Blocks is cross-platform, using the wxWidgets library. It's the one I use.
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param()
without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null'
instead of null
, doesn't work with empty parameters (?foo=&bar=x
), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
In my case, simply using the uxterm
command instead of xterm
solved the problem. It's available in /opt/X11/bin/uxterm
by installing the XQuartz package provided by Apple.
new java.sql.Date(Calendar.getInstance().getTimeInMillis());
For simplicity, If you need to default to some value if nil you can use:
@something.nil? = "No" || "Yes"
A callback is a method that is scheduled to be executed when a condition is met.
An "real world" example is a local video game store. You are waiting for Half-Life 3. Instead of going to the store every day to see if it is in, you register your email on a list to be notified when the game is available. The email becomes your "callback" and the condition to be met is the game's availability.
A "programmers" example is a web page where you want to perform an action when a button is clicked. You register a callback method for a button and continue doing other tasks. When/if the user cicks on the button, the browser will look at the list of callbacks for that event and call your method.
A callback is a way to handle events asynchronously. You can never know when the callback will be executed, or if it will be executed at all. The advantage is that it frees your program and CPU cycles to perform other tasks while waiting for the reply.
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
In my case what happened was that the user I was using had no ownership over the directory. I simply had to change ownership of the directory to that user. For example if user is ubuntu:
chown ubuntu:ubuntu -R directory-in-question
cd directory-in-question/
git clone <git repo comes here >
You have several techniques to do it.
This post - read the part about the revert will explain in details what we want to do and how to do it.
Here is the most simple solution to your problem:
# Checkout the desired branch
git checkout <branch>
# Undo the desired commit
git revert <commit>
# Update the remote with the undo of the code
git push origin <branch>
The revert command will create a new commit with the undo of the original commit.
This is known as type assertion
in golang, and it is a common practice.
Here is the explanation from a tour of go:
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
NOTE: value i
should be interface type.
Even if i
is an interface type, []i
is not interface type. As a result, in order to convert []i
to its value type, we have to do it individually:
// var items []i
for _, item := range items {
value, ok := item.(T)
dosomethingWith(value)
}
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
This solved my problem. Uninstall app from device and run it again via Android studio.
The ::
is called scope resolution operator.
Can be used like this:
::
identifier
class-name ::
identifier
namespace ::
identifier
You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017
I guess you will have to use this code when calling the "mEdit" your EditText object :
myActivity.this.mEdit.getText().toString()
Just make sure that the compiler know which EditText
to call and use.
enumerate
is what you are looking for.
You might also be interested in unpacking:
# The pattern
x, y, z = [1, 2, 3]
# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
print(x) # prints the numbers 28, 4, 1990
# and also
for index, (x, y) in enumerate(l):
print(x) # prints the numbers 28, 4, 1990
Also, there is itertools.count()
so you could do something like
import itertools
for index, el in zip(itertools.count(), [28, 4, 1990]):
print(el) # prints the numbers 28, 4, 1990
With the official Material Components library you can use the MaterialButton
applying a Widget.MaterialComponents.Button.Icon
style.
Something like:
<com.google.android.material.button.MaterialButton
android:layout_width="48dp"
android:layout_height="48dp"
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/ic_add"
app:iconSize="24dp"
app:iconPadding="0dp"
android:insetLeft="0dp"
android:insetTop="0dp"
android:insetRight="0dp"
android:insetBottom="0dp"
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
/>
Currently the app:iconPadding="0dp"
,android:insetLeft
,android:insetTop
,android:insetRight
,android:insetBottom
attributes are needed to center the icon on the button avoiding extra padding space.
Use the app:shapeAppearanceOverlay
attribute to get rounded corners. In this case you will have a circle.
<style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
The final result:
In general, i.e. unlimited decimal places:
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$
Group rows together using the <tbody>
tag and then apply style.
<table>
<tr><td>No Style here</td></tr>
<tbody class="red-outline">
<tr><td>Style me</td></tr>
<tr><td>And me</td></tr>
</tbody>
<tr><td>No Style here</td></tr>
</table>
And the css in style.css
.red-outline {
outline: 1px solid red;
}
This function will filter an object based on a list of keys, its more efficient than the previous answer as it doesn't have to use Array.filter before calling reduce. so its O(n) as opposed to O(n + filtered)
function filterObjectByKeys (object, keys) {
return Object.keys(object).reduce((accum, key) => {
if (keys.includes(key)) {
return { ...accum, [key]: object[key] }
} else {
return accum
}
}, {})
}
Please make sure you are not trying to open and close the database repeatedly either from main thread or background thread.
Make a singleton class in your application and try to create and open data from this class only.
Is guarantees you that database open call is made only when it does not exist.
In your entire application use the same approach of getting sqLiteDatabase object when it is required.
I used below code and my problem is solved now after 1.5 days.
...............................................................
In Your Activity class onCreate() method
public class MainActivity extends AppCompatActivity {
private AssetsDatabaseHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
helper = AssetsDatabaseHelper.getInstance(this);
sqLiteDatabase = helper.getDatabase();
}
}
public class AssetsDatabaseHelper {
Context context;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
private static AssetsDatabaseHelper instance;
private AssetsDatabaseHelper(Context context){
this.context = context;
databaseHelper = new DatabaseHelper(context);
if(databaseHelper.checkDatabase()){
try{
databaseHelper.openDatabase();
}catch(SQLException sqle){
Log.e("Exception in opening ", " :: database :: sqle.getCause() : "+sqle.getCause());
}
}else{
try{
databaseHelper.createDatabase();
}catch(IOException ioe){
Log.d("Exception in creating ", " :: database :: ioe.getCause() : "+ioe.getCause());
}
try{
databaseHelper.openDatabase();
}catch(SQLException sqle){
Log.e("Exception in opening ", " :: database :: "+sqle.getCause());
}
}
sqLiteDatabase = databaseHelper.getSqLiteDatabase();
}
public static AssetsDatabaseHelper getInstance(Context context){
if(instance != null){
return instance;
}else {
instance = new AssetsDatabaseHelper(context);
return instance;
}
}
public SQLiteDatabase getDatabase(){
return sqLiteDatabase;
}
}
Make a Ctrl+Alt+Suppr in order to see if no other Apache version is ever runing on your computer. It was the case for me, I just stop them and the light pass green!
Cheers!
position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;
You may pass "true" or "" to the checked property of input checkbox. The empty quotes ("") will be understood as false and the item will be unchecked.
let checked = variable === value ? "true" : "";
<input
className="form-check-input"
type="checkbox"
value={variable}
id={variable}
name={variable}
checked={checked}
/>
<label className="form-check-label">{variable}</label>
You can also use the restore menu in MySQL Administrator. You just have to open the back-up file, and then click the restore button.
I've had trouble with angled quotes in the past ( ‘ ) usually from copy and pasting from Word. Replacing them with regular single quotes ( ' ) does the trick.
I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:
$("#id").on('click', function(){ //enables click event
//do your thing here
});
$("#id").off('click'); //disables click event
If you want to disable a div, use the following code:
$("#id").attr('disabled','disabled');
Hope this helps.
edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()
I know its 3 years too late, but maybe it can help someone else because I haven't found anything like that except for the moment-timezone library, which is not exactly the same as what he's asking for here.
I've done something similar for german timezone, this is a little complex because of daylight saving time and leap years where you have 366 days.
it might need a little work with the "isDaylightSavingTimeInGermany" function while different timezones change on different times the daylight saving time.
anyway, check out this page: https://github.com/zerkotin/german-timezone-converter/wiki
the main methods are: convertLocalDateToGermanTimezone convertGermanDateToLocalTimezone
I've put an effort into documenting it, so it won't be so confusing.
The second one is correct under the circumstances (well, the least wrong, anyway).
Edit: "least wrong", as in the original code shows no good reason to be using new
or delete
in the first place, so you should probably just use:
std::vector<Monster> monsters;
The result will be simpler code and cleaner separation of responsibilities.
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
I'm a relative novice compared to all the experts on Stack Overflow.
I have 2 versions of jupyter notebook running (one through a fresh Anaconda Navigator installation and one through ????). I think this is because Anaconda was installed as a local installation on my Mac (per Anaconda instructions).
I already had python 3.7 installed. After that, I used my terminal to open jupyter notebook and I think that it put another version globally onto my Mac.
However, I'm not sure because I'm just learning through trial and error!
I did the terminal command:
conda install -c anaconda certifi
(as directed above, but it didn't work.)
My python 3.7 is installed on OS Catalina10.15.3 in:
The certificate is at:
I tried to find the Install Certificate.command ... but couldn't find it through looking through the file structures...not in Applications...not in links above.
I finally installed it by finding it through Spotlight (as someone suggested above). And it double clicked automatically and installed ANOTHER certificate in the same folder as:
NONE of the above solved anything for me...I still got the same error.
So, I solved the problem by:
I can't tell you why this worked. But it solved the problem for me.
I just want to save someone the hassle next time. If someone can tell my why it worked, that would be terrific.
I didn't try the other terminal commands because of the 2 versions of jupyter notebook that I knew were a problem. I just don't know how to fix that.
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
when i first tried to import csv into mysql , i got the same error , and then i figured out mysql table i created doesn't have the character length of the importing csv field , so if it's the first time importing csv
varchar
or text
, don't blend int
or other values.then you are good to go.
Here is another way to display PDF inside Div by using Iframe like below.
<div>_x000D_
<iframe src="/pdf/test.pdf" style="width:100%;height:700px;"></iframe>_x000D_
</div>_x000D_
<div>_x000D_
<!-- I agree button -->_x000D_
</div>
_x000D_
<property attribute="attributeValue">proopertyValue</property>
would be one way to look at it.
In C#
[Attribute]
public class Entity
{
private int Property{get; set;};
You need two tables, where the first one is an exact overlay over the second one. The second one contains all the data, where the first one just contains the first column. You have to synchronize it's width and depending on the content also the height of it's rows.
Additional to this two tables, you need a third one. That's the first row, which lays exactly between the other two and has to be synchronized in the same way.
You will need absolute positioning here. Next, you would synchronize the scrolling of the data table with the scrolling positions of the head row and first column table.
That works very well in all major browsers, except for one issue: The synchronized scrolling will flutter. To fix that, you need two outher div containers that hold a clone of the content of the header row and the first column. When scrolling vertically, you display the header row clone to prevent fluttering, while you reposition the original in the background. When scrolling horizontally, you would show the first row clone. Same thing here.
I usually embed the xmlns:ads property into the adview properties this way:
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id"/>
so that you dont need to embed into the parent every and each time you copy the adview.
Just copy and paste the adview above and paste it anywhere and it should work
If you don't mind using a third party library, with cyclops-react, a library I contribute to, you can use the FluentFunctions API to write
Function<String, Integer> standardFn = FluentFunctions.ofChecked(this::myMethod);
ofChecked takes a jOO? CheckedFunction and returns the reference softened back to a standard (unchecked) JDK java.util.function.Function.
Alternatively you can keep working with the captured function via the FluentFunctions api!
For example to execute your method, retrying it up to 5 times and logging it's status you can write
FluentFunctions.ofChecked(this::myMethod)
.log(s->log.debug(s),e->log.error(e,e.getMessage())
.try(5,1000)
.apply("my param");
What I do is:
Set the td width:
<td width="200" height="50"><!--blaBlaBla Contents here--></td>
Set the td width with CSS:
<td style="width:200px; height:50px;">
Set the width again as max and min with CSS:
<td style="max-width:200px; min-width:200px; max-height:50px; min-height:50px; width:200px; height:50px;">
It sounds little bit repetitive but it gives me the desired result. To achieve this with much ease, you may need put the CSS values in a class in your style-sheet:
.td_size {
width:200px;
height:50px;
max-width:200px;
min-width:200px;
max-height:50px;
min-height:50px;
**overflow:hidden;** /*(Optional)This might be useful for some overflow contents*/
}
then:
<td class="td_size">
Place the class attribute to any <td>
you want.
Hope this will help to someone. Works fine in Angular 6 with reactive forms. Can operate by keyboard too.
dropdown.component.html
<div class="dropdown-wrapper {{className}} {{isFocused ? 'focus':''}}" [ngClass]="{'is-open':isOpen, 'disabled':isReadOnly}" *ngIf="options" (contextmenu)="$event.stopPropagation();">
<div class="box" (click)="toggle($event)">
<ng-container>
<div class="dropdown-selected" *ngIf="isSelectedValue" l10nTranslate><span>{{options[selected]}}</span></div>
<div class="dropdown-selected" *ngIf="!isSelectedValue" l10nTranslate><span>{{placeholder}}</span></div>
</ng-container>
</div>
<ul class="dropdown-options" *ngIf="options">
<li *ngIf="placeholder" (click)="$event.stopPropagation()">{{placeholder}}</li>
<ng-container>
<li id="li{{i}}"
*ngFor="let option of options; let i = index"
[class.active]="selected === i"
(click)="optionSelect(option, i, $event)"
l10nTranslate
>
{{option}}
</li>
</ng-container>
</ul>
</div>
dropdown.component.scss
@import "../../../assets/scss/variables";
// DROPDOWN STYLES
.dropdown-wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
border: 1px solid #DDDDDD;
border-radius: 3px;
cursor: pointer;
position: relative;
&.focus{
border: 1px solid #a8a8a8;
}
.box {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
}
// SELECTED
.dropdown-selected {
height: 30px;
position: relative;
padding: 10px 30px 10px 10px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
width: 100%;
font-size: 12px;
color: #666666;
overflow: hidden;
background-color: #fff;
&::before {
content: "";
position: absolute;
top: 50%;
right: 5px;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
width: 22px;
height: 22px;
background: url('/assets/i/dropdown-open-selector.svg');
background-size: 22px 22px;
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// DROPDOWN OPTIONS
.dropdown-options {
display: none;
position: absolute;
padding: 8px 6px 9px 5px;
max-height: 261px;
overflow-y: auto;
z-index: 999;
li {
padding: 10px 25px 10px 10px;
font-size: $regular-font-size;
color: $content-text-black;
position: relative;
line-height: 10px;
&:last-child {
border-bottom: none;
}
&:hover {
background-color: #245A88;
border-radius: 3px;
color: #fff;
border-bottom-color: transparent;
}
&:focus{
background-color: #245A88;
border-radius: 3px;
color: #fff;
}
&.active {
background-color: #245A88;
border-radius: 3px;
color: #fff;
border-bottom-color: transparent;
}
&:hover {
background-color: #7898B3
}
&.active {
font-weight: 600;
}
}
}
&.is-open {
.dropdown-selected {
&::before {
content: "";
position: absolute;
top: 50%;
right: 5px;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
width: 22px;
height: 22px;
background: url('/assets/i/dropdown-close-selector.svg');
background-size: 22px 22px;
}
}
.dropdown-options {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
width: 100%;
top: 32px;
border-radius: 3px;
background-color: #ffffff;
border: 1px solid #DDDDDD;
-webkit-box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
}
}
&.data-input-fields {
.box {
height: 35px;
}
}
&.send-email-table-select {
min-width: 140px;
border: none;
}
&.persoanal-settings {
width: 80px;
}
}
div.dropdown-wrapper.disabled
{
pointer-events: none;
background-color: #F1F1F1;
opacity: 0.7;
}
dropdown.component.ts
import { Component, OnInit, Input, Output, EventEmitter, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DropdownComponent),
multi: true
};
@Component({
selector: 'app-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss'],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DropdownComponent implements OnInit, ControlValueAccessor {
@Input() options: Array<string>;
@Input() selected: number;
@Input() className: string;
@Input() placeholder: string;
@Input() isReadOnly = false;
@Output() optSelect = new EventEmitter();
isOpen = false;
selectedOption;
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
isSelectedValue: boolean;
key: string;
isFocused: boolean;
/**
*Creates an instance of DropdownComponent.
* @memberof DropdownComponent
*/
ngOnInit() {
// Place default value in dropdown
if (this.selected) {
this.placeholder = '';
this.isOpen = false;
}
}
@HostListener('focus')
focusHandler() {
this.selected = 0;
this.isFocused = true;
}
@HostListener('focusout')
focusOutHandler() {
this.isFocused = false;
}
@HostListener('document:keydown', ['$event'])
keyPressHandle(event: KeyboardEvent) {
if (this.isFocused) {
this.key = event.code;
switch (this.key) {
case 'Space':
this.isOpen = true;
break;
case 'ArrowDown':
if (this.options.length - 1 > this.selected) {
this.selected = this.selected + 1;
}
break;
case 'ArrowUp':
if (this.selected > 0) {
this.selected = this.selected - 1;
}
break;
case 'Enter':
if (this.selected > 0) {
this.isSelectedValue = true;
this.isOpen = false;
this.onChangeCallback(this.selected);
this.optSelect.emit(this.options[this.selected]);
}
break;
}
}
}
/**
* option selection
* @param {string} selectedOption - text
* @param {number} idx - current index of item
* @param {any} event - object
*/
optionSelect(selectedOption: string, idx, e: any) {
e.stopPropagation();
this.selected = idx;
this.isSelectedValue = true;
// this.placeholder = '';
this.isOpen = false;
this.onChangeCallback(this.selected);
this.optSelect.emit(selectedOption);
}
/**
* toggle the dropdown
* @param {any} event object
*/
toggle(e: any) {
e.stopPropagation();
// close all previously opened dropdowns, before open
const allElems = document.querySelectorAll('.dropdown-wrapper');
for (let i = 0; i < allElems.length; i++) {
allElems[i].classList.remove('is-open');
}
this.isOpen = !this.isOpen;
if (this.selected >= 0) {
document.querySelector('#li' + this.selected).scrollIntoView(true);
}
}
/**
* dropdown click on outside
*/
@HostListener('document: click', ['$event'])
onClick() {
this.isOpen = false;
}
/**
* Method implemented from ControlValueAccessor and set default selected value
* @param {*} obj
* @memberof DropdownComponent
*/
writeValue(obj: any): void {
if (obj && obj !== '') {
this.isSelectedValue = true;
this.selected = obj;
} else {
this.isSelectedValue = false;
}
}
// From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
// From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
setDisabledState?(isDisabled: boolean): void {
}
}
Usage
<app-dropdown formControlName="type" [options]="types" [placeholder]="captureData.type" [isReadOnly]="isReadOnly">
</app-dropdown>
Options must bind an array as follows. It can change based on the requirement.
types= [
{
"id": "1",
"value": "Type 1"
},
{
"id": "2",
"value": "Type 2"
},
{
"id": "3",
"value": "Type 3"
}]
Please think first of open/closed principle. The default methods in interfaces DO VIOLATE it. This is a bad feature in Java. It encourages bad design, bad architecture, low software quality. I would suggest to avoid using default methods completely.
Ask yourself a few questions: Why can't you put your methods to the abstract class? Would you need then more than one abstract class? Then think about what is your class responsible for. Are you sure all methods you are going to put to the single class really fulfill the same purpose? May be you will distinguish several purposes and will then split your class into several classes, for each purpose its own class.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
The javadocs for Scanner answer your question
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You might change the default whitespace pattern the Scanner is using by doing something like
Scanner s = new Scanner();
s.useDelimiter("\n");
Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
Pyttsx3 is a python module which is a modern clone of pyttsx, modified to work perfectly well in the latest versions of Python 3!
It is 100% MULTI-PLATFORM and WORKS OFFLINE and IS ACTIVE/STILL BEING DEVELOPED and WORKS WITH ANY PYTHON VERSION
It can be easily installed with pip install pyttsx3
and usage is the same as pyttsx:
import pyttsx3;
engine = pyttsx3.init();
engine.say("I will speak this text");
engine.runAndWait();
This is the best multi platform option!
var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');
That should work just fine.
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
If one is to use all four function, the directive will follow this form:
myApp.directive( 'myDirective', function () {
return {
restrict: 'EA',
controller: function( $scope, $element, $attrs, $transclude ) {
// Controller code goes here.
},
compile: function compile( tElement, tAttributes, transcludeFn ) {
// Compile code goes here.
return {
pre: function preLink( scope, element, attributes, controller, transcludeFn ) {
// Pre-link code goes here
},
post: function postLink( scope, element, attributes, controller, transcludeFn ) {
// Post-link code goes here
}
};
}
};
});
Notice that compile returns an object containing both the pre-link and post-link functions; in Angular lingo we say the compile function returns a template function.
If pre-link
isn't necessary, the compile function can simply return the post-link function instead of a definition object, like so:
myApp.directive( 'myDirective', function () {
return {
restrict: 'EA',
controller: function( $scope, $element, $attrs, $transclude ) {
// Controller code goes here.
},
compile: function compile( tElement, tAttributes, transcludeFn ) {
// Compile code goes here.
return function postLink( scope, element, attributes, controller, transcludeFn ) {
// Post-link code goes here
};
}
};
});
Sometimes, one wishes to add a compile
method, after the (post) link
method was defined. For this, one can use:
myApp.directive( 'myDirective', function () {
return {
restrict: 'EA',
controller: function( $scope, $element, $attrs, $transclude ) {
// Controller code goes here.
},
compile: function compile( tElement, tAttributes, transcludeFn ) {
// Compile code goes here.
return this.link;
},
link: function( scope, element, attributes, controller, transcludeFn ) {
// Post-link code goes here
}
};
});
If no compile function is needed, one can skip its declaration altogether and provide the post-link function under the link
property of the directive's configuration object:
myApp.directive( 'myDirective', function () {
return {
restrict: 'EA',
controller: function( $scope, $element, $attrs, $transclude ) {
// Controller code goes here.
},
link: function postLink( scope, element, attributes, controller, transcludeFn ) {
// Post-link code goes here
},
};
});
In any of the examples above, one can simply remove the controller
function if not needed. So for instance, if only post-link
function is needed, one can use:
myApp.directive( 'myDirective', function () {
return {
restrict: 'EA',
link: function postLink( scope, element, attributes, controller, transcludeFn ) {
// Post-link code goes here
},
};
});
You can also add prompt option like this.
<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>
in my case it is because the ubuntu permission,
check permission by
docker info
if they print problem permission, then use
sudo chmod -R 777 /var/run/docker.sock
You cannot simply add number to datetime
because it's unclear what unit is used: seconds, hours, weeks...
There is timedelta
class for manipulations with date and time. datetime
minus datetime
gives timedelta
, datetime
plus timedelta
gives datetime
, two datetime
objects cannot be added although two timedelta
can.
Create timedelta
object with how many seconds you want to add and add it to datetime
object:
>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)
There is same concept in C++: std::chrono::duration
.
Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...
if args.argument_name:
# do something
else:
# do something else
This should do the trick:
pw_bytes.decode("utf-8")
I installed Node.js on bluehost.com (a shared server) using:
wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node
This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.
then
./node/bin/npm install jt-js-sample
Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
I can now use the commands:
# ~/node/bin/node -v
v0.12.4
# ~/node/bin/npm -v
2.10.1
For security reasons, I have renamed my node directory to something else.
In Jupyter Notebook,
SHIFT+ TAB(to move left) and TAB(to move right) movement is perfectly working.
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Just to expand on the other answers - if you need to control the omission of null values on a per-field basis, annotate the field in question (or alternatively annotate the field's 'getter').
example - here only fieldOne
will be ommitted from json if it is null. fieldTwo
will always be included regardless of if it is null.
public class Foo {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String fieldOne;
private String fieldTwo;
}
To omit all null values in the class as a default, annotate the class. Per-field/getter annotations can still be used to override this default if necessary.
example - here fieldOne
and fieldTwo
will be ommitted from json if they are null, respectively, because this is the default set by the class annotation. fieldThree
however will override the default and will always be included, because of the annotation on the field.
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {
private String fieldOne;
private String fieldTwo;
@JsonInclude(JsonInclude.Include.ALWAYS)
private String fieldThree;
}
UPDATE
The above is for Jackson 2. For earlier versions of Jackson you need to use:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
instead of
@JsonInclude(JsonInclude.Include.NON_NULL)
If this update is useful, please upvote ZiglioUK's answer below, it pointed out the newer Jackson 2 annotation long before I updated my answer to use it!
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
You need to provide a default value:
new_field = models.CharField(max_length=140, default='SOME STRING')
subprocess.check_output()
returns a bytestring.
In Python 3, there's no implicit conversion between unicode (str
) objects and bytes
objects. If you know the encoding of the output, you can .decode()
it to get a string, or you can turn the \n
you want to add to bytes
with "\n".encode('ascii')
You can control with a change event if the input is within your range, if it is not in the range you assign 0.
<md-input-container>
<input type="number"
maxlength="3"
min="0"
max="100"
required
mdInput
placeholder="Charge"
[(ngModel)]="rateInput"
(change)= "rateInput < 0 ? rateInput = 0 : rateInput; rateInput > 100 ? rateInput = 0 : rateIntput;"
name="rateInput">
<md-error>Required field</md-error>
</md-input-container>
Also you can try to formulate your answer in the form of a SELECT CASE
Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.
SELECT @Result =
CASE @inputParam
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 1
ELSE 4
END
IF @Result = 1
BEGIN
...
END
IF @Result = 2
BEGIN
....
END
IF @Result = 4
BEGIN
//Error handling code
END
<%= Html.Partial("PartialName", Model) %>
Please do yourself a favor and just hit the easy button:
download Web Inspector (Open Source) from the Play store.
A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:
console.log('one', 'two', 'three');
you will only see
one
logged to the console. You'll need to manually wrap the params in an Array and join, like so:
console.log([ 'one', 'two', 'three' ].join(' '));
to see the expected output.
But the app is open source! A patch may be imminent! The patcher could even be you!
And this is the answer of Frederik on Swift 3.0
/*
Usage:
- make your CustomeView class and inherit from this one
- in your Xib file make the file owner is your CustomeView class
- *Important* the root view in your Xib file must be of type UIView
- link all outlets to the file owner
*/
@IBDesignable
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
This just happened to me in a string assignment using double quotes. I was missing a closing curly on a POST variable...
"for {$_POST['txtName'] on $date"
;
should have been
"for {$_POST['txtName']} on $date"
;
I can't explain why. I mean, I see the error that would break the code but I don't see why it references a class error.
Either return a value from your main
or use the exit
function. Both take an int. It doesn't really matter what value you return unless you have an external process watching for the return value.
I had this issue, this is how i have solved it. The problem mostly is that your Angular version is not supporting your Node.js version for the build. So the best solution is to upgrade your Node.js to the most current stable one.
For a clean upgrade of Node.js, i advise using n. if you are using Mac.
npm install -g n
npm cache clean -f
sudo n stable
npm update -g
and now check that you are updated:
node -v
npm -v
For more details, check this link: here
Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
class foo:
a = 'foo'
b = 'bar'
To print all non-callable attributes, you can use the following function:
def printVars(object):
for i in [v for v in dir(object) if not callable(getattr(object,v))]:
print '\n%s:' % i
exec('print object.%s\n\n') % i
VAR1=value1 VAR2=value2 myScript args ...
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [(ngModel)]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker1
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [value]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker2
You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.
Instead you should set the option responseType
to text
:
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'}
).pipe(catchError(this.errorHandlerService.handleError));
}
Particularly for node, the documentation for the http server component, under event connection says:
[Triggered] when a new TCP stream is established. [The] socket is an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit readable events because of how the protocol parser attaches to the socket. The socket can also be accessed at
request.connection
.
So, that means request.connection
is a socket and according to the documentation there is indeed a socket.remoteAddress attribute which according to the documentation is:
The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.
Under express, the request object is also an instance of the Node http request object, so this approach should still work.
However, under Express.js the request already has two attributes: req.ip and req.ips
req.ip
Return the remote address, or when "trust proxy" is enabled - the upstream address.
req.ips
When "trust proxy" is
true
, parse the "X-Forwarded-For" ip address list and return an array, otherwise an empty array is returned. For example if the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"] where "proxy2" is the furthest down-stream.
It may be worth mentioning that, according to my understanding, the Express req.ip
is a better approach than req.connection.remoteAddress
, since req.ip
contains the actual client ip (provided that trusted proxy is enabled in express), whereas the other may contain the proxy's IP address (if there is one).
That is the reason why the currently accepted answer suggests:
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
The req.headers['x-forwarded-for']
will be the equivalent of express req.ip
.
You can try this
pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)
I also experienced the same problem I solved as follows:
dataset = pd.read_csv('C:\\Users\\path\\to\\file.csv')
I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child
parameters will only make it more complicated. As for the background color I'd just set that to a variable.
Here goes what I came up with before I realized trying to be too clever might be a bad thing.
#romtest {
$bg: #e5e5e5;
.detailed {
th {
&:nth-child(-2n+6) {
background-color: $bg;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
background-color: $bg;
}
&.last {
&:nth-child(-2n+4){
background-color: $bg;
}
}
}
}
}
and here is a quick demo: http://codepen.io/anon/pen/BEImD
----EDIT----
Here's another approach to avoid retyping background-color
:
#romtest {
%highlight {
background-color: #e5e5e5;
}
.detailed {
th {
&:nth-child(-2n+6) {
@extend %highlight;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
@extend %highlight;
}
&.last {
&:nth-child(-2n+4){
@extend %highlight;
}
}
}
}
}
I also faced the same issue and got a solution very similar:
Changing the classpath to classpath 'com.android.tools.build:gradle:2.3.2'
A new message indicating to Update Build Tool version, so just click that message to update. Update
If you changed my.ini
and restarted mysql
and you still get this error please check your file path and replace "\"
to "/"
.
I solved my proplem after replacing.
try this out let me know what happens.
Form:
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
Form.php:
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
Edit: Cleaned it up a little more.
Final Cut (my test file):
<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
}
?>
</body>
</html>
I am having OpenCV version 3.4.3 on MacOS. I was getting the same error as above.
I changed my code from
frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
to
frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
Now its working fine for me.
The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler
defaults to using its CookieContainer
property for cookies. If you disable that then by setting UseCookies
to false
you can set cookie headers manually and they will appear in the request, e.g.
var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var message = new HttpRequestMessage(HttpMethod.Get, "/test");
message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
var result = await client.SendAsync(message);
result.EnsureSuccessStatusCode();
}
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.
In VB.NET
Dim directory as String = My.Application.Info.DirectoryPath
In C#
string directory = AppDomain.CurrentDomain.BaseDirectory;
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:id="@+id/your_id"
android:layout_marginTop="16dp"
android:layout_below="@+id/Id_of__view_present_above"
/>
My share
I have tested print(-(-101 // 5)) = 21
given example above.
Now for rounding up:
101 * 19% = 19.19
I can not use **
so I spread the multiply to division:
(-(-101 //(1/0.19))) = 20
SELECT DISTINCT groups.id,
(SELECT COUNT(*) FROM group_members
WHERE member_id = groups.id) AS memberCount
FROM groups
This is the real proxy redirection to the intended server.
server {
listen 80;
server_name localhost;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://xx.xxx.xxx.xxx/;
proxy_redirect off;
proxy_set_header Host $host;
}
}
I know this is an older post, but I ran into the ERROR! MySQL server PID file could not be found!
when trying to start MySQL after making an update to my.cnf
file. I did the following to resolve the issue:
Deleted my experimental update to my.cnf
Deleted the .net.pid
and .net.err
files.
delete /usr/local/var/mysql/**<YourUserName>**-MBP.airstreamcomm.net.*
ps -ax | grep mysql
kill **<process id>**
mysql.server start
Similar answer to iHulk's one, but in Swift
Add a file named UIView.swift in your project (or just paste this in any file) :
import UIKit
@IBDesignable extension UIView {
@IBInspectable var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
guard let color = layer.borderColor else {
return nil
}
return UIColor(cgColor: color)
}
}
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
}
Then this will be available in Interface Builder for every button, imageView, label, etc. in the Utilities Panel > Attributes Inspector :
Note: the border will only appear at runtime.
import { AfterViewInit, Component, ElementRef} from '@angular/core';
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.querySelector('my-element')
.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
console.log(event);
}
For nice & readable results, use this:
function printVar($var) {
echo '<pre>';
var_dump($var);
echo '</pre>';
}
The above function will preserve the original formatting, making it (more)readable in a web browser.
Linux, Qt Creator >= 3.4:
You could edit theese themes:
/usr/share/qtcreator/themes/default.creatortheme
/usr/share/qtcreator/themes/dark.creatortheme
I tried all the above with v 1.8.13 to no avail.
What worked for me (on macOS) was to use the doxywizard->Expert tag to fill the USE_MD_FILE_AS_MAINPAGE
setting.
It made the following changes to my Doxyfile:
USE_MDFILE_AS_MAINPAGE = ../README.md
...
INPUT = ../README.md \
../sdk/include \
../sdk/src
Note the line termination for INPUT
, I had just been using space as a separator as specified in the documentation. AFAICT this is the only change between the not-working and working version of the Doxyfile.
For me it was a silly thing: my mac uploaded the file into iCloud, and that is why Xcode did not find it.
If you turn off the automatic upload, it wont happen again.
Instead of
beforeEach(() => {..
use
beforeEach(fakeAsync(() => {..
There's some pretty good answers here but I want to elaborate on all topics:
Cloud: shailesh's answer is awesome, nothing to add there! Basically, An application that's served seamlessly over the network can be considered a Cloud application. Cloud isn't a new invention and it's very similar to Grid computing, but it's more of a buzzword with the spike of recent popularity.
Grid: Grid is defined as a large collection as machines connected by a private network and offers a set of services to users, it acts as a sort of supercomputer by sharing processing power across the machines. Source: Tenenbaum, Andrew.
Cluster: A cluster is different from those two. Clusters are two or more computers who share a network connection that acts as a heart-beat. Clusters are configurable in Active-Active or Active-Passive ways. Active-Active being that each computer runs it's own set of services (Say, one runs a SQL instance, the other runs a web server) and they share some resources such as storage. If one of the computers in a cluster goes down the service fails over to the other node and almost seamlessly starts running there. Active-Passive is similar, but only one machine runs these services and only takes over once there's a failure.
Try this
self.tables.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 10.0f)];
I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :
response => response.json()
Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do response.json()
The easiest is to convert your data to a "tall" format.
s <-
"A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
"
d <- read.delim(textConnection(s), sep="")
library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")
# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) +
geom_point() +
stat_smooth()
# Separate plots
ggplot(d, aes(Xax,value)) +
geom_point() +
stat_smooth() +
facet_wrap(~variable)
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
Why not just use all Lambda syntax?
database.Stores.Where(s => s.CompanyID == curCompany.ID)
.Select(s => new SelectListItem
{
Value = s.Name,
Text = s.ID
});