Try to look into previous error message happened before current error i.e., "CFBundleIdentifier”, Does Not Exist
.
Fix previous error then this error should disappear.
I fixed previous duplicate symbols for architecture
error when run react-native run-ios --simulator="iPad Pro (9.7-inch)
, then the problem gone.
You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');
. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.
In simplest terms :
Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).
Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.
Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
[i for i,x in enumerate(testlist) if x == 1]
Example:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
Update:
Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
Now we'll construct a generator...
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
and niftily enough, we can assign that to a variable, and use it from there...
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
And to think I used to write FORTRAN.
Here is a function to calculate the original size of an encoded Base 64 file as a String in KB:
private Double calcBase64SizeInKBytes(String base64String) {
Double result = -1.0;
if(StringUtils.isNotEmpty(base64String)) {
Integer padding = 0;
if(base64String.endsWith("==")) {
padding = 2;
}
else {
if (base64String.endsWith("=")) padding = 1;
}
result = (Math.ceil(base64String.length() / 4) * 3 ) - padding;
}
return result / 1000;
}
The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull
to DDL by default (thanks to hibernate.validator.apply_to_ddl property
defaults to true
). But there is no guarantee that other JPA providers do or even have the ability to do that.
You should use bean validation annotations like @NotNull
to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).
You should additionally use the JPA annotation like @Column(nullable = false)
to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.
If you're using Vuex
you can use https://github.com/vuejs/vuex-router-sync
Just initialize it in your main file with:
import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);
Each route change will update route
state object in Vuex
.
You can next create getter
to use the from
Object in route state or just use the state
(better is to use getters, but it's other story
https://vuex.vuejs.org/en/getters.html),
so in short it would be (inside components methods/values):
this.$store.state.route.from.fullPath
You can also just place it in <router-link>
component:
<router-link :to="{ path: $store.state.route.from.fullPath }">
Back
</router-link>
So when you use code above, link to previous path would be dynamically generated.
from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException
error from the uriString
. I think some of that code from VideoActivity
:
Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();
startVideo(b.getString(uri));
Cannot receive the uri from here:
public void playsquirrelmp4(View v) {
Intent VideoIntent = (new Intent(this, VideoActivity.class));
VideoIntent.putExtra("android.resource://" + getPackageName()
+ "/"+ R.raw.squirrel, uri);
startActivity(VideoIntent);
}
Use namespace
using System.Collections.Specialized;
Make instance of DataContext
Class
LinqToSqlDataContext dc = new LinqToSqlDataContext();
Use
OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);
In order to retrieve the values use namespace
using System.Collections;
ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;
String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];
keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);
for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();
I have added an extra update method onto my repository base class that's similar to the update method generated by Scaffolding. Instead of setting the entire object to "modified", it sets a set of individual properties. (T is a class generic parameter.)
public void Update(T obj, params Expression<Func<T, object>>[] propertiesToUpdate)
{
Context.Set<T>().Attach(obj);
foreach (var p in propertiesToUpdate)
{
Context.Entry(obj).Property(p).IsModified = true;
}
}
And then to call, for example:
public void UpdatePasswordAndEmail(long userId, string password, string email)
{
var user = new User {UserId = userId, Password = password, Email = email};
Update(user, u => u.Password, u => u.Email);
Save();
}
I like one trip to the database. Its probably better to do this with view models, though, in order to avoid repeating sets of properties. I haven't done that yet because I don't know how to avoid bringing the validation messages on my view model validators into my domain project.
Regarding your main objective " to install libraries they don't already have. " and regardless of using " instllaed.packages() ". The following function mask the original function of require. It tries to load and check the named package "x" , if it's not installed, install it directly including dependencies; and lastly load it normaly. you rename the function name from 'require' to 'library' to maintain integrity . The only limitation is packages names should be quoted.
require <- function(x) {
if (!base::require(x, character.only = TRUE)) {
install.packages(x, dep = TRUE) ;
base::require(x, character.only = TRUE)
}
}
So you can load and installed package the old fashion way of R. require ("ggplot2") require ("Rcpp")
Most browsers will simply ignore any NON-hex values in your color string, substituting non-hex digits with zeros.
ChuCknorris
translates to c00c0000000
. At this point, the browser will divide the string into three equal sections, indicating Red, Green and Blue values: c00c 0000 0000
. Extra bits in each section will be ignored, which makes the final result #c00000
which is a reddish color.
Note, this does not apply to CSS color parsing, which follow the CSS standard.
<p><font color='chucknorris'>Redish</font></p>_x000D_
<p><font color='#c00000'>Same as above</font></p>_x000D_
<p><span style="color: chucknorris">Black</span></p>
_x000D_
My favorite is to look at the boot messages. If it's been recently booted try running /etc/dmesg. Otherwise find the boot messages, logged in /var/adm or some place in /var.
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
Computer c= new Computer()
Here an object is created from the Computer
class. A reference named c allows the programmer to access the object.
The answer is NEVER! (unless you really know what you're doing)
9/10 times the solution can be resolved with a proper understanding of encoding/decoding.
1/10 people have an incorrectly defined locale or environment and need to set:
PYTHONIOENCODING="UTF-8"
in their environment to fix console printing problems.
(struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:sys.setdefaultencoding("utf-8")
str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC")
In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
(My console is configured as UTF-8, so "€" = '\xe2\x82\xac'
, hence exception on \xe2
)
or
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into codesys.setdefaultencoding("utf-8")
also has a side effect of appearing to fix sys.setdefaultencoding("utf-8")
sys.stdout.encoding
, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING
to fix the console encoding.
Example:
$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()
$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€
People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError
exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.
From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/
def welcome_message(byte_string):
try:
return u"%s runs your business" % byte_string
except UnicodeError:
return u"%s runs your business" % unicode(byte_string,
encoding=detect_encoding(byte_string))
print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))
Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.
Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.
While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
My c++ STL
code to initialise 5*3 2-D vector
with zero
#include <iostream>
using namespace std;
#include <vector>
int main()
{// if we wnt to initialise a 2 D vector with 0;
vector<vector<int>> v1(5, vector<int>(3,0));
for(int i=0;i<v1.size();i++)
{
for(int j=0;j<v1[i].size();j++)
cout<<v1[i][j]<<" ";
cout<<endl;
}
}
An old school solution like:
double X=((double)rand()/(double)RAND_MAX);
Should meet all your criteria (portable, standard and fast). obviously the random number generated has to be seeded the standard procedure is something like:
srand((unsigned)time(NULL));
//Get
var p = $("#elementId");
var offset = p.offset();
//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});
With VS2010+ there is a plugin solution: Line Endings Unifier.
With the plugin installed you can right click files and folders in the solution explorer and invoke the menu item Unify Line Endings in this file
Configuration for this is available via
Tools -> Options -> Line Endings Unifier.
The default file extension list that is included is pretty narrow:
.cpp; .c; .h; .hpp; .cs; .js; .vb; .txt;
Might want to use something like:
.cpp; .c; .h; .hpp; .cs; .js; .vb; .txt; .scss; .coffee; .ts; .jsx; .markdown; .config
Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.
I had the same problem sometime back. I had a old laptop, on which almost all the ports were either blocked or were malfunctioning. This is how I did it.
Open the XAMPP control panel.
Click on Config
Then, go into Apache httpd.conf file. Open it with a text editor.
Search for "80" (Do Ctrl + F and find all of them. Replace it with 8080 or 4040 or 4000).
Save the file. And restart XAMPP.
It worked well for me, and I hope it helps you too.
On Linux, this is likely to be a limit on the number of file watches.
The development server uses inotify to implement hot-reloading. The inotify API allows the development server to watch files and be notified when they change.
The default inotify file watch limit varies from distribution to distribution (8192 on Fedora). The needs of the development server often exceeds this limit.
The best approach is to try increasing the file watch limit temporarily, then making that a permanent configuration change if you're happy with it. Note, though, that this changes your entire system's configuration, not just node.
To view your current limit:
sysctl fs.inotify.max_user_watches
To temporarily set a new limit:
# this limit will revert after reset
sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p
# now restart the server and see if it works
To set a permanent limit:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
I just received a response from Kinook, who gave me a link:
Basically, I need to call the following prior to bulding. I guess Visual Studio 2013 does not automatically register the environment first, but 2012 did, or I did and forgot.
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86
Hopefully, this post helps someone else.
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
You can achive this with creating new array:
<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");
if (isset ($_POST['search'])) {
$maker = mysql_real_escape_string($_POST['Make']);
echo $array[$maker];
}
?>
If you want to use FXML, you should separate the controller (like you were doing with the SampleController). Then your fx:controller
in your FXML should point to that.
Probably you are missing the initialize
method in your controller, which is part of the Initializable
interface. This method is called after the FXML is loaded, so I recommend you to set your image there.
Your SampleController
class must be something like this:
public class SampleController implements Initializable {
@FXML
private ImageView imageView;
@Override
public void initialize(URL location, ResourceBundle resources) {
File file = new File("src/Box13.jpg");
Image image = new Image(file.toURI().toString());
imageView.setImage(image);
}
}
I tested here and it's working.
Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.
ok, this has been answered, but I thought you might like to see my answer that calls the math.pow() function once. I guess I like keeping things DRY.
function roundIt(num, precision) {
var rounder = Math.pow(10, precision);
return (Math.round(num * rounder) / rounder).toFixed(precision)
};
It kind of puts it all together. Replace Math.round() with Math.ceil() to round-up instead of rounding-off, which is what the OP wanted.
Not really a "Linq to SQL"
equivalent for Java. but something close to it . Query DSL
From the Mozilla Developer Network:
There is no way to stop or break a
forEach()
loop other than by throwing an exception. If you need such behavior, theforEach()
method is the wrong tool.Early termination may be accomplished with:
- A simple loop
- A
for
...of
loopArray.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
The other Array methods:
every()
,some()
,find()
, andfindIndex()
test the array elements with a predicate returning a truthy value to determine if further iteration is required.
The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.
Alternatively, you can use DOM to create a <script>
tag and set the src property on it then append it to the <head>
. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load
event on that script tag.
This function is based on the functionality of jQuery $.getScript()
function loadScript(src, f) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
var done = false;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
if (typeof f == 'function') f();
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
// example:
loadScript('/some-other-script.js', function() {
alert('finished loading');
finishSetup();
});
In class WeatherRecord
:
First import the class if they are in different package else this statement is not requires
Import <path>.ClassName
Then, just referene or call your object like:
Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();
But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.
Date.date(date,month,year); // this is enough to call those static function
Have clear concept on Object and Static functions. Click me
At this moment, PHP itself does not provide a way to get the project's root directory for sure.
But you can implement a very simple method yourself that will do exactly what you're looking for.
Solution
Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php
(use whatever name and path suit you the best). Then, use the following code:
<?php
class FilesManager
{
public static function rootDirectory()
{
// Change the second parameter to suit your needs
return dirname(__FILE__, 2);
}
}
Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php
:
echo FilesManager::rootDirectory();
And the expected result should be:
"D:/workspace/MySystem"
The output will be the same no matter where your "feature" file is located in the project.
Explanation
dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__
to give it FilesManager.php
's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__
directly instead.
This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.
Additional note
I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):
In the version of Android Studio I have (0.3.2), it was as easy as using the menu.
VCS Menu > Git > Share on GitHub.
It will then ask you for your credentials, and then a name for your new repo, and that's it!
use:
<div class="row form-group"></div>
Instead of manipulating the CMAKE_CXX_FLAGS
strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3")
btw), you can use add_compiler_options
:
add_compile_options(
"-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
"$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)
This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG
build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;
.
The correct thing to do is use the 'string-escape' code to decode the string.
>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs
Don't use the AST or eval. Using the string codecs is much safer.
Please check you are using //
not \\
by-mistake , like below
Wrong:"http:\\stackoverflow.com"
Right:"http://stackoverflow.com"
I would recommend this (just found via search):
Since none of the other answers worked for me I did it using this hack:
$ cd /yourfolder
svn co https://path-to-folder-which-has-your-files/ --depth files
This will create a new local folder which has only the files from the remote path. Then you can do a symbolic link to the files you want to have here.
what this means ? is there any problem in my code
It means that you are accessing a location or index which is not present in collection.
To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line
dataGridView1.Columns[4].Name = "Amount";
Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1)
by which you are accessing it, then this exception arises.
I'm using hub, a tool from github: https://github.com/github/hub
With hub checking out a pull request locally is kinda easy:
hub checkout https://github.com/owner/repo/pull/1234
or
hub pr checkout 1234
I ended up doing systemd service for WAR/JAR layout
I'm calling java -jar because its more flexible. Tried also putting the ExecStart=spring-mvc.war but even though is executable, I got 'Exec format error'
Anyway these days, systemd is present on all distros, and offers a nice solution to redirect logs(syserr is important when you service doesn't even start log4j file location will be empty :) ).
cat /etc/systemd/system/spring-mvc.service
[Unit]
Description=Spring MVC Java Service
[Service]
User=spring-mvc
# The configuration file application.properties should be here:
WorkingDirectory=/usr/local/spring-mvc
# Run ExecStartPre with root-permissions
PermissionsStartOnly=true
ExecStartPre=-/bin/mkdir -p /var/log/spring-mvc
ExecStartPre=/bin/chown -R spring-mvc:syslog /var/log/spring-mvc
ExecStartPre=/bin/chmod -R 775 /var/log/spring-mvc
#https://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
ExecStart=/usr/bin/java \
-Dlog4j.configurationFile=log4j2-spring.xml \
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector \
-Dspring.profiles.active=dev \
-Denvironment-type=dev \
-XX:+UseConcMarkSweepGC \
-XX:CMSInitiatingOccupancyFraction=80 \
-XX:NewSize=756m \
-XX:MetaspaceSize=256m \
-Dsun.net.inetaddr.ttl=5 \
-Xloggc:/var/log/spring-mvc/gc.log \
-verbose:gc \
-verbosegc \
-XX:+DisableExplicitGC \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-XX:+PreserveFramePointer \
-XX:+StartAttachListener \
-Xms1024m \
-Xmx1024m \
-XX:+HeapDumpOnOutOfMemoryError \
-jar spring-mvc.war
SuccessExitStatus=143
StandardOutput=journal
StandardError=journal
KillSignal=SIGINT
TimeoutStopSec=20
Restart=always
RestartSec=5
StartLimitInterval=0
StartLimitBurst=10
LimitNOFILE=500000
LimitNPROC=500000
#https://www.freedesktop.org/software/systemd/man/systemd.exec.html#LimitCPU=
#LimitCPU=, LimitFSIZE=, LimitDATA=, LimitSTACK=, LimitCORE=, LimitRSS=, LimitNOFILE=, LimitAS=, LimitNPROC=, LimitMEMLOCK=, LimitLOCKS=, LimitSIGPENDING=, LimitMSGQUEUE=, LimitNICE=, LimitRTPRIO=, LimitRTTIME=¶
SyslogIdentifier=spring-mvc
[Install]
WantedBy=multi-user.target
# https://www.freedesktop.org/software/systemd/man/journalctl.html
#check logs --- journalctl -u spring-mvc -f -o cat
rsyslog - redirect syslog input from app to specific folder/file
cat /etc/rsyslog.d/30-spring-mvc.conf
if $programname == 'spring-mvc' then /var/log/spring-mvc/spring-mvc.log
& stop
logrotate
cat /etc/logrotate.d/spring-mvc.conf
/var/log/spring-mvc/spring-mvc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
logrotate gc
cat /etc/logrotate.d/spring-mvc-gc.conf
/var/log/spring-mvc/gc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
Here's my addition.
From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source
"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."
I did that and here is Luciano's updated code snippet:
$.getJSON("example.json", function() {
alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });
And with error description plus showing all json data as a string:
$.getJSON("example.json", function(data) {
alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
If you don't like alerts, substitute them with console.log
$.getJSON("example.json", function(data) {
console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });
i tought it's because the connection but i use this:
git push --force origin master
Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}
I see at least one case where it should be avoided to use external files for long strings : if these long string are expected values in an unit-test file, because I think the tests should always be written in a way that they don't rely on any external resource.
the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
I'm just learning Schema. I'm using RELAX NG and using xmllint to validate. I'm getting frustrated by the errors coming out of xmlllint. I wish they were a little more informative.
If there is a wrong attribute in the XML then xmllint tells you the name of the unsupported attribute. But if you are missing an attribute in the XML you just get a message saying the element can not be validated.
I'm working on some very complicated XML with very complicated rules, and I'm new to this so tracking down which attribute is missing is taking a long time.
Update: I just found a java tool I'm liking a lot. It can be run from the command line like xmllint and it supports RELAX NG: https://msv.dev.java.net/
If you want to create a li
element for each input/name, then you have to create it, with document.createElement
[MDN].
Give the list the ID:
<ol id="demo"></ol>
and get a reference to it:
var list = document.getElementById('demo');
In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild
[MDN]:
var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
<head>
<link rel="shortcut icon" href="favicon.ico">
</head>
Try:
select v.*, row_number() over (partition by id order by elem) rn from
(select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable) v
To quote the specifications:
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's
__init__.py
module) should also list the modules and subpackages exported by the package.The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its
__init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
Angular 7 + NgBootstrap
A simple way of opening modal from main component and passing result back to it. is what I wanted. I created a step-by-step tutorial which includes creating a new project from scratch, installing ngbootstrap and creation of Modal. You can either clone it or follow the guide.
Hope this helps new to Angular.!
https://github.com/wkaczurba/modal-demo
Details:
modal-simple template (modal-simple.component.html):
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Are you sure?</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>You have not finished reading my code. Are you sure you want to close?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('yes')">Yes</button>
<button type="button" class="btn btn-outline-dark" (click)="modal.close('no')">No</button>
</div>
</ng-template>
The modal-simple.component.ts:
import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal-simple',
templateUrl: './modal-simple.component.html',
styleUrls: ['./modal-simple.component.css']
})
export class ModalSimpleComponent implements OnInit {
@ViewChild('content') content;
@Output() result : EventEmitter<string> = new EventEmitter();
constructor(private modalService : NgbModal) { }
open() {
this.modalService.open(this.content, {ariaLabelledBy: 'modal-simple-title'})
.result.then((result) => { console.log(result as string); this.result.emit(result) },
(reason) => { console.log(reason as string); this.result.emit(reason) })
}
ngOnInit() {
}
}
Demo of it (app.component.html) - simple way of dealing with return event:
<app-modal-simple #mymodal (result)="onModalClose($event)"></app-modal-simple>
<button (click)="mymodal.open()">Open modal</button>
<p>
Result is {{ modalCloseResult }}
</p>
app.component.ts - onModalClosed is executed once modal is closed:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
modalCloseResult : string;
title = 'modal-demo';
onModalClose(reason : string) {
this.modalCloseResult = reason;
}
}
Cheers
If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.
Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));
select.getOptions();//will get all options as List<WebElement>
One of the popular solutions to this question will have issues with the new line character. It can be fixed pretty easy with a simple str_replace
.
$handle = fopen("some_file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = str_replace("\n", "", $line);
}
fclose($handle);
}
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
A robust solution is to delegate counting to a subroutine invoked with call
; the subroutine uses goto
statements to emulate a loop in which shift
is used to consume the (subroutine-only) arguments iteratively:
@echo off
setlocal
:: Call the argument-counting subroutine with all arguments received,
:: without interfering with the ability to reference the arguments
:: with %1, ... later.
call :count_args %*
:: Print the result.
echo %ReturnValue% argument(s) received.
:: Exit the batch file.
exit /b
:: Subroutine that counts the arguments given.
:: Returns the count in %ReturnValue%
:count_args
set /a ReturnValue = 0
:count_args_for
if %1.==. goto :eof
set /a ReturnValue += 1
shift
goto count_args_for
Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.
<input type="text" pattern="[a-zA-Z]+" id="my-input">
var myInput = document.getElementById = "my-input";
myInput.addEventListener("keyup", function(){
if(!this.checkValidity() || !this.value){
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
});
You could directly inject the values into JavaScript:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Model.Addresses)');
</script>
See JSON.parse
, Html.Raw
Alternatively you can get the values via Ajax:
public ActionResult GetValues()
{
// logic
// Edit you don't need to serialize it just return the object
return Json(new { Addresses: lAddressGeocodeModel });
}
<script type="text/javascript">
$(function() {
$.ajax({
type: 'POST',
url: '@Url.Action("GetValues")',
success: function(result) {
// do something with result
}
});
});
</script>
See jQuery.ajax
Because fs.writefile
is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:
return new Promise(function(resolve, reject) {
fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
if (err) reject(err);
else resolve(data);
});
});
So in your code you would use it like so right after your call to .then()
:
.then(function(results) {
return new Promise(function(resolve, reject) {
fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
if (err) reject(err);
else resolve(data);
});
});
}).then(function(results) {
console.log("results here: " + results)
}).catch(function(err) {
console.log("error here: " + err);
});
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Temporary workaround: unicode(urllib2.urlopen(url).read(), 'utf8')
- this should work if what is returned is UTF-8.
urlopen().read()
return bytes and you have to decode them to unicode strings. Also it would be helpful to check the patch from http://bugs.python.org/issue4733
Working solution to set CultureInfo for all threads and windows.
<Application ........
Startup="Application_Startup"
>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
}
Yes!! Got it!
I downloaded the Java Developer Kit (JDK) from sun.com for Linux. There was src.zip in. But first I uninstalled all Java packages with synaptic.
You cannot concatenate multiple fields with a string. You need to select a field instand of all (*
).
if the program leaks over a long time, top might not be practical. I would write a simple shell scripts that appends the result of "ps aux" to a file every X seconds, depending on how long it takes to leak significant amounts of memory. Something like:
while true
do
echo "---------------------------------" >> /tmp/mem_usage
date >> /tmp/mem_usage
ps aux >> /tmp/mem_usage
sleep 60
done
The innerText
property returns the actual text value of an html element while the innerHTML
returns the HTML content
. Example below:
var element = document.getElementById('hello');_x000D_
element.innerText = '<strong> hello world </strong>';_x000D_
console.log('The innerText property will not parse the html tags as html tags but as normal text:\n' + element.innerText);_x000D_
_x000D_
console.log('The innerHTML element property will encode the html tags found inside the text of the element:\n' + element.innerHTML);_x000D_
element.innerHTML = '<strong> hello world </strong>';_x000D_
console.log('The <strong> tag we put above has been parsed using the innerHTML property so the .innerText will not show them \n ' + element.innerText);_x000D_
console.log(element.innerHTML);
_x000D_
<p id="hello"> Hello world _x000D_
</p>
_x000D_
To only get those errors that cause the application to stop working, use:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));
This will stop showing notices, warnings, and deprecated errors.
I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.
One column was a CHAR (90) and the other was a BIGINT (20).
One table was InnoDB and the other was MEMORY.
Part of query:
[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );
Changing the column type on the one column from BIGINT to CHAR solved the issue.
What levi said about passing it into the constructor is correct, but you could also use an object.
I think what Veverke is trying to say is that you could easily use the delete
keyword on an object to achieve the same effect.
I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).
Try something like this:
var obj = {
"bob": "dole",
"mr.": "peabody",
"darkwing": "duck"
};
Then, you could just do this:
delete obj["bob"];
The structure of the object would then be this:
{
"mr.": "peabody",
"darkwing": "duck"
}
Which has the same effect.
I recommend, you change your loop algorithm:
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
If you renamed the folder containing your Homestead project, you'll get this error. Visit your Homestead.yaml
file and update any references to point to the renamed folder, then do vagrant up
(etc.) again
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
Use the title
attribute while alt
is important for SEO stuff.
This is a common question and the answer is always the same: don't do it. Identity values should be treated as arbitrary and, as such, there is no "correct" order.
It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (
See this question's answers and/or search for a CodePen titled prettify <input type=range> #101
for some solutions.
CSS (or jQuery, for that matter) can't animate between display: none;
and display: block;
. Worse yet: it can't animate between height: 0
and height: auto
. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);
#main-image{
height: 0;
overflow: hidden;
background: red;
-prefix-animation: slide 1s ease 3.5s forwards;
}
@-prefix-keyframes slide {
from {height: 0;}
to {height: 300px;}
}
You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.
You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/
If you have this statement..
View view = inflater.inflate(R.layout.fragment1, container);//may be Incorrect
Then try this.. Add false as third argument.. May be it could help..
View view = inflater.inflate(R.layout.fragment1, container, false);//correct one
Function matmul (since numpy 1.10.1) works fine for both types and return result as a numpy matrix class:
import numpy as np
A = np.mat('1 2 3; 4 5 6; 7 8 9; 10 11 12')
B = np.array(np.mat('1 1 1 1; 1 1 1 1; 1 1 1 1'))
print (A, type(A))
print (B, type(B))
C = np.matmul(A, B)
print (C, type(C))
Output:
(matrix([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
(array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]), <type 'numpy.ndarray'>)
(matrix([[ 6, 6, 6, 6],
[15, 15, 15, 15],
[24, 24, 24, 24],
[33, 33, 33, 33]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
Since python 3.5 as mentioned early you also can use a new matrix multiplication operator @
like
C = A @ B
and get the same result as above.
Math.Floor()
rounds
"toward negative infinity" in compliance to IEEE Standard 754 section 4.
Math.Truncate()
rounds " to the nearest integer towards zero."
Python3
import urllib.request
print('Beginning file download with urllib2...')
url = 'https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/modi_instagram_660_020320092717.jpg'
urllib.request.urlretrieve(url, 'modiji.jpg')
If you want to find the rows
that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)
), create a logical index of (TRUE/FALSE) with (==
). Use Reduce
and OR (|
) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums
), double negate (!!
) to get the rows with any matches.
indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)
Or vectorise and get the row indices with which
with arr.ind=TRUE
indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
arr.ind=TRUE)[,1])
I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500
matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased
val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500,
replace=TRUE), ncol=500), stringsAsFactors=FALSE)
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)
konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
na.rm=TRUE)}
akrun2 <- function() {unique(which(Vectorize(function(x) x %in%
v1)(df1),arr.ind=TRUE)[,1])}
library(microbenchmark)
microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
#Unit: relative
# expr min lq mean median uq max neval
# konvas() 1.00000 1.000000 1.000000 1.000000 1.000000 1.00000 20
# akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737 20
# akrun2() 5.85611 5.641451 4.676836 5.330067 5.269937 2.22255 20
# cld
# a
# b
# a
For ncol = 10
, the results are slighjtly different:
expr min lq mean median uq max neval
konvas() 3.116722 3.081584 2.90660 2.983618 2.998343 2.394908 20
akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376 20
akrun2() 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000 20
v1 <- c('M017', 'M018')
df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53",
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07",
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23",
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>",
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2",
"col3", "col4"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11"))
Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.
You supply a function that takes a date and returns a boolean array:
"$(".selector").datepicker({ beforeShowDay: nationalDays})
natDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'],
[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7,
'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']];
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1 && date.getDate() ==
natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
List of time zone identifiers, included by default in Windows XP and Vista: Finding the Time Zones Defined on a Local System
This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
Sub test()
Dim myString As String
myString = Selection.Address
End Sub
The sheer <img ... width="50%"> said above, did work on my Github Readme.md document.
However my real issue was, that the image was inside a table cell, just compressing the text in the beside cell. So the other way was to set columns width in Markdown tables, but the solutions did not really seem enough markdownish for my morning.
At last I solved both problems by simply forcing the beside text cell with as much "& nbsp;" as I needed.
I hope this helps. Bye and thanks everybody.
These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.
But if you have to send non-ASCII text or large binary data, the form-data is for that.
You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.
Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.
Refer to this link for further reading: Forms in HTML documents
I have found the solution as followiing... working for me perfectly :)
$(document).ready(function(){
$("#selectbox1").change(function() {
var id = $(this).val();
$("#selectbox2").val(id);
}); });
I've placed this code in the document ready function and it only triggers in internet explorer. Tested in Internet Explorer 11.
var ua = window.navigator.userAgent;
ms_ie = /MSIE|Trident/.test(ua);
if ( ms_ie ) {
//Do internet explorer exclusive behaviour here
}
Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
You can use standard UITableViewDelegate methods
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell selectMe];
return indexPath;
}
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell deSelectMe];
return indexPath;
}
in my situation this works, cause we need to select cell, change color, and when user taps 2 times on the selected cell further navigation should be performed.
You can also put in a new virtual Host entry in the
c:\xampp\apache\conf\httpd-vhosts.conf
like:
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "C:/xampp/htdocs/myproject/web"
ServerName localhost
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
You (as in the process that runs b.php
, either you through CLI
or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod()
function to set the mode of a file or folder to 777
you should use 0777
to make sure the number is correctly interpreted as an octal number.
There is no need for typedef in Java. Everything is an Object except for the primitives. There are no pointers, only references. The scenarios where you normally would use typedefs are instances in which you create objects instead.
You can simply use the command below to describe a table.
desc table-name
or
desc schema-name.table-name
One of my colleagues noticed that most of the HttpClient
methods all call SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
under the hood, which is a virtual method off of HttpMessageInvoker
:
So by far the easiest way to mock out HttpClient
was to simply mock that particular method:
var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())).ReturnsAsync(_mockResponse.Object);
and your code can call most (but not all) of the HttpClient
class methods, including a regular
httpClient.SendAsync(req)
Check here to confirm https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
Real, User and Sys process time statistics
One of these things is not like the other. Real refers to actual elapsed time; User and Sys refer to CPU time used only by the process.
Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).
User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure.
Sys is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent in system calls within the kernel, as opposed to library code, which is still running in user-space. Like 'user', this is only CPU time used by the process. See below for a brief description of kernel mode (also known as 'supervisor' mode) and the system call mechanism.
User+Sys
will tell you how much actual CPU time your process used. Note that this is across all CPUs, so if the process has multiple threads (and this process is running on a computer with more than one processor) it could potentially exceed the wall clock time reported by Real
(which usually occurs). Note that in the output these figures include the User
and Sys
time of all child processes (and their descendants) as well when they could have been collected, e.g. by wait(2)
or waitpid(2)
, although the underlying system calls return the statistics for the process and its children separately.
Origins of the statistics reported by time (1)
The statistics reported by time
are gathered from various system calls. 'User' and 'Sys' come from wait (2)
(POSIX) or times (2)
(POSIX), depending on the particular system. 'Real' is calculated from a start and end time gathered from the gettimeofday (2)
call. Depending on the version of the system, various other statistics such as the number of context switches may also be gathered by time
.
On a multi-processor machine, a multi-threaded process or a process forking children could have an elapsed time smaller than the total CPU time - as different threads or processes may run in parallel. Also, the time statistics reported come from different origins, so times recorded for very short running tasks may be subject to rounding errors, as the example given by the original poster shows.
A brief primer on Kernel vs. User mode
On Unix, or any protected-memory operating system, 'Kernel' or 'Supervisor' mode refers to a privileged mode that the CPU can operate in. Certain privileged actions that could affect security or stability can only be done when the CPU is operating in this mode; these actions are not available to application code. An example of such an action might be manipulation of the MMU to gain access to the address space of another process. Normally, user-mode code cannot do this (with good reason), although it can request shared memory from the kernel, which could be read or written by more than one process. In this case, the shared memory is explicitly requested from the kernel through a secure mechanism and both processes have to explicitly attach to it in order to use it.
The privileged mode is usually referred to as 'kernel' mode because the kernel is executed by the CPU running in this mode. In order to switch to kernel mode you have to issue a specific instruction (often called a trap) that switches the CPU to running in kernel mode and runs code from a specific location held in a jump table. For security reasons, you cannot switch to kernel mode and execute arbitrary code - the traps are managed through a table of addresses that cannot be written to unless the CPU is running in supervisor mode. You trap with an explicit trap number and the address is looked up in the jump table; the kernel has a finite number of controlled entry points.
The 'system' calls in the C library (particularly those described in Section 2 of the man pages) have a user-mode component, which is what you actually call from your C program. Behind the scenes, they may issue one or more system calls to the kernel to do specific services such as I/O, but they still also have code running in user-mode. It is also quite possible to directly issue a trap to kernel mode from any user space code if desired, although you may need to write a snippet of assembly language to set up the registers correctly for the call.
More about 'sys'
There are things that your code cannot do from user mode - things like allocating memory or accessing hardware (HDD, network, etc.). These are under the supervision of the kernel, and it alone can do them. Some operations like malloc
orfread
/fwrite
will invoke these kernel functions and that then will count as 'sys' time. Unfortunately it's not as simple as "every call to malloc will be counted in 'sys' time". The call to malloc
will do some processing of its own (still counted in 'user' time) and then somewhere along the way it may call the function in kernel (counted in 'sys' time). After returning from the kernel call, there will be some more time in 'user' and then malloc
will return to your code. As for when the switch happens, and how much of it is spent in kernel mode... you cannot say. It depends on the implementation of the library. Also, other seemingly innocent functions might also use malloc
and the like in the background, which will again have some time in 'sys' then.
Select a series and look in the formula bar. The last argument is the plot order of the series. You can edit this formula just like any other, right in the formula bar.
For example, select series 4, then change the 4 to a 3.
I fixed the issue by changing the code to
@Basic(optional = false)
@Column(name = "LastTouched", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastTouched;
So the timestamp column is ignored when generating SQL inserts. Not sure if this is the best way to go about this. Feedback is welcome.
May be helpful for somebody. Mocked method must be of mocked class, created with mock(MyService.class)
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
For Swift 5.0 and iOS 12
extension UIImage {
func imageResized(to size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
}
use:
let image = #imageLiteral(resourceName: "ic_search")
cell!.search.image = image.imageResized(to: cell!.search.frame.size)
Dropzone.options.dpzSingleFile = {
paramName: "file", // The name that will be used to transfer the file
maxFiles: 1,
init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
});
}
};
In most of the modern single page applications, we indeed have to store the token somewhere on the client side (most common use case - to keep the user logged in after a page refresh).
There are a total of 2 options available: Web Storage (session storage, local storage) and a client side cookie. Both options are widely used, but this doesn't mean they are very secure.
Tom Abbott summarizes well the JWT sessionStorage and localStorage security:
Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS, in a nutshell, is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts
<script>alert('You are Hacked');</script>
into a form to see if it is run by the browser and can be viewed by other users.
To prevent XSS, the common response is to escape and encode all untrusted data. React (mostly) does that for you! Here's a great discussion about how much XSS vulnerability protection is React responsible for.
But that doesn't cover all possible vulnerabilities! Another potential threat is the usage of JavaScript hosted on CDNs or outside infrastructure.
Here's Tom again:
Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.
What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.
Therefore, my conclusion is that as a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
Installig Eclispe ADT from market place solved this problem for me.
Here's a script to get foreign keys:
SELECT TOP(150)
t.[name] AS [Table],
cols.[name] AS [Column],
t2.[name] AS [Referenced Table],
c2.[name] AS [Referenced Column],
constr.[name] AS [Constraint]
FROM sys.tables t
INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
--WHERE t.[name] IN ('?', '?', ...)
ORDER BY t.[Name], cols.[name]
There is difference between collision and duplication. Collision means hashcode and bucket is same, but in duplicate, it will be same hashcode,same bucket, but here equals method come in picture.
Collision detected and you can add element on existing key. but in case of duplication it will replace new value.
I guess an egg shell can be consider the encapsulation and the contents the abstraction. The shell protects the information. You cant have the contents of an egg without the shell.,,LOL
My objective is to check if the 'onEditButtonClick' is getting invoked when the user clicks the edit button and not checking just the console.log being printed.
You will need to first set up the test using the Angular TestBed
. This way you can actually grab the button and click it. What you will do is configure a module, just like you would an @NgModule
, just for the testing environment
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
describe('', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ],
declarations: [ TestComponent ],
providers: [ ]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
}));
});
Then you need to spy on the onEditButtonClick
method, click the button, and check that the method was called
it('should', async(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(component.onEditButtonClick).toHaveBeenCalled();
});
}));
Here we need to run an async
test as the button click contains asynchronous event handling, and need to wait for the event to process by calling fixture.whenStable()
It is now preferred to use fakeAsync/tick
combo as opposed to the async/whenStable
combo. The latter should be used if there is an XHR call made, as fakeAsync
does not support it. So instead of the above code, refactored, it would look like
it('should', fakeAsync(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
tick();
expect(component.onEditButtonClick).toHaveBeenCalled();
}));
Don't forget to import fakeAsync
and tick
.
In Eclipse: right-click
on your project -> Export
-> JAR file
At last page with options (when there will be no Next
button active) you will see settings for Main class:
. You need to set here class with main
method which should be executed by default (like when JAR file will be double-clicked).
In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl
In your startup.cs add the following:
// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});`enter code here`
To redirect Http to Https, add the following in the startup.cs
// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var options = new RewriteOptions()
.AddRedirectToHttps();
app.UseRewriter(options);
While you're waiting.. Curved corner (border-radius) cross browser
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem
instances. This is fortunately not needed anymore in JSF 2.x.
To answer your question directly, just use <f:selectItems>
whose value
points to a List<T>
property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T
actually represents a String
.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{bean.names}" />
</h:selectOneMenu>
with
@ManagedBean
@RequestScoped
public class Bean {
private String name;
private List<String> names;
@EJB
private NameService nameService;
@PostConstruct
public void init() {
names = nameService.list();
}
// ... (getters, setters, etc)
}
Simple as that. Actually, the T
's toString()
will be used to represent both the dropdown item label and value. So, when you're instead of List<String>
using a list of complex objects like List<SomeEntity>
and you haven't overridden the class' toString()
method, then you would see com.example.SomeEntity@hashcode
as item values. See next section how to solve it properly.
Also note that the bean for <f:selectItems>
value does not necessarily need to be the same bean as the bean for <h:selectOneMenu>
value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{data.names}" />
</h:selectOneMenu>
Whenever T
concerns a complex object (a javabean), such as User
which has a String
property of name
, then you could use the var
attribute to get hold of the iteration variable which you in turn can use in itemValue
and/or itemLabel
attribtues (if you omit the itemLabel
, then the label becomes the same as the value).
Example #1:
<h:selectOneMenu value="#{bean.userName}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>
with
private String userName;
private List<User> users;
@EJB
private UserService userService;
@PostConstruct
public void init() {
users = userService.list();
}
// ... (getters, setters, etc)
Or when it has a Long
property id
which you would rather like to set as item value:
Example #2:
<h:selectOneMenu value="#{bean.userId}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private Long userId;
private List<User> users;
// ... (the same as in previous bean example)
Whenever you would like to set it to a T
property in the bean as well and T
represents an User
, then you would need to bake a custom Converter
which converts between User
and an unique string representation (which can be the id
property). Do note that the itemValue
must represent the complex object itself, exactly the type which needs to be set as selection component's value
.
<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private User user;
private List<User> users;
// ... (the same as in previous bean example)
and
@ManagedBean
@RequestScoped
public class UserConverter implements Converter {
@EJB
private UserService userService;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return userService.find(Long.valueOf(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof User) {
return String.valueOf(((User) modelValue).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
}
}
}
(please note that the Converter
is a bit hacky in order to be able to inject an @EJB
in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class)
, but that unfortunately doesn't allow @EJB
injections)
Don't forget to make sure that the complex object class has equals()
and hashCode()
properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.
public class User {
private Long id;
@Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((User) other).id)
: (other == this);
}
@Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
}
Head to this answer: Implement converters for entities with Java Generics.
The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu>
without the need to create a custom converter. The SelectItemsConverter
will simply do the conversion based on readily available items in <f:selectItem(s)>
.
<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
Because your <form>
element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.
Try this...
<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>
You can do this:
//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));
//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
if(linkList.get(i).getAttribute("href").contains("long"))
{
linkList.get(i).click();
break;
}
}
in this what we r doing is first we are finding all the <a>
tags and storing them in a list.After
that we are iterating the list one by one to find <a>
tag whose href attribute contains long string. And then we click on that particular <a>
tag and comes out of the loop.
you can do this with css3, this blurs the whole element
div (or whatever element) {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Fiddle: http://jsfiddle.net/H4DU4/
You can also move your file in a sudoers used directory :
sudo mv $HOME/bash/script.sh /usr/sbin/
I think this post by Rex St John is very useful for unit testing with android studio.
(source: rexstjohn.com)
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
Two observations:
You should write
<input type="button" value="button text" />
instead of
<input type="button">button text</input>
You should rename your function. The function click()
is already defined on a button (it simulates a click), and gets a higher priority then your method.
Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:
onclick="javascript:myfunc()"
. Only use the javascript:
prefix inside the href
attribute of a hyperlink: <a href="javascript:myfunc()">
.onclick="foo()"
and onclick="foo();"
both work just fine.onclick
, onClick
and ONCLICK
all work. It is common practice to write attributes in lowercase: onclick
. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ...
, then it must be all lowercase.The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
If you are using PHP7, then you would need a PHP script like this one in order to migrate your collation:
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$mysqli = new mysqli('db',$dbuser,$dbpassword);
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> select_db($dbname);
$result= $mysqli->query('show tables');
while($tables = $result->fetch_array) {
foreach ($tables as $key => $value) {
$mysqli->query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
I looked into this a bit more and the actual problem seems to be with assigning initial
to page width
under the print
media rule. It seems like in Chrome width: initial
on the .page
element results in scaling of the page content if no specific length value is defined for width
on any of the parent elements (width: initial
in this case resolves to width: auto
... but actually any value smaller than the size defined under the @page
rule causes the same issue).
So not only the content is now too long for the page (by about 2cm
), but also the page padding will be slightly more than the initial 2cm
and so on (it seems to render the contents under width: auto
to the width of ~196mm
and then scale the whole content up to the width of 210mm
~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm
).
To fix this problem you can simply in the print
media rule assign the A4 paper width and hight to html, body
or directly to .page
and in this case avoid the initial
keyword.
@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
/* ... the rest of the rules ... */
}
This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).
The correct way to insert something (in Oracle) based on another record already existing is by using the MERGE statement.
Please note that this question has already been answered here on SO:
You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.
You can use the list.sort
to avoid creating new lists with sorted
and sort the lists in place.
Also you should not use list
as a variable name as it shadows python's own list.
def median(l):
half = len(l) // 2
l.sort()
if not len(l) % 2:
return (l[half - 1] + l[half]) / 2.0
return l[half]
Here is a POSIX version that combines many of the previous answers to deliver following features:
Here is the code and some test cases:
import threading
import signal
import os
import time
class TerminateExecution(Exception):
"""
Exception to indicate that execution has exceeded the preset running time.
"""
def quit_function(pid):
# Killing all subprocesses
os.setpgrp()
os.killpg(0, signal.SIGTERM)
# Killing the main thread
os.kill(pid, signal.SIGTERM)
def handle_term(signum, frame):
raise TerminateExecution()
def invoke_with_timeout(timeout, fn, *args, **kwargs):
# Setting a sigterm handler and initiating a timer
old_handler = signal.signal(signal.SIGTERM, handle_term)
timer = threading.Timer(timeout, quit_function, args=[os.getpid()])
terminate = False
# Executing the function
timer.start()
try:
result = fn(*args, **kwargs)
except TerminateExecution:
terminate = True
finally:
# Restoring original handler and cancel timer
signal.signal(signal.SIGTERM, old_handler)
timer.cancel()
if terminate:
raise BaseException("xxx")
return result
### Test cases
def countdown(n):
print('countdown started', flush=True)
for i in range(n, -1, -1):
print(i, end=', ', flush=True)
time.sleep(1)
print('countdown finished')
return 1337
def really_long_function():
time.sleep(10)
def really_long_function2():
os.system("sleep 787")
# Checking that we can run a function as expected.
assert invoke_with_timeout(3, countdown, 1) == 1337
# Testing various scenarios
t1 = time.time()
try:
print(invoke_with_timeout(1, countdown, 3))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function2))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
# Checking that classes are referenced and not
# copied (as would be the case with multiprocessing)
class X:
def __init__(self):
self.value = 0
def set(self, v):
self.value = v
x = X()
invoke_with_timeout(2, x.set, 9)
assert x.value == 9
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout
. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
Do you mean append
?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
Or merge?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.
String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}
Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.
String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}
Now in Solution-2 it wll return false because no independent cent word exist.
Additional: You can add or remove space on either side in 2nd solution according to your requirements.
to add on top of @Sushant Chaudhary's answer
in my case, I got another error regarding lxml as below
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
I had to install lxml-4.2.3-cp37-cp37m-win_amd64.whl same way as in the answer of @Sushant Chaudhary to successfully complete installation of Scrapy.
pip install <file-name>
now you can run pip install scrapy
For me it was not selecting 'Copy items if needed' in destination path while adding the framework. Simply re-add the framework with this option selected.
Using TimeUnit.SECONDS.sleep(1);
or Thread.sleep(1000);
Is acceptable way to do it. In both cases you have to catch InterruptedException
which makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException
inside. So your code would just include one line:
TimeUtils.sleepFor(1, TimeUnit.SECONDS);
See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here
you can follow the below command to install using the wheel file at your local
pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl
Quick google search says you can embed it like this:
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"
width="16" height="14" alt="embedded folder icon">
But you need a different implementation in Internet Explorer.
http://www.websiteoptimization.com/speed/tweak/inline-images/
If logical test is against a single column then you could use something like
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017
Using overflow: auto
on the <body>
tag is a cleaner solution and will work a charm.
I typically do this sort of thing by defining a custom [Serializable
] settings class and simply serializing it to disk. In your case you could just as easily store it as a string blob in your SQLite database.
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
The fact that SimpleDateFormat
is not thread-safe does not mean you cannot use it.
What that only means is that you must not use a single (potentially, but not necessarily static
) instance that gets accessed from several threads at once.
Instead, just make sure you create a fresh SimpleDateFormat
for each thread. Instances created as local variables inside a method are safe by definition, because they cannot be reached from any concurrent threads.
You might want to take a look at the ThreadLocal
class, although I would recommend to just create a new instance wherever you need one. You can, of course, have the format definition defined as a static final String DATE_FORMAT_PATTERN = "...";
somewhere and use that for each new instance.
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
string[] arr = { "Parrot" , "Snake" ,"Rabbit" , "Dog" , "cat" };
arr = arr.ToList().GetRange(0, arr.Length -1).ToArray();
First, you do not need android:process=":remote"
, so please remove it, since all it will do is take up extra RAM for no benefit.
Second, since the <service>
element contains an action string, use it:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=new Intent("com.sample.service.serviceClass");
this.startService(intent);
}
An alternative approach to those described above would be to create an external agent using java.lang.instrument
to find out what classes are loaded and run your program with the -javaagent
switch:
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class SimpleTransformer implements ClassFileTransformer {
public SimpleTransformer() {
super();
}
public byte[] transform(ClassLoader loader, String className, Class redefiningClass, ProtectionDomain domain, byte[] bytes) throws IllegalClassFormatException {
System.out.println("Loading class: " + className);
return bytes;
}
}
This approach has the added benefit of providing you with information about which ClassLoader loaded a given class.
With the xhr2 library you can globally overwrite XMLHttpRequest
from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.
global.XMLHttpRequest = require('xhr2');
Since Apache library is deprecated, for those who want to use HttpURLConncetion
, I wrote this class to send Get and Post Request with the help of this answer:
public class WebService {
static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";
static CookieManager msCookieManager = new CookieManager();
private static int responseCode;
public static String sendPost(String requestURL, String urlParameters) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
conn.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if (urlParameters != null) {
writer.write(urlParameters);
}
writer.flush();
writer.close();
os.close();
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
setResponseCode(conn.getResponseCode());
if (getResponseCode() == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// HTTP GET request
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla");
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form cookieManager and load them to connection:
*/
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
con.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form response header and load them to cookieManager:
*/
Map<String, List<String>> headerFields = con.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static void setResponseCode(int responseCode) {
WebService.responseCode = responseCode;
Log.i("Milad", "responseCode" + responseCode);
}
public static int getResponseCode() {
return responseCode;
}
}
Use jquery multiple selector.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>
Link : http://api.jquery.com/multiple-selector/
selector should like this : $("#id1,#id2,#id3")
If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.
For people coming from the future, you can now do this purely in CSS.
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
margin: 5rem;
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
width: 120px;
bottom: 100%;
left: 50%;
margin-left: -60px;
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
I fixed it by installing Android SDK Build-tools 20:
In Eclipse ? Pull Down Menu ? Window ? Android SDK Manager, check Android SDK Build-tools Rev. 20, then click the Install n package(s)… button to start installing.
execute the command
declare @sql varchar (100)
set @sql ='select * from #td1'
if (@IsMonday+@IsTuesday !='')
begin
set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
end
exec( @sql)
I had same problem regarding that i.e A network-related or instance-specific error occurred while establishing a connection to SQL Server.
I was using SQL Server 2005 (.\sqlexpress)` and worked fine but suddenly services stopped and gave me error.
I solved it like this,
Start -> Search Box - > Sql Configuration Manager -> SQL Server 2005 Services >and just Change Your SQL Server (SQLEXPRESS) State to Running by right clicking that service Sate.
For me my service that I created had to be uninstalled in Control Panel > Programs and Features
You can convert type of plaintext
to string:
f.write(str(plaintext) + '\n')
Simple function
function isCharNumber(c) {
return c >= '0' && c <= '9';
}
string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];
vals will give you the title
For having hover effect you can simply try this code
import React from "react";
import "./styles.css";
export default function App() {
function MouseOver(event) {
event.target.style.background = 'red';
}
function MouseOut(event){
event.target.style.background="";
}
return (
<div className="App">
<button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
</div>
);
}
Or if you want to handle this situation using useState() hook then you can try this piece of code
import React from "react";
import "./styles.css";
export default function App() {
let [over,setOver]=React.useState(false);
let buttonstyle={
backgroundColor:''
}
if(over){
buttonstyle.backgroundColor="green";
}
else{
buttonstyle.backgroundColor='';
}
return (
<div className="App">
<button style={buttonstyle}
onMouseOver={()=>setOver(true)}
onMouseOut={()=>setOver(false)}
>Hover over me!</button>
</div>
);
}
Both of the above code will work for hover effect but first procedure is easier to write and understand
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
Is there a way to initialize the
EntityManager
without a persistence unit defined?
You should define at least one persistence unit in the persistence.xml
deployment descriptor.
Can you give all the required properties to create an
Entitymanager
?
persistence.xml
file:<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
SOME_PROPERTIES
</persistence-unit>
</persistence>
In Java EE environments, the
jta-data-source
andnon-jta-data-source
elements are used to specify the global JNDI name of the JTA and/or non-JTA data source to be used by the persistence provider.
So if your target Application Server supports JTA (JBoss, Websphere, GlassFish), your persistence.xml
looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<!--GLOBAL_JNDI_GOES_HERE-->
<jta-data-source>jdbc/myDS</jta-data-source>
</persistence-unit>
</persistence>
If your target Application Server does not support JTA (Tomcat), your persistence.xml
looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<!--GLOBAL_JNDI_GOES_HERE-->
<non-jta-data-source>jdbc/myDS</non-jta-data-source>
</persistence-unit>
</persistence>
If your data source is not bound to a global JNDI (for instance, outside a Java EE container), so you would usually define JPA provider, driver, url, user and password properties. But property name depends on the JPA provider. So, for Hibernate as JPA provider, your persistence.xml
file will looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>br.com.persistence.SomeClass</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/EmpServDB;create=true"/>
<property name="hibernate.connection.username" value="APP"/>
<property name="hibernate.connection.password" value="APP"/>
</properties>
</persistence-unit>
</persistence>
Transaction Type Attribute
In general, in Java EE environments, a transaction-type of
RESOURCE_LOCAL
assumes that a non-JTA datasource will be provided. In a Java EE environment, if this element is not specified, the default is JTA. In a Java SE environment, if this element is not specified, a default ofRESOURCE_LOCAL
may be assumed.
I need to create the
EntityManager
from the user's specified values at runtime
So use this:
Map addedOrOverridenProperties = new HashMap();
// Let's suppose we are using Hibernate as JPA provider
addedOrOverridenProperties.put("hibernate.show_sql", true);
Persistence.createEntityManagerFactory(<PERSISTENCE_UNIT_NAME_GOES_HERE>, addedOrOverridenProperties);
If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.
You can use this function to disable the form:
function disableForm(formID){
$('#' + formID).children(':input').attr('disabled', 'disabled');
}
Note that it uses jQuery.
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
From the command line, .exit
is what you want:
$ node
> .exit
$
It's documented in the REPL docs. REPL (Read-Eval-Print-Loop) is what the Node command line is called.
From a normal program, use process.exit([code])
.
The problem is not to know if django can scale or not.
The right way is to understand and know which are the network design patterns and tools to put under your django/symfony/rails project to scale well.
Some ideas can be :
Hope it help a bit. This is my tiny rock to the mountain.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
namespace HMS.HtmlHelper
{
public class SendmailHelper
{
//Created SendEMail method for sendiing mails to users
public bool SendEMail(string FromName, string ToAddress, string Subject, string Message)
{
bool valid =false;
try
{
string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["smtpusername"].ToString();
string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtppassword"].ToString();
MailMessage mail = new MailMessage();``
mail.From = new MailAddress(smtpUserName, FromName);
mail.Subject = Subject;
mail.To.Add(FormatMultipleEmailAddresses(ToAddress));
//mail.To.Add(ToAddress);
mail.Body = Message.ToString();
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["smtpserverport"]);
smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; /
smtp.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
smtp.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ssl"]); ;
smtp.Send(mail);
valid = true;
}
catch (Exception ex)
{
valid =false ;
}
return valid;
}
public string FormatMultipleEmailAddresses(string emailAddresses)
{
var delimiters = new[] { ',', ';' };
var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", addresses);
}
}
}``
Raw sql query is fastest way I suppose
public void DeleteCustomer(int id)
{
using (var context = new Context())
{
const string query = "DELETE FROM [dbo].[Customers] WHERE [id]={0}";
var rows = context.Database.ExecuteSqlCommand(query,id);
// rows >= 1 - count of deleted rows,
// rows = 0 - nothing to delete.
}
}
using System;
using System.Text;
public static class Base64Conversions
{
public static string EncodeBase64(this string text, Encoding encoding = null)
{
if (text == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = encoding.GetBytes(text);
return Convert.ToBase64String(bytes);
}
public static string DecodeBase64(this string encodedText, Encoding encoding = null)
{
if (encodedText == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = Convert.FromBase64String(encodedText);
return encoding.GetString(bytes);
}
}
Usage
var text = "Sample Text";
var base64 = text.EncodeBase64();
base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding
Incrementing on the answer by MarvinLabs to make it cleaner:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
It is not necessary to check the lower end of the range because the break
statements will cause execution to skip remaining cases, so by the time execution gets to checking e.g. (x < 9) we know the value must be 5 or greater.
Of course the output is only correct if the cases stay in the original order, and we assume integer values (as stated in the question) - technically the ranges are between 5 and 8.999999999999 or so since all numbers in js are actually double-precision floating point numbers.
If you want to be able to move the cases around, or find it more readable to have the full range visible in each case statement, just add a less-than-or-equal check for the lower range of each case:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x >= 5 && x < 9):
alert("between 5 and 8");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
Keep in mind that this adds an extra point of human error - someone may try to update a range, but forget to change it in both places, leaving an overlap or gap that is not covered. e.g. here the case of 8 will now not match anything when I just edit the case that used to match 8.
case (x >= 5 && x < 8):
alert("between 5 and 7");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;
To disable the constraint you have ALTER
the table using NOCHECK
ALTER TABLE [TABLE_NAME] NOCHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
To enable you to have to use double CHECK:
ALTER TABLE [TABLE_NAME] WITH CHECK CHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
Once completed, if you need to check the status, use this script to list the constraint status. Will be very helpfull:
SELECT (CASE
WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'
ELSE 'DISABLED'
END) AS STATUS,
OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,
OBJECT_NAME(FKEYID) AS TABLE_NAME,
COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,
OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,
COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
FROM SYSFOREIGNKEYS
ORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO
You could use the following code where indentation doesn't matter:
>>> def fun():
return ('{0} Here is a really long'
' sentence with {1}').format(3, 5)
You just need to enclose string in the parentheses.
Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
How to generate an SSL certificate for localhost: link
openssl genrsa -des3 -out server.key 1024
you need to enter a password here which you need to retype in the following steps
openssl req -new -key server.key -out server.csr
when asked "Common Name" type in: localhost
openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt
iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.
This page has the details on creating barcodes. Here is an example from that site:
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.
import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.
First, are you referring to distance as in length of the entire path or you want to know only the displacement (straight line distance)? I see no one is pointing the difference between distance and displacement here. For distance calculate each route point given by JSON/XML data, as for displacement there is a built-in solution using Spherical
class
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
The SQL standard says full join on
is inner join on
rows union all
unmatched left table rows extended by nulls union all
right table rows extended by nulls. Ie inner join on
rows union all
rows in left join on
but not inner join on
union all
rows in right join on
but not inner join on
.
Ie left join on
rows union all
right join on
rows not in inner join on
. Or if you know your inner join on
result can't have null in a particular right table column then "right join on
rows not in inner join on
" are rows in right join on
with the on
condition extended by and
that column is null
.
Ie similarly right join on
union all
appropriate left join on
rows.
From What is the difference between “INNER JOIN” and “OUTER JOIN”?:
(SQL Standard 2006 SQL/Foundation 7.7 Syntax Rules 1, General Rules 1 b, 3 c & d, 5 b.)
I encountered same problem in opening android React Native Project in Android Studio.
The root cause is I opened the root folder of React Native Project instead of android folder of the React Native Project.
Reopen the project under android folder of React Native Project solved my problem.
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
and in onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
}
if(resultCode == RESULT_CANCELED){
//handle cancel
}
}
}
Just add the directory on the command line:
svn checkout svn://192.168.1.1/projectname/ target-directory/
You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([]
, separated by comma) with a square bracing, just like below:
Matrix = [[], []]
Now suppose you want to append 1 to Matrix[0][0]
then you type:
Matrix[0].append(1)
Now, type Matrix and hit Enter. The output will be:
[[1], []]
If you entered the following statement instead
Matrix[1].append(1)
then the Matrix would be
[[], [1]]
if I want to revert the container I can try to commit an image, and then later delete the container, and create a new container from the committed image. But if I do that the volume gets deleted and all my data is gone
As the docker user guide explains, data volumes are meant to persist data outside of a container filesystem. This also ease the sharing of data between multiple containers.
While Docker will never delete data in volumes (unless you delete the associated container with docker rm -v
), volumes that are not referenced by any docker container are called dangling volumes. Those dangling volumes are difficult to get rid of and difficult to access.
This means that as soon as the last container using a volume is deleted, the data volume becomes dangling and its content difficult to acess.
In order to prevent those dangling volumes, the trick is to create an additional docker container using the data volume you want to remain ; so that there will always be at least that docker container referencing the volume. This way you can delete the docker container running the wordpress app without losing the ease of access to that data volume content.
Such containers are called data volume containers.
There must be some simple way to back up my container plus volume data but I can't find it anywhere.
To backup docker images, use the docker save command that will produce a tar archive that can be used later on to create a new docker image with the docker load command.
You can backup a docker container by different means
Be aware that those commands will only backup the docker container layered file system. This excludes the data volumes.
To backup a data volume you can run a new container using the volume you want to backup and executing the tar command to produce an archive of the volume content as described in the docker user guide.
In your particular case, the data volume is used to store the data for a MySQL server. So if you want to export a tar archive for this volume, you will need to stop the MySQL server first. To do so you will have to stop the wordpress container.
An other way is to remotely connect to the MySQL server to produce a database dump with the mysqldump command. However in order for this to work, your MySQL server must be configured to accept remote connections and also have a user who is allowed to connect remotely. This might not be the case with the wordpress docker image you are using.
Docker recently introduced Docker volume plugins which allow to delegate the handling of volumes to plugins implemented by vendors.
The docker run
command has a new behavior for the -v
option. It is now possible to pass it a volume name. Volumes created in that way are named and easy to reference later on, easing the issues with dangling volumes.
Docker introduced the docker volume prune
command to delete all dangling volumes easily.
the approved answer does not include the essential return false to prevent touchstart from calling click if click is implemented which will result in running the handler twoce.
do:
$(btn).on('click touchstart', e => {
your code ...
return false;
});
If not done yet, you need to integrate Tomcat in your Servers view. Rightclick there and choose New > Server. Select the appropriate Tomcat version from the list and complete the wizard.
When you create a new Dynamic Web Project, you should select the integrated server from the list as Targeted Runtime in the 1st wizard step.
Or when you have an existing Dynamic Web Project, you can set/change it in Targeted Runtimes entry in project's properties. Eclipse will then automagically add all its libraries to the build path (without having a copy of them in the project!).
How can I make xargs execute the command exactly once for each line of input given?
-L 1
is the simple solution but it does not work if any of the files contain spaces in them. This is a key function of find's -print0
argument – to separate the arguments by '\0' character instead of whitespace. Here's an example:
echo "file with space.txt" | xargs -L 1 ls
ls: file: No such file or directory
ls: with: No such file or directory
ls: space.txt: No such file or directory
A better solution is to use tr
to convert newlines to null (\0
) characters, and then use the xargs -0
argument. Here's an example:
echo "file with space.txt" | tr '\n' '\0' | xargs -0 ls
file with space.txt
If you then need to limit the number of calls you can use the -n 1
argument to make one call to the program for each input:
echo "file with space.txt" | tr '\n' '\0' | xargs -0 -n 1 ls
This also allows you to filter the output of find before converting the breaks into nulls.
find . -name \*.xml | grep -v /target/ | tr '\n' '\0' | xargs -0 tar -cf xml.tar
On a Fedora 18 with Mongo 2.2.4 instance I was able to get around a similar error by disabling SELinux by calling setenforce 0
as root.
BTW, this was a corporate environment, not an Amazon EC2 instance, but the symptoms were similar.
Edit /etc/paths
. Then close the terminal and reopen it.
$ sudo vi /etc/paths
Note: each entry is seperated by line breaks.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin