Can You Please try this :
Check the web site properties in IIS.
Under home directory tab, check the application pool value
Verify that all SharePoint services are started.
If the application is not started do the following:
I think this error might occur because of changing the service account password.
You may need to change the new password to application pool
1)Click the stopped application pool
2)click advanced settings
3)Identity ->click the user to retype the user
4) Application Pool Identity dialog
5)click set -> manually type the user name and password.
Then restart the server.
If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
For me the problem was a configuration file that was missing an Element.
By pressing F12 web developers can quickly debug JavaScript code without leaving the browser. It is built into every installation of Windows.
In Internet Explorer 11, F12 tools provides debugging tools such as breakpoints, watch and local variable viewing, and a console for messages and immediate code execution.
The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.
I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that is idle for more than 5 mins.
Once again, this is the unlikely scenario.
PHP 5.2.2 <
$d = new DateTime();
echo $d->format("Y-m-d H:i:s.u"); // u : Microseconds
PHP 7.0.0 < 7.1
$d = new DateTime();
echo $d->format("Y-m-d H:i:s.v"); // v : Milliseconds
Use:
/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}
when typehinting inline variables, and
class A {
/** @var Test[] */
private $items;
}
for class properties.
Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:
The best you can do is say,
foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.
In my case, I wanted to split a data frame in Train, test and dev with a specific number. Here I am sharing my solution
First, assign a unique id to a dataframe (if already not exist)
import uuid
df['id'] = [uuid.uuid4() for i in range(len(df))]
Here are my split numbers:
train = 120765
test = 4134
dev = 2816
The split function
def df_split(df, n):
first = df.sample(n)
second = df[~df.id.isin(list(first['id']))]
first.reset_index(drop=True, inplace = True)
second.reset_index(drop=True, inplace = True)
return first, second
Now splitting into train, test, dev
train, test = df_split(df, 120765)
test, dev = df_split(test, 4134)
Based on an answer by Clay Bridges, here is an example of filtering using blocks (change yourArray
to your array variable name and testFunc
to the name of your testing function):
yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self testFunc:obj];
}]];
I had the same issue and eventually chose to use a Rectangle element:
<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4"/>
In my opinion it's somewhat easier to modify/shape than a separator.
Of course the Separator
is a very easy and neat solution for simple separations :)
The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.
It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.
For a good explanation of how, when and where see MSDN
Try this:
public static void arrayContains(){
int myArray[]={2,2,5,4,8};
int length=myArray.length;
int toFind = 5;
boolean found = false;
for(int i = 0; i < length; i++) {
if(myArray[i]==toFind) {
found=true;
}
}
System.out.println(myArray.length);
System.out.println(found);
}
<script type="text/javascript">
<!--
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>
Here's the other way, it's simpler than the other one.
<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />
It's simpler.
I have a bad time putting my war file at /etc/tomcat7/webapps
but the real path was /var/lib/tomcat7/webapps
. May you want to use sudo find / -type f -name "my-war-file.war"
to know where is it.
And remove this folders /tmp/hsperfdata_*
and /tmp/tomcat7-tomcat7-tmp
.
The terms "shallow copy" and "deep copy" are a bit vague; I would suggest using the terms "memberwise clone" and what I would call a "semantic clone". A "memberwise clone" of an object is a new object, of the same run-time type as the original, for every field, the system effectively performs "newObject.field = oldObject.field". The base Object.Clone() performs a memberwise clone; memberwise cloning is generally the right starting point for cloning an object, but in most cases some "fixup work" will be required following a memberwise clone. In many cases attempting to use an object produced via memberwise clone without first performing the necessary fixup will cause bad things to happen, including the corruption of the object that was cloned and possibly other objects as well. Some people use the term "shallow cloning" to refer to memberwise cloning, but that's not the only use of the term.
A "semantic clone" is an object which is contains the same data as the original, from the point of view of the type. For examine, consider a BigList which contains an Array> and a count. A semantic-level clone of such an object would perform a memberwise clone, then replace the Array> with a new array, create new nested arrays, and copy all of the T's from the original arrays to the new ones. It would not attempt any sort of deep-cloning of the T's themselves. Ironically, some people refer to the of cloning "shallow cloning", while others call it "deep cloning". Not exactly useful terminology.
While there are cases where truly deep cloning (recursively copying all mutable types) is useful, it should only be performed by types whose constituents are designed for such an architecture. In many cases, truly deep cloning is excessive, and it may interfere with situations where what's needed is in fact an object whose visible contents refer to the same objects as another (i.e. a semantic-level copy). In cases where the visible contents of an object are recursively derived from other objects, a semantic-level clone would imply a recursive deep clone, but in cases where the visible contents are just some generic type, code shouldn't blindly deep-clone everything that looks like it might possibly be deep-clone-able.
Note that getcwd(3)
is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.
Must link with -loldnames
(oldnames.lib, which is done automatically in most cases), or use _getcwd()
. The unprefixed version is unavailable under Windows RT.
import UIKit
import AudioToolbox
class ViewController: UIViewController {
let toneSound : Array = ["note1","note2","note3","note4","note5","note6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSound(theTone : String) {
if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
var mySound: SystemSoundID = 0
do {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
catch {
print(error)
}
}
}
@IBAction func anypressed(_ sender: UIButton) {
playSound(theTone: toneSound[sender.tag-1] )
}
}
I've found a simple javascript/jquery solution which utilizes the bootstrap modal events.
My solution also fixes the position:fixed
problem where it scrolls the background page all the way back to the top instead of staying in place when modal window is opened/closed.
See details here
For the 1st case, the inner loop is executed n-i
times, so the total number of executions is the sum for i
going from 0
to n-1
(because lower than, not lower than or equal) of the n-i
. You get finally n*(n + 1) / 2
, so O(n²/2) = O(n²)
.
For the 2nd loop, i
is between 0
and n
included for the outer loop; then the inner loop is executed when j
is strictly greater than n
, which is then impossible.
The jsonlite package is easy to use and tries to convert json into data frames.
Example:
library(jsonlite)
# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'
# read url and convert to data.frame
document <- fromJSON(txt=url)
Use the isSelected method.
You can also use an ItemListener so you'll be notified when it's checked or unchecked.
I find the method in the post Compile and Run Java programs with Sublime Text 2 works well and is a little more convenient than the other methods. Here is a link to the archived page.
Create runJava.bat
with the following code.
@ECHO OFF
cd %~dp1
ECHO Compiling %~nx1.......
IF EXIST %~n1.class (
DEL %~n1.class
)
javac %~nx1
IF EXIST %~n1.class (
ECHO -----------OUTPUT-----------
java %~n1
)
Copy this file to jdk bin directory.
"cmd": ["javac", "$file"],
"cmd": ["runJava.bat", "$file"],
Done!
Write programs and Run using CTRL + B
Note: Instructions are different for Sublime 3.
To avoid error, an important point about the new dataset is the name of independent variable. It must be the same as reported in the model. Another way is to nest the two function without creating a new dataset
model <- lm(Coupon ~ Total, data=df)
predict(model, data.frame(Total=c(79037022, 83100656, 104299800)))
Pay attention on the model. The next two commands are similar, but for predict function, the first work the second don't work.
model <- lm(Coupon ~ Total, data=df) #Ok
model <- lm(df$Coupon ~ df$Total) #Ko
You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.
On Ubuntu and Debian:
sudo apt-get install php5-pgsql
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
Extend your WHERE
condition:
WHERE
(FirstName = ISNULL(@FirstName, FirstName)
OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
OR COALESCE(@Title, Title, '') = '')
i. e. combine different cases with boolean conditions.
softwareupdate --list
see the list of outdated software.
softwareupdate --install --all
update all outdated software.
softwareupdate --install <product name>
update the software you named.
Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)
By C89, variable can only be defined at the top of a block.
if (a == 1)
int b = 10; // it's just a statement, syntacitially error
if (a == 1)
{ // refer to the beginning of a local block
int b = 10; // at the top of the local block, syntacitially correct
} // refer to the end of a local block
if (a == 1)
{
func();
int b = 10; // not at the top of the local block, syntacitially error, I guess
}
You can use next function to split string:
vector<string> split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
git diff -a
treats all file as text and it works for me.
You can use ISNULL(....)
SET @Concatenated = ISNULL(@Column1, '') + ISNULL(@Column2, '')
If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.
Functor can also be used to simulate defining a local function within a function. Refer to the question and another.
But a local functor can not access outside auto variables. The lambda (C++11) function is a better solution.
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
I was able to get jsPDF to print dynamically created tables from a div.
$(document).ready(function() {
$("#pdfDiv").click(function() {
var pdf = new jsPDF('p','pt','letter');
var specialElementHandlers = {
'#rentalListCan': function (element, renderer) {
return true;
}
};
pdf.addHTML($('#rentalListCan').first(), function() {
pdf.save("caravan.pdf");
});
});
});
Works great with Chrome and Firefox... formatting is all blown up in IE.
I also included these:
<script src="js/jspdf.js"></script>
<script src="js/jspdf.plugin.from_html.js"></script>
<script src="js/jspdf.plugin.addhtml.js"></script>
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="./libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="./libs/Blob.js/Blob.js"></script>
<script type="text/javascript" src="./libs/deflate.js"></script>
<script type="text/javascript" src="./libs/adler32cs.js/adler32cs.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.sillysvgrenderer.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.standard_fonts_metrics.js"></script>
Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.
MutationObserver (docs) to literally detect DOM changes:
Performance of MutationObserver to detect nodes in entire DOM.
Simple example:
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
onUrlChange();
}
}).observe(document, {subtree: true, childList: true});
function onUrlChange() {
console.log('URL changed!', location.href);
}
Event listener for sites that signal content change by sending a DOM event:
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,yt-navigate-finish
used by Youtube,Periodic checking of DOM via setInterval:
Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.
Cloaking History API:
let _pushState = History.prototype.pushState;
History.prototype.pushState = function (state, title, url) {
_pushState.call(this, state, title, url);
console.log('URL changed', url)
};
Listening to hashchange, popstate events:
window.addEventListener('hashchange', e => {
console.log('URL hash changed', e);
doSomething();
});
window.addEventListener('popstate', e => {
console.log('State changed', e);
doSomething();
});
All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).
Now let's look at the background script.
There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:
manifest.json:
declare background/event page
declare content script
add "tabs"
permission.
background.js
var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (rxLookfor.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
content.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'url-update') {
// doSomething();
}
});
A LINQ approach:
string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'";
string s1 = String.Join("", s.Where(c => c != '\n' && c != '\r' && c != '\t'));
I just encountered this exception and in my case it was cause by a white space between asp:content elements
So, this failed:
<asp:content runat="server" ContentPlaceHolderID="Header">
Header
</asp:content>
<asp:Content runat="server" ContentPlaceHolderID="Content">
Content
</asp:Content>
But removing the white spaces between the elements worked:
<asp:content runat="server" ContentPlaceHolderID="Header">
Header
</asp:content><asp:Content runat="server" ContentPlaceHolderID="Content">
Content
</asp:Content>
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).
Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
/* if you prefer to functionize and use onclick= rather then the .on bind
function hide_show(){
$(this).hide();
$("#hidden-div").show();
}
*/
$(function(){
$("#chkbtn").on('click',function() {
$(this).hide();
$("#hidden-div").show();
});
});
</script>
<style>
.hidden-div {
display:none
}
</style>
</head>
<body>
<div class="reform">
<form id="reform" action="action.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="type" value="" />
<fieldset>
content here...
</fieldset>
<div class="hidden-div" id="hidden-div">
<fieldset>
more content here that is hidden until the button below is clicked...
</fieldset>
</form>
</div>
<span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
</div>
</body>
</html>
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
You can do the following:
df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})
df['x']=df.a + df.b
df['y']=df.a - df.b
create column title whatever order you want in this way:
column_titles = ['x','y','a','b']
df.reindex(columns=column_titles)
This will give you desired output
After reading all the answers here - how to summarize grouped information, i decided to skip it all and just loaded one of the SQL javascript libraries. I'm using alasql, yeah it takes a few secs longer on load time but saves countless time in coding and debugging, Now to group and sum() I just use,
$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);
I know this sounds like a bit of a rant on angular/js but really SQL solved this 30+ years ago and we shouldn't have to re-invent it within a browser.
This worked for me. TypeScript Version: 2.8.3
for (const [key, value] of Object.entries(myMap)) {
console.log(key, value);
}
mythreads = threading.enumerate()
Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html
The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.
Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.
(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)
Hope it helps.
'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim theta As Double = lon1 - lon2
Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
Math.Cos(deg2rad(theta))
dist = Math.Acos(dist)
dist = rad2deg(dist)
dist = dist * 60 * 1.1515
If unit = "K" Then
dist = dist * 1.609344
ElseIf unit = "N" Then
dist = dist * 0.8684
End If
Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim R As Double = 6371 'earth radius in km
Dim dLat As Double
Dim dLon As Double
Dim a As Double
Dim c As Double
Dim d As Double
dLat = deg2rad(lat2 - lat1)
dLon = deg2rad((lon2 - lon1))
a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
d = R * c
Select Case unit.ToString.ToUpper
Case "M"c
d = d * 0.62137119
Case "N"c
d = d * 0.5399568
End Select
Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
Return rad / Math.PI * 180.0
End Function
There is OFFSET .. FETCH
in SQL Server 2012, but you will need to specify an ORDER BY
column.
If you really don't have any explicit column that you could pass as an ORDER BY
column (as others have suggested), then you can use this trick:
SELECT * FROM MyTable
ORDER BY @@VERSION
OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY
... or
SELECT * FROM MyTable
ORDER BY (SELECT 0)
OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY
We're using it in jOOQ when users do not explicitly specify an order. This will then produce pretty random ordering without any additional costs.
It's a common issue, imagine you use a cool PHP templating engine, so you have your base layout:
HEADER
BODY ==> dynamic CONTENT/PAGE
FOOTER
And of course, you read somewhere it's better to load Javascript at the bottom of the page, so your dynamic content doesnot know who is jQuery (or the $).
Also you read somewhere it's good to inline small Javascript, so imagine you need jQuery in a page, baboom, $ is not defined (.. yet ^^).
I love the solution Facebook provides
window.fbAsyncInit = function() { alert('FB is ready !'); }
So as a lazy programmer (I should say a good programmer ^^), you can use an equivalent (within your page):
window.jqReady = function() {}
And add at the bottom of your layout, after jQuery include
if (window.hasOwnProperty('jqReady')) $(function() {window.jqReady();});
It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore
, isAfter
, isSameOrBefore
, isSameOrAfter
, isBetween
So instead of 2014-03-24T01:14:000, your datetime should be either:
2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z
otherwise you may receive the following deprecation warning and the condition will evaluate to false:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...
Good luck!
This is the code that I use to remove null values from an array which does not use array lists.
String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
refinedArray[++count] = s; // Increments count and sets a value in the refined array
}
}
// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);
Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.
For example if you delete a record using ORM, and your DELETE CASCADE
will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.
Properties prop = new Properties();
prop.load(...); // FileInputStream
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream
Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery
You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/
All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter
<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">
and run js function
app_handle_listing_horisontal_scroll($('#table-listing'))
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");
AFNetworking provides async image loading into a UIImageView with placeholder support. It also supports async networking for working with APIs in general.
You missed the each=
argument to rep()
:
R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
so your example can be done with a simple
R> rep(1:8, each=20)
I am trying to improve the answer from @swilliams, this will return an array without duplicates.
// arrays for testing
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
// ascending order
var sorted_arr = arr.sort(function(a,b){return a-b;});
var arr_length = arr.length;
var results = [];
if(arr_length){
if(arr_length == 1){
results = arr;
}else{
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] != sorted_arr[i]) {
results.push(sorted_arr[i]);
}
// for last element
if (i == arr.length - 2){
results.push(sorted_arr[i+1]);
}
}
}
}
alert(results);
Quoting Yoga...
For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/
I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...
/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml
...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.
You can also do it via powershell using SET STATISTICS XML ON to get the actual plan. I've written it so that it merges multi-statement plans into one plan;
########## BEGIN : SCRIPT VARIABLES #####################
[string]$server = '.\MySQLServer'
[string]$database = 'MyDatabase'
[string]$sqlCommand = 'EXEC sp_ExampleSproc'
[string]$XMLOutputFileName = 'sp_ExampleSproc'
[string]$XMLOutputPath = 'C:\SQLDumps\ActualPlans\'
########## END : SCRIPT VARIABLES #####################
#Set up connection
$connectionString = "Persist Security Info=False;Integrated Security=true;Connection Timeout=0;Initial Catalog=$database;Server=$server"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
#Set up commands
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$command.CommandTimeout = 0
$commandXMLActPlanOn = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML ON",$connection)
$commandXMLActPlanOff = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML OFF",$connection)
$connection.Open()
#Enable session XML plan
$result = $commandXMLActPlanOn.ExecuteNonQuery()
#Execute SP and return resultsets into a dataset
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
#Set up output file name and path
[string]$fileNameDateStamp = get-date -f yyyyMMdd_HHmmss
[string]$XMLOutputFilePath = "$XMLOutputPath$XMLOutputFileName`_$fileNameDateStamp.sqlplan"
#Pull XML plans out of dataset and merge into one multi-statement plan
[int]$cntr = 1
ForEach($table in $dataset.Tables)
{
if($table.Columns[0].ColumnName -eq "Microsoft SQL Server 2005 XML Showplan")
{
[string]$fullXMLPlan = $Table.rows[0]."Microsoft SQL Server 2005 XML Showplan"
if($cntr -eq 1)
{
[regex]$rx = "\<ShowPlanXML xmlns\=.{1,}\<Statements\>"
[string]$startXMLPlan = $rx.Match($fullXMLPlan).Value
[regex]$rx = "\<\/Statements\>.{1,}\<\/ShowPlanXML\>"
[string]$endXMLPlan = $rx.Match($fullXMLPlan).Value
$startXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
}
[regex]$rx = "\<StmtSimple.{1,}\<\/StmtSimple\>"
[string]$bodyXMLPlan = $rx.Match($fullXMLPlan).Value
$bodyXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
$cntr += 1
}
}
$endXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
#Disable session XML plan
$result = $commandXMLActPlanOff.ExecuteNonQuery()
$connection.Close()
While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.
There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.
Then again, if you're not fussy about how things look, disregard this advice.
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
Based on the op voted solution, the following should be a bit more efficient:
public static byte [] hexStringToByteArray (final String s) {
if (s == null || (s.length () % 2) == 1)
throw new IllegalArgumentException ();
final char [] chars = s.toCharArray ();
final int len = chars.length;
final byte [] data = new byte [len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));
}
return data;
}
Because: the initial conversion to a char array spares the length checks in charAt
A couple of issues arise when trying to reload/source ~/.profile file. [This refers to Ubuntu linux - in some cases the details of the commands will be different]
Ad. 1)
Running this directly in terminal means that there will be no subshell created. So you can use either two commands:
source ~/.bash_profile
or
. ~/.bash_profile
In both cases this will update the environment with the contents of .profile file.
Ad 2) You can start any bash script either by calling
sh myscript.sh
or
. myscript.sh
In the first case this will create a subshell that will not affect the environment variables of your system and they will be visible only to the subshell process. After finishing the subshell command none of the exports etc. will not be applied. THIS IS A COMMON MISTAKE AND CAUSES A LOT OF DEVELOPERS TO LOSE A LOT OF TIME.
In order for your changes applied in your script to have effect for the global environment the script has to be run with
.myscript.sh
command.
In order to make sure that you script is not runned in a subshel you can use this function. (Again example is for Ubuntu shell)
#/bin/bash
preventSubshell(){
if [[ $_ != $0 ]]
then
echo "Script is being sourced"
else
echo "Script is a subshell - please run the script by invoking . script.sh command";
exit 1;
fi
}
I hope this clears some of the common misunderstandings! :D Good Luck!
Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
won't work because worksheet functions (when actually used on a worksheet) don't understand Range
or Cell
Try
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
As it has been explained here, beside of multiple extensions that perform ad or script blocking you may aware that this may happen by file names as below:
Particularly in the AdBlock Plus the character string "-300x600" is causing the Failed to Load Resource ERR_BLOCKED_BY_CLIENT problem.
As shown in the picture, some of the images were blocked because of the '-300x600' pattern in their name, that particular text pattern matches an expression list pattern in the AdBlock Plus.
Try this:
Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);
For example:
String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
Log.e("Regex"," Regex result: " + m.group())
}
Output:
10 Ene
3.08%
If you get "undefined" to all of your console.log calls, that probably means you still have an old firebuglite loaded (firebug.js). It will override all the valid functions of IE8's console.log even though they do exist. This is what happened to me anyway.
Check for other code overriding the console object.
You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.
this is the query you need:
SELECT b.id, a.home,b.[datetime],b.player,a.resource FROM
(SELECT home,MAX(resource) AS resource FROM tbl_1 GROUP BY home) AS a
LEFT JOIN
(SELECT id,home,[datetime],player,resource FROM tbl_1) AS b
ON a.resource = b.resource WHERE a.home =b.home;
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
If you're looking for the RPM.
rpm -qa | grep MySQL
Most of it's data is stored in /var/lib/mysql so that's another good place to look.
If it is installed
which mysql
will give you the location of the binary.
You could also do an
updatedb
and a
locate mysql
to find any mysql files.
TextPad will allow you to perform this operation.
example:
test this sentence
Find what: \([^ ]*\) \(.*\)
Replace with: \U\1\E \2
the \U
will cause all following chars to be upper
the \E
will turn off the \U
the result will be:
TEST this sentence
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
The code that worked for me on a Windows 10 machine using Sublime Text 3
{
"cmd" : "gcc $file_name -o ${file_base_name}",
"selector" : "source.c",
"shell" : true,
"working_dir" : "$file_path",
"variants":
[
{
"name": "Run",
"cmd": "${file_base_name}"
}
]
}
Below solution may help you.
var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
UnmanagedAssetRegistryID = grouped.Key,
Count = grouped.Count()
};
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
For me (selectionChange)
and the suggested (onSelectionChange)
didn't work and I'm not using ReactiveForms
. What I ended up doing was using the (valueChange)
event like:
<mat-select (valueChange)="someFunction()">
And this worked for me
I know it is old but according to my own theme editor with default light theme, default
textPrimaryColor = #000000
and
textColorPrimaryDark = #757575
Check it out -
<input type="button" id="btnclick" value="click" />
var intervalA;
var intervalB;
$(document).ready(function () {
$('#btnclick').click(function () {
blinkFont();
setTimeout(function () {
clearInterval(intervalA);
clearInterval(intervalB);
}, 5000);
});
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("blinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
<div id="blink" class="live-chat">
<span>This is blinking text and background</span>
</div>
It's called the carriage return, or \r
Use
print i/len(some_list)*100," percent complete \r",
The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)
Also, don't forget to terminate with a print ""
to get at least a finalizing newline!
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
I prefer to use
require_once('phpfile.php');
lots of options out there for you. and a good way to keep things clean.
Another option is to add a new OnClickListener as parameter in setOnClickListener() and overriding the onClick()-method:
mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));
// Add onClickListener to mycards_button
mycards_button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Start new activity
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
}
});
// Add onClickListener to exit_button
exit_button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Display alertDialog
MyAlertDialog();
}
});
If you don't want to use classes (which you really should), the only way to accomplish what you want is by saving the changing styles first:
var oldFontSize = $(this).css("font-size");
var oldBackgroundColor = $(this).css("background-color");
// set style
// do your thing
$(this).css("font-size",oldFontSize);
// etc...
From Excel Macro Security - www.excelfunctions.net:
Macro Security in Excel 2007, 2010 & 2013:
.....
The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :
'Disable all macros without notification'
This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Disable all macros with notification'
This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.
'Disable all macros except digitally signed macros'
This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Enable all macros'
This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.
If you trust the macros and are ok with enabling them, select this option:
'Enable all macros'
and this dialog box should not show up for macros.
As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.
Try:
select id, game, min(point) from t
group by id
JS provides the tools to do this the right way. Try the demo snippet.
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
this.classList.remove('mouse-down');_x000D_
alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling. It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px';
_x000D_
button{_x000D_
text-transform: uppercase;_x000D_
background-color:rgba(66, 66, 66,0.3);_x000D_
border:none;_x000D_
font-size:4em;_x000D_
color:white;_x000D_
-webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
-moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
-webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
-moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52); _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
display: flex;_x000D_
flex-flow: row nowrap ;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items: center;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
order:1;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
min-width: 0;_x000D_
min-height: auto;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<meta name="description" content="3d Button Configuration" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section id="box">_x000D_
<button>_x000D_
Submit_x000D_
</button>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
Use the CSS property border on the <td>
s following the <tr>
s you do not want to have the border.
In my example I made a class noBorder
that I gave to one <tr>
. Then I use a simple selector tr.noBorder td
to make the border go away for all the <td>
s that are inside of <tr>
s with the noBorder
class by assigning border: 0
.
Note that you do not need to provide the unit (i.e. px
) if you set something to 0
as it does not matter anyway. Zero is just zero.
table, tr, td {_x000D_
border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
border: 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>A1</td>_x000D_
<td>B1</td>_x000D_
<td>C1</td>_x000D_
</tr>_x000D_
<tr class="noBorder">_x000D_
<td>A2</td>_x000D_
<td>B2</td>_x000D_
<td>C2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Here's the output as an image:
Once you have your image, you can use
$ docker tag <image> <newName>/<repoName>:<tagName>
Build and tag the image with creack/node:latest
$ ID=$(docker build -q -t creack/node .)
Add a new tag
$ docker tag $ID creack/node:0.10.24
You can use this and skip the -t part from build
$ docker tag $ID creack/node:latest
Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:
var lastSelectedOption = null;_x000D_
_x000D_
DDChange = function(Dd) {_x000D_
//Blur after change so that clicking again without _x000D_
//losing focus re-triggers onfocus._x000D_
Dd.blur();_x000D_
_x000D_
//The rest is whatever you want in the change._x000D_
var tcs = $("span.on_change_times");_x000D_
tcs.html(+tcs.html() + 1);_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};_x000D_
_x000D_
DDFocus = function(Dd) {_x000D_
lastSelectedOption = Dd.prop("selectedIndex");_x000D_
Dd.prop("selectedIndex", -1);_x000D_
_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};_x000D_
_x000D_
//On blur, set it back to the value before they clicked _x000D_
//away without selecting an option._x000D_
//_x000D_
//This is what is typically weird for the user since they _x000D_
//might click on the dropdown to look at other options,_x000D_
//realize they didn't what to change anything, and _x000D_
//click off the dropdown._x000D_
DDBlur = function(Dd) {_x000D_
if (Dd.prop("selectedIndex") === -1)_x000D_
Dd.prop("selectedIndex", lastSelectedOption);_x000D_
_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select id="Dd" onchange="DDChange($(this));" onfocus="DDFocus($(this));" onblur="DDBlur($(this));">_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
</select>_x000D_
<br/>_x000D_
<br/>Selected index: <span class="selected_index"></span>_x000D_
<br/>Times onchange triggered: <span class="on_change_times">0</span>
_x000D_
This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.
The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.
Replace @Restcontroller
with @controller
. @Restcontroller
returns only content not html and jsp pages.
In my case, I solved it with the following:
app.set('views', `${__dirname}/views`);
app.use(express.static(`${__dirname}/public`));
I needed to start node app.min.js
from /dist
folder.
My folder structure was:
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
maxObj = db.CollectionName.aggregate([
{
$group : { _id: '$item', maxValue: { $max: '$fieldName' } }
}
];
fieldNextValue = maxObj.maxValue + 1;
$fieldName
is the name of your field, but without the $
sign.
CollectionName
is the name of your collection.
The reason I am not using count()
is that the produced value could meet an existing value.
The creation of an enforcing unique index could make it safer:
db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )
Override all single element
$("*").css("cursor", "progress");
When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me
eg:
$ curl ifconfig.me/ip
Over the years I have seen many of these sites come and go, I find this DNS based method more robust:
$ dig +short myip.opendns.com @resolver1.opendns.com
I have this handy alias in my ~/.bashrc
:
alias wip='dig +short myip.opendns.com @resolver1.opendns.com'
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:
https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html
Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).
Some example code (this example makes an RGraph chart):
<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>
<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>
<script>
// Create a new RGraph Sheets object using the spreadsheet's key and
// the callback function that creates the chart. The RGraph.Sheets object is
// passed to the callback function as an argument so it doesn't need to be
// assigned to a variable when it's created
new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
{
// Get the labels from the spreadsheet by retrieving part of the first row
var labels = sheet.get('A2:A7');
// Use the column headers (ie the names) as the key
var key = sheet.get('B1:E1');
// Get the data from the sheet as the data for the chart
var data = [
sheet.get('B2:E2'), // January
sheet.get('B3:E3'), // February
sheet.get('B4:E4'), // March
sheet.get('B5:E5'), // April
sheet.get('B6:E6'), // May
sheet.get('B7:E7') // June
];
// Create and configure the chart; using the information retrieved above
// from the spreadsheet
var bar = new RGraph.Bar({
id: 'cvs',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxisLabels: labels,
xaxisLabelsOffsety: 5,
colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
yaxis: false,
marginLeft: 40,
marginBottom: 35,
marginRight: 40,
key: key,
keyBoxed: false,
keyPosition: 'margin',
keyTextSize: 12,
textSize: 12,
textAccessible: false,
axesColor: '#aaa'
}
}).wave();
});
</script>
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
I needed to do the same thing, so I googled how and came to stack overflow, where the OP was having the same issue... So my findings.. I tried renaming files from all different directions AND my conclusion was basically it's taking me too long. SOOOO I ended up just installing version 7 from here:
https://www.apachefriends.org/index.html (kill services and quit out of xampp before attempting)
When asked where to put the directory name it like so (give it a different name):
and
DONEZO! Now just make sure to kill services and quit before swapping back and forth and you have 2 sterile XAMPP envs to play in..
Hooray! now I can actually get to work!
The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.
If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.
See:
File fnew=new File("/tmp/rose.jpg");
BufferedImage originalImage=ImageIO.read(fnew);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos );
byte[] imageInByte=baos.toByteArray();
Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.
If anaconda is fully updated, a simple "conda init zsh" should work. Navigate into the anaconda3 folder using
cd /path/to/anaconda3/
of course replacing "/path/to/anaconda/" with "~/anaconda3" or "/anaconda3" or wherever the "anaconda3" folder is kept.
To make sure it's updated, run
./bin/conda update --prefix . anaconda
After this, running
./bin/conda init zsh
(or whatever shell you're using) will finish the job cleanly.
For capital letters:
i=67
letters=({A..Z})
echo "${letters[$i-65]}"
Output:
C
Help
/ Install New Software...
Add
buttonAdd Repository
dialog that appears, click the Archive
button next to the Location
fieldOK
You could also just copy plugins to the eclipse/plugins
directory, but it's not recommended.
<ul id="category-tabs">
<li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
<ul>
<li><a href="javascript:void">item 1</a></li>
<li><a href="javascript:void">item 2</a></li>
<li><a href="javascript:void">item 3</a></li>
</ul>
</li> </ul>
//Jquery
$(document).ready(function() {
$('li').click(function() {
$('i').toggleClass('fa-plus-square fa-minus-square');
});
});
To parallelize this...
for i in $(whatever_list) ; do
do_something $i
done
Translate it to this...
for i in $(whatever_list) ; do echo $i ; done | ## execute in parallel...
(
export -f do_something ## export functions (if needed)
export PATH ## export any variables that are required
xargs -I{} --max-procs 0 bash -c ' ## process in batches...
{
echo "processing {}" ## optional
do_something {}
}'
)
--max-procs
based on how much parallelism you want (0
means "all at once").xargs
-- but it isn't always installed by default.for
loop isn't strictly necessary in this example since echo $i
is basically just regenerating the output of $(whatever_list
). I just think the use of the for
keyword makes it a little easier to see what is going on.Here's a simplified working example...
for i in {0..5} ; do echo $i ; done |xargs -I{} --max-procs 2 bash -c '
{
echo sleep {}
sleep 2s
}'
I made a button I can reuse anywhere on my app.
Create this component
import { Location } from '@angular/common';
import { Component, Input } from '@angular/core';
@Component({
selector: 'back-button',
template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
@Input()color: string;
constructor(private location: Location) { }
goBack() {
this.location.back();
}
}
Then add it to any template when you need a back button.
<back-button color="primary"></back-button>
Note: This is using Angular Material, if you aren't using that library then remove the mat-button
and color
.
The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.
You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.
Example:
File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);
lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));
The above example reads a text file composed of 50 lines in the following format:
[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN
Disclamer: I wrote this library
So basically it is an old style and do not use it for newer version of PHP. Better to use Public keyword instead;if you are not in love with var keyword. So instead of using
class Test {
var $name;
}
Use
class Test {
public $name;
}
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Make sure your routing.yml
file has 'id'
specified in it. In other words, it should look like:
_category:
path: /category/{id}
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);
Clear repository is one possible solution.
Windows -> delete all subfolders in the maven repository:
C:\Users\YourUserName.m2\repository
In more current versions of MongoDB, I have 3.2.10, it is stored be default into
/var/lib/mongodb
There are two steps here:
X$newdate <- strptime(as.character(X$date), "%d/%m/%Y")
Now the newdate
column should be of type Date
.
format()
or strftime()
:format(X$newdate, "%Y-%m-%d")
A more complete example:
R> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"),
+ mid=c(0.8378,0.8457,0.8147))
R> nzd
date mid
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
R> nzd$newdate <- strptime(as.character(nzd$date), "%d/%m/%Y")
R> nzd$txtdate <- format(nzd$newdate, "%Y-%m-%d")
R> nzd
date mid newdate txtdate
1 31/08/2011 0.8378 2011-08-31 2011-08-31
2 31/07/2011 0.8457 2011-07-31 2011-07-31
3 30/06/2011 0.8147 2011-06-30 2011-06-30
R>
The difference between columns three and four is the type: newdate
is of class Date
whereas txtdate
is character.
why dont you do something like:
re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);
to check if your input contain any special char
I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.
Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using node-uuid and the password can be hashed using pbkdf2
Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.
When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.
Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.
If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.
The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.
If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.
Summary:
An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.
Use the following snippet to add a Switch to your layout via XML:
<Switch
android:id="@+id/on_off_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON"/>
Then in your Activity's onCreate method, get a reference to your Switch and set its OnCheckedChangeListener:
Switch onOffSwitch = (Switch) findViewById(R.id.on_off_switch);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("Switch State=", ""+isChecked);
}
});
If a caching system correctly implements no-store, then you wouldn't need no-cache. But not all do. Additionally, some browsers implement no-cache like it was no-store. Thus, while not strictly required, it's probably safest to include both.
I find the best way to do this is duplicate a Chrome or Chrome Canary shortcut on your windows desktop. Rename this shortcut to "NO CORS" then edit the properties of that shortcut.
in the target add --disable-web-security --user-data-dir="D:/Chrome"
to the end of the target path.
your target should look something like this:
Update: New Flags added.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:/Chrome"
I have solved it this way.
Go to your project file let's say project/name/bin and delete everything within the bin folder. (this will then give you another error which you can solve this way)
then in your visual studio right click project's References folder, to open NuGet Package Manager.
Go to browse and install "DotNetCompilerPlatform".
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
curr_year = curr_year.toString().substr(2,2);
document.write(curr_date+"-"+curr_month+"-"+curr_year);
You can change this as your need..
You can try this lightweight small plugin.
It will allow you customize it as per your requirement. It will have Expand/Collapse functionality.
<item name="editTextColor">@color/white</item>
<item name="android:textColor">@color/white</item>
<item name="android:textColorHint">@color/gray</item>
<item name="android:textColorPrimary">@color/gray</item>
<item name="colorControlNormal">@color/gray</item>
<item name="colorControlActivated">@color/white</item>
<item name="colorControlHighlight">#30FFFFFF</item>
Set it to use as much memory as it wants with:
COMPOSER_MEMORY_LIMIT=-1 composer update
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
You need to use convert in order by as well:
SELECT Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Sometimes it's necessary to print out server's response for debugging purposes. Here's a function I use:
extension Dictionary {
var json: String {
let invalidJson = "Not a valid JSON"
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
} catch {
return invalidJson
}
}
func printJson() {
print(json)
}
}
Example of use:
(lldb) po dictionary.printJson()
{
"InviteId" : 2,
"EventId" : 13591,
"Messages" : [
{
"SenderUserId" : 9514,
"MessageText" : "test",
"RecipientUserId" : 9470
},
{
"SenderUserId" : 9514,
"MessageText" : "test",
"RecipientUserId" : 9470
}
],
"TargetUserId" : 9470,
"InvitedUsers" : [
9470
],
"InvitingUserId" : 9514,
"WillGo" : true,
"DateCreated" : "2016-08-24 14:01:08 +00:00"
}
require 'time'
require 'date'
t = Time.now
d = DateTime.now
dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)
The accepted answer is incorrect.
createNativeQuery
will always return a Query
:
public Query createNativeQuery(String sqlString, Class resultClass);
Calling getResultList
on a Query
returns List
:
List getResultList()
When assigning (or casting) to List<MyEntity>
, an unchecked assignment warning is produced.
Whereas, createQuery
will return a TypedQuery
:
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
Calling getResultList
on a TypedQuery
returns List<X>
.
List<X> getResultList();
This is properly typed and will not give a warning.
With createNativeQuery
, using ObjectMapper
seems to be the only way to get rid of the warning. Personally, I choose to suppress the warning, as I see this as a deficiency in the library and not something I should have to worry about.
I had this same issue, and fixed it by modifying my project's .iml file:
From:
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/wrong/entry/here" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
To:
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
Somehow a package folder became specified as the root source directory when this project was imported.
There is an easier alternative to change the color of the title bar, by using the v7 appcompat support library provided by Google.
See this link on how to to setup this support library: https://developer.android.com/tools/support-library/setup.html
Once you have done that, it's sufficient to add the following lines to your res/values/styles.xml file:
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<!-- Actionbar Theme -->
<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">@color/titlebackgroundcolor</item>
</style>
(assuming that "titlebackgroundcolor" is defined in your res/values/colors.xml, e.g.:
<color name="titlebackgroundcolor">#0000AA</color>
)
Try this:
import * as moment from 'moment';
ngOnInit() {
this.date = moment().format("YYYY Do MMM");
}
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
Usage: If you're going to store information that you want to access on different web pages, you can use SessionState
If you want to store information that you want to access from the same page, then you can use Viewstate
Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.
The SessionState will clear in the following conditions
It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:
s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)
Note the *s
intead of just s
in os.path.join(*s)
. Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript
Here is a helpful website on using appcmd to export/import a site configuration. http://www.microsoftpro.nl/2011/01/27/exporting-and-importing-sites-and-app-pools-from-iis-7-and-7-5/
For Indian Mobile Numbers
Regular Expression to validate 11 or 12 (starting with 0 or 91) digit number
String regx = "(0/91)?[7-9][0-9]{9}";
String mobileNumber = "09756432848";
check
if(mobileNumber.matches(regx)){
"VALID MOBILE NUMBER"
}else{
"INVALID MOBILE NUMBER"
}
You can check for 10 digit mobile number by removing "(0/91)?"
from the regular expression i.e. regx
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});
For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution
ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>
It's Works
.ts -> pi = 3.1415
.html -> {{ pi | number : '1.0-2' }}
Ouput -> 3.14
https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html
this works for me!!! thanks!!
Additionally, if you're building a ReSTful API, browser leakage and http referer issues are mostly mitigated as the client may not be a browser and you may not have people clicking links.
If this is the case I'd recommend oAuth2 login to obtain a bearer token. In which case the only sensitive data would be the initial credentials...which should probably be in a post request anyway
I had lots of fun debugging an issue where a <h:commandLink>
's action in richfaces
datatable
refused to fire. The table used to work at some point but stopped for no apparent reason. I left no stone unturned, only to find out that my rich:datatable
was using the wrong rowKeyConverter
which returned nulls that richfaces happily used as row keys. This prevented my <h:commandLink>
action from getting called.
This will get the index of the selected option on change:
$('select').change(function(){_x000D_
console.log($('option:selected',this).index()); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="CCards">_x000D_
<option value="0">Select Saved Payment Method:</option>_x000D_
<option value="1846">test xxxx1234</option>_x000D_
<option value="1962">test2 xxxx3456</option>_x000D_
</select>
_x000D_
If you only need the dynamic properties for JSON serialization/deserialization, eg if your API accepts a JSON object with different fields depending on context, then you can use the JsonExtensionData
attribute available in Newtonsoft.Json or System.Text.Json.
Example:
public class Pet
{
public string Name { get; set; }
public string Type { get; set; }
[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }
}
Then you can deserialize JSON:
public class Program
{
public static void Main()
{
var bingo = JsonConvert.DeserializeObject<Pet>("{\"Name\": \"Bingo\", \"Type\": \"Dog\", \"Legs\": 4 }");
Console.WriteLine(bingo.AdditionalData["Legs"]); // 4
var tweety = JsonConvert.DeserializeObject<Pet>("{\"Name\": \"Tweety Pie\", \"Type\": \"Bird\", \"CanFly\": true }");
Console.WriteLine(tweety.AdditionalData["CanFly"]); // True
tweety.AdditionalData["Color"] = "#ffff00";
Console.WriteLine(JsonConvert.SerializeObject(tweety)); // {"Name":"Tweety Pie","Type":"Bird","CanFly":true,"Color":"#ffff00"}
}
}
Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
in stead of
ModelState.AddRuleViolations(dinner.GetRuleViolations());
In my case I had a panda Series where the values are tuples of characters:
Out[67]
0 (H, H, H, H)
1 (H, H, H, T)
2 (H, H, T, H)
3 (H, H, T, T)
4 (H, T, H, H)
Therefore I could use indexing to filter the series, but to create the index I needed apply
. My condition is "find all tuples which have exactly one 'H'".
series_of_tuples[series_of_tuples.apply(lambda x: x.count('H')==1)]
I admit it is not "chainable", (i.e. notice I repeat series_of_tuples
twice; you must store any temporary series into a variable so you can call apply(...) on it).
There may also be other methods (besides .apply(...)
) which can operate elementwise to produce a Boolean index.
Many other answers (including accepted answer) using the chainable functions like:
.compress()
.where()
.loc[]
[]
These accept callables (lambdas) which are applied to the Series, not to the individual values in those series!
Therefore my Series of tuples behaved strangely when I tried to use my above condition / callable / lambda, with any of the chainable functions, like .loc[]
:
series_of_tuples.loc[lambda x: x.count('H')==1]
Produces the error:
KeyError: 'Level H must be same as name (None)'
I was very confused, but it seems to be using the Series.count series_of_tuples.count(...)
function , which is not what I wanted.
I admit that an alternative data structure may be better:
This creates a series of strings (i.e. by concatenating the tuple; joining the characters in the tuple on a single string)
series_of_tuples.apply(''.join)
So I can then use the chainable Series.str.count
series_of_tuples.apply(''.join).str.count('H')==1
If selected more 1 file:
$("input[type="file"]").change(function() {
var files = $("input[type="file"]").prop("files");
var names = $.map(files, function(val) { return val.name; });
$(".some_div").text(names);
});
files
will be a FileList
object. names
is an array of strings (file names).
Instead of allocating space, et al, an approach using ByteBuffer
from java.nio
....
byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};
// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt(); // 72
Now, to go the other way.
ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array(); // [0, 0, 0, 72] {0x48 = 72}
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
You can simply use base64.urlsafe_b64decode(data)
if you are trying to decode a web image. It will automatically take care of the padding.
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
This might be obvious, but it might help someone who has never seen it before. This also happens for regular functions if you mistakenly assign a parameter by position and explicitly by name.
>>> def foodo(thing=None, thong='not underwear'):
... print thing if thing else "nothing"
... print 'a thong is',thong
...
>>> foodo('something', thing='everything')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foodo() got multiple values for keyword argument 'thing'
Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.
Check your capitalization!
Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.
Whenever you get a ClassNotFound Exception check the following:
C# 7.0 supports binary literals (and optional digit separators via underscore characters).
An example:
int myValue = 0b0010_0110_0000_0011;
You can also find more information on the Roslyn GitHub page.
You can make up a class, RestTemplateXML, which extends RestTemplate. Then override doExecute(URI, HttpMethod, RequestCallback, ResponseExtractor<T>)
, and explicitly get response-headers
and set content-type
to application/xml
.
Now Spring reads the headers and knows that it is `application/xml'. It is kind of a hack but it works.
public class RestTemplateXML extends RestTemplate {
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
logger.info( RestTemplateXML.class.getSuperclass().getSimpleName() + ".doExecute() is overridden");
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
// Set ContentType to XML
response.getHeaders().setContentType(MediaType.APPLICATION_XML);
if (!getErrorHandler().hasError(response)) {
logResponseStatus(method, url, response);
}
else {
handleResponseError(method, url, response);
}
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + url + "\":" + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response) {
if (logger.isDebugEnabled()) {
try {
logger.debug(method.name() + " request for \"" + url + "\" resulted in " +
response.getRawStatusCode() + " (" + response.getStatusText() + ")");
}
catch (IOException e) {
// ignore
}
}
}
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException {
if (logger.isWarnEnabled()) {
try {
logger.warn(method.name() + " request for \"" + url + "\" resulted in " +
response.getRawStatusCode() + " (" + response.getStatusText() + "); invoking error handler");
}
catch (IOException e) {
// ignore
}
}
getErrorHandler().handleError(response);
}
}
Spring exposes the current HttpServletRequest
object (as well as the current HttpSession
object) through a wrapper object of type ServletRequestAttributes
. This wrapper object is bound to ThreadLocal and is obtained by calling the static
method RequestContextHolder.currentRequestAttributes()
.
ServletRequestAttributes
provides the method getRequest()
to get the current request, getSession()
to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Note that the RequestContextHolder.currentRequestAttributes()
method returns an interface and needs to be typecasted to ServletRequestAttributes
that implements the interface.
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
Actually you can set the default thread culture and UI culture, but only with Framework 4.5+
I put in this static constructor
static MainWindow()
{
CultureInfo culture = CultureInfo
.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
var dtf = culture.DateTimeFormat;
dtf.ShortTimePattern = (string)Microsoft.Win32.Registry.GetValue(
"HKEY_CURRENT_USER\\Control Panel\\International", "sShortTime", "hh:mm tt");
CultureInfo.DefaultThreadCurrentUICulture = culture;
}
and put a breakpoint in the Convert method of a ValueConverter to see what arrived at the other end. CultureInfo.CurrentUICulture ceased to be en-US and became instead en-AU complete with my little hack to make it respect regional settings for ShortTimePattern.
Hurrah, all is well in the world! Or not. The culture parameter passed to the Convert method is still en-US. Erm, WTF?! But it's a start. At least this way
CultureInfo.CurrentUICulture
string.Format("{0}", DateTime.Now)
will use your customised regional settingsIf you can't use version 4.5 of the framework then give up on setting CurrentUICulture as a static property of CultureInfo and set it as a static property of one of your own classes. This won't fix default behaviour of string.Format or make StringFormat work properly in bindings then walk your app's logical tree to recreate all the bindings in your app and set their converter culture.
The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Example:
your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Output:
>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
This is very possible. It just takes a little CSS trickery!
div.border {_x000D_
border: 1px solid #000;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div.border:before {_x000D_
position: absolute;_x000D_
display: block;_x000D_
content: '';_x000D_
border: 1px solid red;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}
_x000D_
<div class="border">Hi I have two border colors<br />I am also Fluid</div>
_x000D_
Is that what you are looking for?
It's programming where the architecture of your system fits the REST style laid out by Roy Fielding in his thesis. Since this is the architectural style that describes the web (more or less), lots of people are interested in it.
Bonus answer: No. Unless you're studying software architecture as an academic or designing web services, there's really no reason to have heard the term.
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution
Place this at the top of your PHP script and let your script loose!
Taken from Increase PHP Script Execution Time Limit Using ini_set()
Try
gadget_url.value=''
addGadgetUrl.addEventListener('click', () => {_x000D_
gadget_url.value = '';_x000D_
});
_x000D_
<div>_x000D_
<p>URL</p>_x000D_
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />_x000D_
<input type="button" id="addGadgetUrl" value="add gadget" />_x000D_
<br>_x000D_
<span id="error"></span>_x000D_
</div>
_x000D_
I don't know why so many downovotes (and no comments) - however (for future readers) don't think that this solution not work - It works with html provided in OP question and this is SHORTEST working solution - you can try it by yourself HERE
I've set the default action in windows to "Open with WinZip". This makes it easy to manage JARs as archives. You can even add/remove files manually.
Jan 19th, 2020 Self Signed Certificate ISSUE FIX:
To play video , image , calling webservice for any self signed certificate or connecting to any unsecured url just call this method before performing any action , it will fix your issue regarding certificate issue :
KOTLIN CODE
private fun disableSSLCertificateChecking() {
val hostnameVerifier = object: HostnameVerifier {
override fun verify(s:String, sslSession: SSLSession):Boolean {
return true
}
}
val trustAllCerts = arrayOf<TrustManager>(object: X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
//val acceptedIssuers:Array<X509Certificate> = null
@Throws(CertificateException::class)
override fun checkClientTrusted(arg0:Array<X509Certificate>, arg1:String) {// Not implemented
}
@Throws(CertificateException::class)
override fun checkServerTrusted(arg0:Array<X509Certificate>, arg1:String) {// Not implemented
}
})
try
{
val sc = SSLContext.getInstance("TLS")
sc.init(null, trustAllCerts, java.security.SecureRandom())
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier)
}
catch (e: KeyManagementException) {
e.printStackTrace()
}
catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
}
I'm not sure if this is helping you, but I guess that when you do a svn add mysql
after you've deleted it it will just reinstantiate the directory (so don't do a mkdir yourself). If you create a directory yourself svn expects a .svn directory inside it because it already 'knows' about it.
Yes to your second and third questions -- that's what you need to do as you cannot have multiple 'lvalues' on the left of an assignment.
Maybe, you can use moment.js which in my opinion is the best JavaScript library for parsing, formatting and working with dates client-side. You could use something like:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');_x000D_
var jsDate = momentDate.toDate();_x000D_
_x000D_
// Now, you can run any JavaScript Date method_x000D_
_x000D_
jsDate.toLocaleString();
_x000D_
The advantage of using a library like moment.js is that your code will work perfectly even in legacy browsers like IE 8+.
Here is the documenation about parsing methods: https://momentjs.com/docs/#/parsing/
Try this:
var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
That is called a shebang, it tells the shell what program to interpret the script with, when executed.
In your example, the script is to be interpreted and run by the bash shell.
Some other example shebangs are:
(From Wikipedia)
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby
and a few additional ones I can think off the top of my head, such as:
#!/bin/ksh
#!/bin/awk
#!/bin/expect
In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.
Response to updated portion:
It depends on what /bin/sh
actually points to on your system. Often it is just a symlink to /bin/bash
. Sometimes portable scripts are written with #!/bin/sh
just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh
on that particular system (maybe it points to /bin/bash
, /bin/ksh
or /bin/zsh
)
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
https://stackoverflow.com/a/40919650/4976373
Unfortunately, I believe that your app "contains encryption" in terms of US BIS even if you just use HTTPS (if your app is not an exception included in question 2).
Quote from FAQ on iTunes Connect:
"How do I know if I can follow the Exporter Registration and Reporting (ERN) process?
If your app uses, accesses, implements or incorporates industry standard encryption algorithms for purposes other than those listed as exemptions under question 2, you need to submit for an ERN authorization. Examples of standard encryption are: AES, SSL, https. This authorization requires that you submit an annual report to two U.S. Government agencies with information about your app every January. "
"2nd Question: Does your product qualify for any exemptions provided under category 5 part 2?
There are several exemptions available in US export regulations under Category 5 Part 2 (Information Security & Encryption regulations) for applications and software that use, access, implement or incorporate encryption.
All liabilities associated with misinterpretation of the export regulations or claiming exemption inaccurately are borne by owners and developers of the apps.
You can answer “YES” to the question if you meet any of the following criteria:
(i) if you determine that your app is not classified under Category 5, Part 2 of the EAR based on the guidance provided by BIS at encryption question. The Statement of Understanding for medical equipment in Supplement No. 3 to Part 774 of the EAR can be accessed at Electronic Code of Federal Regulations site. Please visit the Question #15 in the FAQ section of the encryption page for sample items BIS has listed that can claim Note 4 exemptions.
(ii) your app uses, accesses, implements or incorporates encryption for authentication only
(iii) your app uses, accesses, implements or incorporates encryption with key lengths not exceeding 56 bits symmetric, 512 bits asymmetric and/or 112 bit elliptic curve
(iv) your app is a mass market product with key lengths not exceeding 64 bits symmetric, or if no symmetric algorithms, not exceeding 768 bits asymmetric and/or 128 bits elliptic curve.
Please review Note 3 in Category 5 Part 2 to understand the criteria for mass market definition.
(v) your app is specially designed and limited for banking use or ‘money transactions.’ The term ‘money transactions’ includes the collection and settlement of fares or credit functions.
(vi) the source code of your app is “publicly available”, your app distributed at free of cost to general public, and you have met the notification requirements provided under 740.13.(e).
Please visit encryption web page in case you need further help in determining if your app qualifies for any exemptions.
If you believe that your app qualifies for an exemption, please answer “YES” to the question."
You should access frames from window
and not document
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
I got this Error after re-creating a Repository on my Server (Codebeamer) - the User in Question lacked some permissions, after granting them, everything worked fine.
if you use zsh.please add flowing string to the line 'export PATH="..."' in file '~/.zshrc'
:/opt/local/bin:/opt/local/sbin
Following solution is better than bootbox.js, because
digimango.messagebox.js:
const dialogTemplate = '\_x000D_
<div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
<div class ="modal-dialog">\_x000D_
<div class ="modal-content">\_x000D_
<div class ="modal-body">\_x000D_
<p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
<p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
</div>\_x000D_
<div class ="modal-footer">\_x000D_
<button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
<button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
var iDiv = document.createElement('div');_x000D_
iDiv.id = 'digimango_MessageBoxContainer';_x000D_
document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
$("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
}_x000D_
_x000D_
var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
if (options == null) {_x000D_
okButtonName = 'OK';_x000D_
cancelButtonName = null;_x000D_
showTextBox = null;_x000D_
textBoxDefaultText = null;_x000D_
} else {_x000D_
okButtonName = options.okButtonName;_x000D_
cancelButtonName = options.cancelButtonName;_x000D_
showTextBox = options.showTextBox;_x000D_
textBoxDefaultText = options.textBoxDefaultText;_x000D_
}_x000D_
_x000D_
if (showTextBox == true) {_x000D_
if (textBoxDefaultText == null)_x000D_
$('#digimango_messageBoxTextArea').val('');_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
$('#digimango_messageBoxTextArea').show();_x000D_
}_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
if (okButtonName != null)_x000D_
$('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
else_x000D_
$('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
if (cancelButtonName == null)_x000D_
$('#digimango_messageBoxCancelButton').hide();_x000D_
else {_x000D_
$('#digimango_messageBoxCancelButton').show();_x000D_
$('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
}_x000D_
_x000D_
$('#digimango_messageBoxOkButton').unbind('click');_x000D_
$('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
$('#digimango_messageBoxCancelButton').unbind('click');_x000D_
$('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
if (significance == 'error')_x000D_
content.attr('class', 'text-danger');_x000D_
else if (significance == 'warning')_x000D_
content.attr('class', 'text-warning');_x000D_
else_x000D_
content.attr('class', 'text-success');_x000D_
_x000D_
content.html(msg);_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$("#digimango_messageBox").modal();_x000D_
_x000D_
digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
// JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
// thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
// clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
// how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
// not execute the last line in this function._x000D_
if (typeof (event.data.callback) != 'undefined')_x000D_
event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
To use digimango.messagebox.js:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title>A useful generic message box</title>_x000D_
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
<script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
function testAlert() {_x000D_
messageBox('Something went wrong!', 'error');_x000D_
}_x000D_
_x000D_
function testAlertWithCallback() {_x000D_
messageBox('Something went wrong!', 'error', null, function () {_x000D_
messageBox('OK clicked.');_x000D_
});_x000D_
}_x000D_
_x000D_
function testConfirm() {_x000D_
messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
});_x000D_
}_x000D_
_x000D_
function testPrompt() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
function testPromptWithDefault() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
<a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
<a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
<a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
<a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe.
Hoping to get an answer regarding the obj in a_list
language construct here.
The strategy of using .setType("message/rfc822")
or ACTION_SEND
seems to also match apps that aren't email clients, such as Android Beam and Bluetooth.
Using ACTION_SENDTO
and a mailto:
URI seems to work perfectly, and is recommended in the developer documentation. However, if you do this on the official emulators and there aren't any email accounts set up (or there aren't any mail clients), you get the following error:
Unsupported action
That action is not currently supported.
As shown below:
It turns out that the emulators resolve the intent to an activity called com.android.fallback.Fallback
, which displays the above message. Apparently this is by design.
If you want your app to circumvent this so it also works correctly on the official emulators, you can check for it before trying to send the email:
private void sendEmail() {
Intent intent = new Intent(Intent.ACTION_SENDTO)
.setData(new Uri.Builder().scheme("mailto").build())
.putExtra(Intent.EXTRA_EMAIL, new String[]{ "John Smith <[email protected]>" })
.putExtra(Intent.EXTRA_SUBJECT, "Email subject")
.putExtra(Intent.EXTRA_TEXT, "Email body")
;
ComponentName emailApp = intent.resolveActivity(getPackageManager());
ComponentName unsupportedAction = ComponentName.unflattenFromString("com.android.fallback/.Fallback");
if (emailApp != null && !emailApp.equals(unsupportedAction))
try {
// Needed to customise the chooser dialog title since it might default to "Share with"
// Note that the chooser will still be skipped if only one app is matched
Intent chooser = Intent.createChooser(intent, "Send email with");
startActivity(chooser);
return;
}
catch (ActivityNotFoundException ignored) {
}
Toast
.makeText(this, "Couldn't find an email app and account", Toast.LENGTH_LONG)
.show();
}
Find more info in the developer documentation.
Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps
You will have to modify the below line:
<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>
modalRegister
is the ID and hence requires a preceding #
for ID reference in html.
So, the modified html code snippet would be as follows:
<li><a href="#" data-toggle="modal" data-target="#modalRegister">Register</a></li>