My Answer is close to the above answers but you need to write the class exactly without changing anything.
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
and to use it with HttpsURLConnection
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < Build.VERSION_CODES.LOLLIPOP) {
if (url.toString().startsWith("https")) {
try {
TLSSocketFactory sc = new TLSSocketFactory();
conn.setSSLSocketFactory(sc);
} catch (Exception e) {
String sss = e.toString();
}
}
}
Highlight the lines and use:
You can then move the cursor to your heart's content and edit all lines at once.
It's also called "Split into Lines" in the "Selection" menu.
To add to Lennart Regebro's answer There is even the third way that can be used:
encoded3 = str.encode(original, 'utf-8')
print(encoded3)
Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.
A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.
Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.
In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".
The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.
Add Google Play Services to Your Project
To make the Google Play services APIs available to your app:
follow the steps present in this link : http://developer.android.com/google/play-services/setup.html#Setup
My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex
which has useful APIs for converting between String
y hex and binary. For example:
Hex.decodeHex(char[] data)
which throws a DecoderException
if there are non-hex characters in the array, or if there are an odd number of characters.
Hex.encodeHex(byte[] data)
is the counterpart to the decode method above, and spits out the char[]
.
Hex.encodeHexString(byte[] data)
which converts back from a byte
array to a String
.
Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
None of these answers solved the problem for me. The root cause being:
You cannot store 4-byte characters in MySQL with the utf-8 character set.
MySQL has a 3 byte limit on utf-8 characters (yes, it's wack, nicely summed up by a Django developer here)
To solve this you need to:
settings.py
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql',
...
'OPTIONS': {'charset': 'utf8mb4'},
}
}
Note: When recreating your database you may run into the 'Specified key was too long' issue.
The most likely cause is a CharField
which has a max_length of 255 and some kind of index on it (e.g. unique). Because utf8mb4 uses 33% more space than utf-8 you'll need to make these fields 33% smaller.
In this case, change the max_length from 255 to 191.
Alternatively you can edit your MySQL configuration to remove this restriction but not without some django hackery
UPDATE: I just ran into this issue again and ended up switching to PostgreSQL because I was unable to reduce my VARCHAR
to 191 characters.
Maybe you're in the wrong perspective?
Eclipse has a construct called a "perspective"; it's a task-oriented arrangement of windows, toolbar buttons, and menus. There's a Java perspective, a Debug perspective, there's probably a PHP perspective, etc. If you're not in the Java perspective, you won't see some of the buttons you expect (like New Class).
To switch perspectives, see the long-ish buttons on the right side of the toolbar, or use the Window menu.
The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.
var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)
The tilde truncs the division result (see this article about integer division)
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.
You can use :
import os
import sys
from fuzzywuzzy import fuzz
import subprocess
path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"
files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
pyfiles.append(os.path.join(root, file))
stopWords = ['from', 'import',',','.']
importables = []
for file in pyfiles:
with open(file) as f:
content = f.readlines()
for line in content:
if "import" in line:
for sw in stopWords:
line = ' '.join(line.split(sw))
importables.append(line.strip().split(' ')[0])
importables = set(importables)
subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)
with open(path+'/requirements.txt') as req:
modules = req.readlines()
modules = {m.split('=')[0].lower() : m for m in modules}
notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']
new_requirements = []
for req_module in importables:
try :
new_requirements.append(modules[req_module])
except KeyError:
for k,v in modules.items():
if len(req_module)>1 and req_module not in notList:
if fuzz.partial_ratio(req_module,k) > 90:
new_requirements.append(modules[k])
new_requirements = [i for i in set(new_requirements)]
new_requirements
with open(path+'/requirements.txt','w') as req:
req.write(''.join(new_requirements))
P.S: It may have a few additional libraries as it checks on fuzzylogic.
How about this...
<style type="text/css">
div.frame { background-color: #000; }
img.pic:hover {
opacity: .6;
filter:alpha(opacity=60);
}
</style>
<div class="frame">
<img class="pic" src="path/to/image" />
</div>
It is always ideal to use the json.dumps()
method.
To get rid of this error, I used the following code
json.dumps(YOUR_DICT_STRING).replace("'", '"')
I don't have enough reputation to comment on answers but wanted to note that the Google Chart API has been deprecated.
From the API homepage:
The Infographics portion of Google Chart Tools has been officially deprecated as of April 20, 2012.
Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".
Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.
Hope this can help you.
I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting
overflow: hidden;
on the last element (or all of them).
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationI got this exception too. MY error code is below
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("Content-type", "JSON");
I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below
connection.setRequestProperty("Content-type", "application/json");
you can check up your "Content-type"
about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.
Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.
So i found the solution!
If you want something done right, do it yourself.
I present to you Shinobi! Shinobi : The Open Source CCTV Platform
In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password
Update new Change code into Github
->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.
Additionally to the PIL
image check you can also add file name extension check like this:
filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))
Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL
or one of the libraries suggested in the other answers.
You can try adding:
#aboutDescription
{
height: 100px;
max-height: 100px;
}
1) do
svn revert . --recursive
2) parse output for errors like
"Failed to revert 'dir1/dir2' -- try updating instead."
3) call svn up for each of error directories:
svn up dir1/dir2
Using a (very) commonly used package is prefered:
import matplotlib.pyplot as plt
im = plt.imread('image.png')
I wrote two programs:
int main(){return 0;}
and
#include <stdlib.h>
int main(){exit(0)}
After executing gcc -S -O1
. Here what I found watching
at assembly (only important parts):
main:
movl $0, %eax /* setting return value */
ret /* return from main */
and
main:
subq $8, %rsp /* reserving some space */
movl $0, %edi /* setting return value */
call exit /* calling exit function */
/* magic and machine specific wizardry after this call */
So my conclusion is: use return
when you can, and exit()
when you need.
I have experienced the same situation I did the below as this much easier.
By passing commit-Id
you can reach to the particular commit you want to go:
git reset --hard {commit-id}
As you want to remove your last commit so you need to pass the commit-Id
where you need to move your pointer:
git reset --hard db0c078d5286b837532ff5e276dcf91885df2296
Best solution to this is css/html: Make a div to wrap your elements in, if you dont have it already And set it to position fixed and overflow hidden. Optional, set height and width to 100% if you want it to fill the whole screen and nothing but the whole screen
#wrapper{_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
position: fixed;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<p>All</p>_x000D_
<p>Your</p>_x000D_
<p>Elements</p>_x000D_
</div>
_x000D_
Mac OSX since 10.10 has an app called Murus Firewall, which acts as a GUI to pf, the replacement for ipfw.
It works very well for system-wide or domain-specific throttling. I was just able to use it to slide my download speed between 300Kbps and 30Mbps to test how a streaming video player adjusts.
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
This might work for you:
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
Application.CutCopyMode = False
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
Please try the following:
<script>
$(document).ready(function() {
$('.carousel').carousel('pause');
});
</script>
In cases wherein the width/height of the space is beyond
I usually use:
For horizontal spacer:
<span style="display:inline-block; width: YOURWIDTH;"></span>
For vertical spacer:
<span style="display:block; height: YOURHEIGHT;"></span>
This works for anonymous types, ExpandoObject
, Nancy.DynamicDictionary
or anything else that can be cast to IDictionary<string, object>
.
public static bool PropertyExists(dynamic obj, string name) {
if (obj == null) return false;
if (obj is IDictionary<string, object> dict) {
return dict.ContainsKey(name);
}
return obj.GetType().GetProperty(name) != null;
}
The property
in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.
For example, to use that code you would have to have something like this in your <head
tag. <head xmlns:og="http://example.org/">
and inside the http://example.org/
there would be a specification for title
(og:title).
The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).
You should favour range()
over xrange()
only when you need an actual list. For instance, when you want to modify the list returned by range()
, or when you wish to slice it. For iteration or even just normal indexing, xrange()
will work fine (and usually much more efficiently). There is a point where range()
is a bit faster than xrange()
for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer xrange()
.
This kind of logic could be implemented using EXISTS
:
CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');
Query:
DECLARE @a INT;
--SET @a = 1; -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1; -- all values
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');
It could be extended to contain multiple params:
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');
Jakub's answer actually improves on this. With Git versions = 1.6.6, with only one remote, you can do:
git fetch
git checkout test
As user masukomi points out in a comment, git checkout test
will NOT work in modern git if you have multiple remotes. In this case use
git checkout -b test <name of remote>/test
or the shorthand
git checkout -t <name of remote>/test
Before you can start working locally on a remote branch, you need to fetch it as called out in answers below.
To fetch a branch, you simply need to:
git fetch origin
This will fetch all of the remote branches for you. You can see the branches available for checkout with:
git branch -v -a
With the remote branches in hand, you now need to check out the branch you are interested in, giving you a local working copy:
git checkout -b test origin/test
I think you have put command like java -VERSION
. This is in capital letters
You need to put all command in lowercase letters
javac -version
java -version
All characters must be in lowercase letter
This works using java.util.Scanner and will take multiple "enter" keystrokes:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
}
To break it down:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
These lines initialize a new Scanner
that is reading from the standard input stream (the keyboard) and reads a single line from it.
while(readString!=null) {
System.out.println(readString);
While the scanner is still returning non-null data, print each line to the screen.
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
If the "enter" (or return, or whatever) key is supplied by the input, the nextLine()
method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.
Try this:
<a class="button" href="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" download="smile.jpg">Download image</a>
If you need this code in several places then I'd suggest that you add a short function to keep your code simpler and easier to test.
function add_days( $days, $from_date = null ) {
if ( is_numeric( $from_date ) ) {
$new_date = $from_date;
} else {
$new_date = time();
}
// Timestamp is the number of seconds since an event in the past
// To increate the value by one day we have to add 86400 seconds to the value
// 86400 = 24h * 60m * 60s
$new_date += $days * 86400;
return $new_date;
}
Then you can use it anywhere like this:
$today = add_days( 0 );
$tomorrow = add_days( 1 );
$yesterday = add_days( -1 );
$in_36_hours = add_days( 1.5 );
$first_reminder = add_days( 10 );
$second_reminder = add_days( 5, $first_reminder );
$last_reminder = add_days( 3, $second_reminder );
I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.
As iOS does not use Java like Android, your options are quite limited:
1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).
2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.
3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.
The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.
Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.
As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.
by far the best C++ GUI library out there is Qt, it's comprehensive, easy to learn, really fast, and multiplattform.
ah, it recently got a LGPL license, so now you can download it for free and include on commercial programs
I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case
example:
BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH
(
FIELDTERMINATOR =',',
ROWTERMINATOR ='\n'
);
This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.
Crucial bit: Master.Master.
See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl
Example:
'Find the content control
Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")
'now find controls inside that content
Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")
I prefer this solution, over the accepted answer by Michael Williamson, it catches changes to sources+inline files, then sources+headers, and finally sources only. Advantage here is that the whole library is not recompiled if only a a few changes are made. Not a huge consideration for a project with a couple of files, bur if you have 10 or a 100 sources, you will notice the difference.
COMMAND= gcc -Wall -Iinclude ...
%.o: %.cpp %.inl
$(COMMAND)
%.o: %.cpp %.hpp
$(COMMAND)
%.o: %.cpp
$(COMMAND)
I'll throw this in just in case someone is running into this issue while working in a parallel loop:
Parallel.ForEach(query, deet =>
{
MyContext ctx = new MyContext();
//do some stuff with this to identify something
if(something)
{
//Do stuff
ctx.MyObjects.Add(myObject);
ctx.SaveChanges() //this is where my error was being thrown
}
else
{
//same stuff, just an update rather than add
}
}
I changed it to the following:
Parallel.ForEach(query, deet =>
{
MyContext ctxCheck = new MyContext();
//do some stuff with this to identify something
if(something)
{
MyContext ctxAdd = new MyContext();
//Do stuff
ctxAdd .MyObjects.Add(myObject);
ctxAdd .SaveChanges() //this is where my error was being thrown
}
else
{
MyContext ctxUpdate = new MyContext();
//same stuff, just an update rather than add
ctxUpdate.SaveChanges();
}
}
Not sure if this is 'Best Practice', but it fixed my issue by having each parallel operation use its own context.
In Express it's already done for you and you can simply use req.query for that:
var id = req.query.id; // $_GET["id"]
Otherwise, in NodeJS, you can access req.url and the builtin url
module to url.parse it manually:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
You can on
the DOMNodeInserted
event to get an event for when it's added to the document by your code.
$('body').on('DOMNodeInserted', 'select', function () {
//$(this).combobox();
});
$('<select>').appendTo('body');
$('<select>').appendTo('body');
Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/
EDIT: after reading around I just need to double check DOMNodeInserted
won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.
See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
The problem with information_schema is that it can be terribly slow. It is faster to use the SHOW commands.
After you select the database you first send the query SHOW TABLES. And then you do SHOW COLUMNS for each of the tables.
In PHP that would look something like
$res = mysqli_query("SHOW TABLES"); while($row = mysqli_fetch_array($res)) { $rs2 = mysqli_query("SHOW COLUMNS FROM ".$row[0]); while($rw2 = mysqli_fetch_array($rs2)) { if($rw2[0] == $target) .... } }
When I faced this problem, I approached it like this:
I created a DataRowView
, grabbed the column index, and then used that in the row's ItemArray
DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();
Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:
import javax.swing.JOptionPane;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
}
The first JOptionPane
parameter (null
in this example) is used to align the dialog. null
causes it to center itself on the screen, however any java.awt.Component
can be specified and the dialog will appear in the center of that Component
instead.
I tend to use the titleBar
String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.
As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
/* By specifying a null headerMessage String, we cause the dialog to
not have a header */
infoBox(infoMessage, titleBar, null);
}
public static void infoBox(String infoMessage, String titleBar, String headerMessage)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(titleBar);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
alert.showAndWait();
}
}
One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
or
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");
In my machine, ssh-keygen
was available from powershell.
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
But it gets more interesting when there's a UINavigationController involved:
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
Swift 4+
You can use simplified regex "^[6-9]\\d{9}$"
^ #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\\d #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9} #Repeat the previous "\d" 9 times (9 digits)
$ #Match the end of the string
Indian 10 Digit Mobile validation(can start with 6,7,8,9) -
extension String {
var isValidContact: Bool {
let phoneNumberRegex = "^[6-9]\\d{9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
let isValidPhone = phoneTest.evaluate(with: self)
return isValidPhone
}
}
Usage:-
print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false
For email validation you can check this
On Ubuntu :
Try
$ cat /usr/local/cuda/version.txt
or
$ cat /usr/local/cuda-8.0/version.txt
Sometimes the folder is named "Cuda-version".
If none of above works, try going to
$ /usr/local/
And find the correct name of your Cuda folder.
Output should be similar to:
CUDA Version 8.0.61
The answer is not as easy as a simple yes or no. Check out the results of a test I recently did:
So after digging further I found this, which explains how each browser handles loading img assets based on css display: none;
Excerpt from the blog post:
- Chrome and Safari (WebKit):
WebKit downloads the file every time except when a background is applied through a non-matching media-query.- Firefox:
Firefox won't download the image called with background image if the styles are hidden but they will still download assets from img tags.- Opera:
Like Firefox does, Opera won't load useless background-images.- Internet Explorer:
IE, like WebKit will download background-images even if they have display: none; Something odd appears with IE6 : Elements with a background-image and display: none set inline won't be downloaded... But they will be if those styles aren't applied inline.
As per the current setup on June, 2017 Here is the downloadable link for Visual C++ 2015 Redistributable package : https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe
Hope this will help, who are struggling with the download link.
Note: This is with regards to MySQL Workbench 6.3.9
In addition to Ishmaeel's answer, the method OpenMappedMachineConfiguration()
will always return a Configuration
object. So to check to see if it loaded you should check the HasFile
property where true means it came from a file.
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
select *from table_name where boolean_column is False or Null;
Is interpreted as "( boolean_column is False ) or (null)".
It returns only rows where boolean_column
is False as the second condition is always false.
select *from table_name where boolean_column is Null or False;
Same reason. Interpreted as "(boolean_column is Null) or (False)"
select *from table_name where boolean_column is Null or boolean_column = False;
This one is valid and returns 2 rows: false
and null
.
I just created the table to confirm. You might have typoed somewhere.
You should use getFullYear()
instead of getYear()
. getYear()
returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth()
and setMonth()
. You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate()
and setDate()
.
mysql -u -p databaseName>fileToPutDatabase
In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:
make sure your API is sending the Content-Type
header to tell the client to expect a JSON response:
header('Content-Type: application/json');
echo json_encode($response);
Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.
If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController
with an add()
action/method.
There are a few starting point projects for RESTful APIs on GitHub that are worth a look.
OS_ACTIVITY_MODE didn't work for me (it may have been because I typo'd disable
as disabled
, but isn't that more natural?!?), or at least didn't prevent a great deal of messages. So here's the real deal with the environment variables.
https://llvm.org/svn/llvm-project/lldb/trunk/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp
lldb_private::Error
PlatformDarwin::LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) {
// Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr
// if the OS_ACTIVITY_DT_MODE environment variable is set. (It doesn't
// require any specific value; rather, it just needs to exist).
// We will set it here as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag
// is not set. Xcode makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
// LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
// specifically want it unset.
const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
auto &env_vars = launch_info.GetEnvironmentEntries();
if (!env_vars.ContainsEnvironmentVariable(disable_env_var)) {
// We want to make sure that OS_ACTIVITY_DT_MODE is set so that
// we get os_log and NSLog messages mirrored to the target process
// stderr.
if (!env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE"))
env_vars.AppendArgument(llvm::StringRef("OS_ACTIVITY_DT_MODE=enable"));
}
// Let our parent class do the real launching.
return PlatformPOSIX::LaunchProcess(launch_info);
}
So setting OS_ACTIVITY_DT_MODE
to "NO" in the environment variables (GUI method explained in Schemes screenshot in main answer) makes it work for me.
As far as NSLog
being the dumping ground for system messages, errors, and your own debugging: a real logging approach is probably called for anyway, e.g. https://github.com/fpillet/NSLogger .
OR
Drink the new Kool-Aid: http://asciiwwdc.com/2016/sessions/721 https://developer.apple.com/videos/play/wwdc2016/721/ It's not surprising that there are some hitches after overhauling the entire logging API.
ADDENDUM
Anyway, NSLog
is just a shim:
https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/
NSLog / CFLog
NSLog is now just a shim to os_log in most circumstances.
Only makes sense now to quote the source for the other env variable. Quite a disparate place, this time from Apple internals. Not sure why they are overlapping. [Incorrect comment about NSLog
removed]
[Edited 22 Sep]: I wonder what "release" and "stream" do differently than "debug". Not enough source.
e = getenv("OS_ACTIVITY_MODE");
if (e) {
if (strcmp(e, "release") == 0) {
mode = voucher_activity_mode_release;
} else if (strcmp(e, "debug") == 0) {
mode = voucher_activity_mode_debug;
} else if (strcmp(e, "stream") == 0) {
mode = voucher_activity_mode_stream;
} else if (strcmp(e, "disable") == 0) {
mode = voucher_activity_mode_disable;
}
}
If you use the $.ajax
function, you can simply add the csrf
token in the data body:
$.ajax({
data: {
somedata: 'somedata',
moredata: 'moredata',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.
Zakaria, that is a reference to an built-in XML layout document that is part of the Android OS, rather than one of your own XML layouts.
Here is a further list of layouts that you can use:
http://developer.android.com/reference/android/R.layout.html
(Updated link thanks @Estel: https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout )
You can actually view the code for the layouts.
If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.
<div align="center"><form id="form_login"><!--form content here--></form></div>
UPDATE
@G-Cyr is right. align="center"
attribute is now obsolete. You can use text-align
attribute for this as following.
<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>
This will center all the content inside the parent DIV. An optional way is to use margin: auto
CSS attribute with predefined widths and heights. Please follow the following thread for more information.
How to horizontally center a in another ?
Vertical centering is little difficult than that. To do that, you can do the following stuff.
html
<body>
<div id="parent">
<form id="form_login">
<!--form content here-->
</form>
</div>
</body>
Css
#parent {
display: table;
width: 100%;
}
#form_login {
display: table-cell;
text-align: center;
vertical-align: middle;
}
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
myArray.sample(x)
can also help you to get x random elements from the array.
$(...)[index] // gives you the DOM element at index
$(...).get(index) // gives you the DOM element at index
$(...).eq(index) // gives you the jQuery object of element at index
DOM objects don't have css
function, use the last...
$('ul li').eq(index).css({'background-color':'#343434'});
docs:
.get(index)
Returns: Element
.eq(index)
Returns: jQuery
Map the array is the quickest and cleanest.
var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })
will return values as an array like:
array => [2,3]
assuming castle and barn were checked and the others were not.
I needed to restart the adb service with the command adb usb
Prior to this I was getting all logging and able to debug, but wasn't getting my own log lines (yes, I was getting system logging associated with my application).
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
Give the UL an ID and use the getElementById function:
<html>
<body>
<script>
function toggledisplay(elementID)
{
(function(style) {
style.display = style.display === 'none' ? '' : 'none';
})(document.getElementById(elementID).style);
}
</script>
<a href="#" title="Show Tags" onClick="toggledisplay('changethis');">Show All Tags</a>
<ul class="subforums" id="changethis" style="overflow-x: visible; overflow-y: visible; ">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after
// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });
// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bars = bs })
.SelectMany(
fooBars => fooBars.Bars.DefaultIfEmpty(),
(x,y) => new { Foo = x.Foo, Bar = y });
To display the difference using a simple data set (assuming we're joining on the values themselves):
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };
// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };
// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 } // Misleading, we had multiple matches.
// Which 3 should get selected (not arbitrarily the first)?.
// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
{ A = 3, B = 3 }
Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set.
The information there is I think partially correct:
That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.
As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the +
is defined, though %20
is standard.
If this is happening to you in an AJAX post, you'll want to compare the values that you're sending and the values that the Controller is expecting.
In my case, I had changed a parameter in a serializable class from State to StateID, and then in an AJAX call didn't change the receiving field out 'data'
success: function (data) { MakeAddressForm.formData.StateID = data.State;
Note that the class was changed - it doesn't matter what I call it in the formData.
This created a null reference in the formData which I was trying to post back to the Controller once I'd done the update. Obviously, if someone changed the state (which was the purpose of the form) then they didn't get the error, so it made for a hard one to find.
This also through a 500 error. I'm posting this here in hopes it saves someone else the time I've wasted
You should do mkdir build
and cd build
while inside opencv
folder, not the opencv-contrib
folder. The CMakeLists.txt
is there.
Angular 2.0.0 Final:
I have found that using a ViewChild
setter is most reliable way to set the initial form control focus:
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => {
this._renderer.invokeElementMethod(_input.nativeElement, "focus");
}, 0);
}
}
The setter is first called with an undefined
value followed by a call with an initialized ElementRef
.
Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview
Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).
UPDATE for Angular 4+
Renderer
has been deprecated in favor of Renderer2
, but Renderer2
does not have the invokeElementMethod
. You will need to access the DOM directly to set the focus as in input.nativeElement.focus()
.
I'm still finding that the ViewChild setter approach works best. When using AfterViewInit
I sometimes get read property 'nativeElement' of undefined
error.
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => { //This setTimeout call may not be necessary anymore.
_input.nativeElement.focus();
}, 0);
}
}
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.
Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...
I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.
When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...
Class under test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClassWithSomeLogging {
private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);
public void doStuff(boolean b) {
if(b) {
LOG.info("true");
} else {
LOG.info("false");
}
}
}
Test
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {
private static Logger mockLOG;
@BeforeClass
public static void setup() {
mockStatic(LoggerFactory.class);
mockLOG = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
}
@Test
public void testIt() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(true);
verify(mockLOG, times(1)).info("true");
}
@Test
public void testIt2() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(false);
verify(mockLOG, times(1)).info("false");
}
@AfterClass
public static void verifyStatic() {
verify(mockLOG, times(1)).info("true");
verify(mockLOG, times(1)).info("false");
verify(mockLOG, times(2)).info(anyString());
}
}
Note
If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true");
- rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....
I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value
annotation inside of classes.
Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"
):
<context:property-placeholder location="/path/to/my/app.properties"
ignore-resource-not-found="true" />
Write a small script named gitpush.sh with below lines and add it your ~ directory.
echo $1
git add .
git commit -m "$1"
git push
Now add an alias in ~/.bashrc like below :
alias gitpush='~/gitpush'
Now from any git repository just write gitpush "message" .
Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.
if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1}) Then
""
else
"and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}
I had this problem and
dumpbin /exports mydll.dll
and
depends mydll.dll
showed 'DllRegisterServer'.
The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.
What I did was created a validator that did the samething as angular for minLength except I added the trim()
import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
@Injectable()
export class ValidatorHelper {
///This is the guts of Angulars minLength, added a trim for the validation
static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (ValidatorHelper.isPresent(Validators.required(control))) {
return null;
}
const v: string = control.value ? control.value : '';
return v.trim().length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
null;
};
}
static isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
}
}
I then in my app.component.ts overrode the minLength function provided by angular.
import { Component, OnInit } from '@angular/core';
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit(): void {
Validators.minLength = ValidatorHelper.minLength;
}
}
Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.
Validators.compose([
Validators.minLength(2)
]);
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID
If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE()
as the default value for that column, and don't allow NULLs
for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml
when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.
Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.
Assume that they were just considered unnecessary. Since it's so easy to just type #a comment
, multiline comments can just consist of many single line comments.
For HTML, on the other hand, there's more of a need for multiliners. It's harder to keep typing <!--comments like this-->
.
When reading to and from your CSV file include the argument index=False
so for example:
df.to_csv(filename, index=False)
and to read from the csv
df.read_csv(filename, index=False)
This should prevent the issue so you don't need to fix it later.
You could map it to a key, for instance F3, in .vimrc
inoremap <F3> <Esc>GA
I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
});
}
res.writeHead( ... );
res.end(results);
The problem with the previous code is that the search
function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results
is empty.
To fix the problem, you have to put the code after the loop in the callback function.
search(query, function(result) {
results.push(result);
// Put res.writeHead( ... ) and res.end(results) here
});
However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.
To get a list of all keys, use Object.keys
. Then, to iterate through this list, I use .forEach
(you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }
, but that could give problems, see JavaScript closure inside loops – simple practical example).
Here's a complete example:
var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
res.writeHead( ... );
res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
onComplete();
} else {
// There is at least one element, so the callback will be called.
keys.forEach(function(key) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
if (--tasksToGo === 0) {
// No tasks left, good to go
onComplete();
}
});
});
}
Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:
var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
if (index === keys.length) { // No items left
res.writeHead( ... );
res.end(results);
return;
}
var key = keys[index];
var query = config[key].query;
search(query, function(result) {
results.push(result);
next(index + 1);
});
})(0);
What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.
0
and 7
both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.
Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON
, THU
, etc:
0 - Sun Sunday
1 - Mon Monday
2 - Tue Tuesday
3 - Wed Wednesday
4 - Thu Thursday
5 - Fri Friday
6 - Sat Saturday
7 - Sun Sunday
Graphically:
+---------- minute (0 - 59)
¦ +-------- hour (0 - 23)
¦ ¦ +------ day of month (1 - 31)
¦ ¦ ¦ +---- month (1 - 12)
¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
¦ ¦ ¦ ¦ ¦ 1 - 7 => Monday - Sunday)
? ? ? ? ?
* * * * * command to be executed
Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU
will exectute the command only on sundays, mondays on thursdays.
You can read further details in Wikipedia's article about Cron.
In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?
IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.
Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as
package 7 com.example;
could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.
There is also a descent solution which seems not to have any memory or performance overhead and be quite elegant:
string[] filters = new[]{"*.jpg", "*.png", "*.gif"};
string[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
This answers improves on Rashmi Pandit's answer, which is in a way better than the rest because that it seems to completely resolve the exact problem detailed in the question.
The bad part is that is inefficient and not uses the IgnoreCase option consistently.
Inefficient part is because regex can be expensive to construct and execute, and in that answer it could have been constructed just once (calling Regex.IsMatch
was just constructing the regex again behind the scene). And Match
method could have been called only once and stored in a variable and then link
and name
should call Result
from that variable.
And the IgnoreCase option was only used in the Match
part but not in the Regex.IsMatch
part.
I also moved the Regex definition outside the method in order to construct it just once (I think is the sensible approach if we are storing that the assembly with the RegexOptions.Compiled
option).
private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
var matches = hrefRegex.Match(htmlTd);
if (matches.Success)
{
link = matches.Result("${link}");
name = matches.Result("${name}");
return true;
}
else
{
link = null;
name = null;
return false;
}
}
You can do this with CSS filters in all modern browsers (see the caniuse compatibility table).
.button {_x000D_
color: #ff0000;_x000D_
}_x000D_
_x000D_
/* note: 100% is baseline so 85% is slightly darker, _x000D_
20% would be significantly darker */_x000D_
.button:hover {_x000D_
filter: brightness(85%);_x000D_
}
_x000D_
<button class="button">Foo lorem ipsum</button>
_x000D_
Here's more reading from CSS Tricks about the various filters you can use: https://css-tricks.com/almanac/properties/f/filter/
The command-line syntax for opening a text file is:
type filename.txt
File types supported by this command include (but are not limited to): .doc, .txt, .html, .log
If the contents is too long, you can add "|more" after "type filename.txt", and it will pause after each screen; to end the command before the end of the file, you can hold Ctrl + C.
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
Method 1:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
With below permission
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Method 2:
There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.
Try below code:
String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
main_data, "mimetype=?",
new String[]{"vnd.android.cursor.item/phone_v2"},
"is_primary DESC");
if (object != null) {
do {
if (!((Cursor) (object)).moveToNext())
break;
String s1 = ((Cursor) (object)).getString(4);
} while (true);
((Cursor) (object)).close();
}
You will need to add these two permissions.
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
Hope this helps, Thanks!
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
Using Kotlin and Extensions you can add colored text really easy and clean:
Create a file TextViewExtensions.kt with this content
fun TextView.append(string: String?, @ColorRes color: Int) {
if (string == null || string.isEmpty()) {
return
}
val spannable: Spannable = SpannableString(string)
spannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
0,
spannable.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
append(spannable)
}
Now is really easy to append text with color
textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)
Basically is same as @Abdul Rizwan answer but using Kotlin, extensions, some validations and getting color inside extension.
Use http://[jenkins-server]/exit
This page shows how to use URL commands.
If you want to reset by id
$('select[id="baba"]').empty();
If you want to reset by name
$('select[name="baba"]').empty();
Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script>
to the end of <body>
tag.
or use defer.
<script defer src="">
so rest assured e.preventDefault()
should work.
Well, this is my final solution for a simple db, for Linux:
# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
# administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
# strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB
#-------------------------------------------------------------------------------
//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//
cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf
# change all `md5` with `scram-sha-256`
# save and exit
//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//
sudo -u postgres psql
# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE
create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL
# Create all tables and objects, and after that:
\connect $DB postgres
revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;
grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;
grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on tables to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on sequences to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on functions to $ROLE_LOCAL;
alter default privileges for role $ROLE_REMOTE in schema public
grant select, insert, update, delete on tables to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant usage, select on sequences to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant execute on functions to $ROLE_REMOTE;
# CTRL+D
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:
newHero() {
return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>
Try css:
.topcorner{
position:absolute;
top:10px;
right: 10px;
}
you can play with the top
and right
properties.
If you want to float the div
even when you scroll down, just change position:absolute;
to position:fixed;
.
Hope it helps.
Script based on Joe answer (detach, copy files, attach both).
It's not necessary, but maybe access denied error on executing.
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
@dbName
and @copyDBName
variables before.USE master;
GO
DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'
-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
INSERT INTO ##DBFileNames([FileName])
SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')
-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')
EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')
-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')
-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE
@oldAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @dbName + ' ON ',
@newAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @copyDBName + ' ON '
DECLARE curs CURSOR FOR
SELECT [filename] FROM ##DBFileNames
OPEN curs
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0
BEGIN
SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
SET @ext = RIGHT(@filename,4)
SET @copyFileName = @path + @copyDBName + @ext
SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
PRINT @command
EXEC(@command);
SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'
FETCH NEXT FROM curs INTO @filename
END
CLOSE curs
DEALLOCATE curs
-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'
-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)
-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)
DROP TABLE ##DBFileNames
foreach (var v in structure)
{
var group = groups.Single(g => g.Key == v. ??? );
v.ListOfSmth = group.ToList();
}
First you need to select the desired group. Then you can use the ToList
method of on the group. The IGrouping
is a IEnumerable
of the values.
I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra \n at the end.
private static IPAddress GetExternalIp () {
using (WebClient client = new WebClient()) {
List<String> hosts = new List<String>();
hosts.Add("https://icanhazip.com");
hosts.Add("https://api.ipify.org");
hosts.Add("https://ipinfo.io/ip");
hosts.Add("https://wtfismyip.com/text");
hosts.Add("https://checkip.amazonaws.com/");
hosts.Add("https://bot.whatismyipaddress.com/");
hosts.Add("https://ipecho.net/plain");
foreach (String host in hosts) {
try {
String ipAdressString = client.DownloadString(host);
ipAdressString = ipAdressString.Replace("\n", "");
return IPAddress.Parse(ipAdressString);
} catch {
}
}
}
return null;
}
It is basically a two-step process:
pip install cmap
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
Functions that might be helpful:
open("file").read()
which reads the contents of the whole file at once'string'.splitlines()
which separates lines from each other (and discards empty lines)By using len() and those functions you could accomplish what you're doing.
this answer can be confusing
do read the comments attached to this post and make sure this is what you are after
'svn delete' works against repository content, not against the repository itself. for doing repository maintenance (like completely deleting one) you should use svnadmin. However, there's a reason why svnadmin doesn't have a 'delete' subcommand. You can just
rm -rf $REPOS_PATH
on the svn server,
where $REPOS_PATH is the path you used to create your repository with
svnadmin create $REPOS_PATH
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
The disabled
attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.
In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.
In order to find duplicate values you should run,
SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);
Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.
DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;
This is a Microsoft specific extension to the C++ language which allows you to attribute a type or function with storage class information.
Documentation
Mutable way:
import UserString
s = UserString.MutableString("EXAMPLE")
>>> type(s)
<type 'str'>
# Delete 'M'
del s[3]
# Turn it for immutable:
s = str(s)
If you are averse to boost, you can use regular old operator>>
, along with std::noskipws
:
EDIT: updates after testing.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
void split(const std::string& str, std::vector<std::string>& v) {
std::stringstream ss(str);
ss >> std::noskipws;
std::string field;
char ws_delim;
while(1) {
if( ss >> field )
v.push_back(field);
else if (ss.eof())
break;
else
v.push_back(std::string());
ss.clear();
ss >> ws_delim;
}
}
int main() {
std::vector<std::string> v;
split("hello world how are you", v);
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
std::cout << "\n";
}
You can use an HTTP Handler (.ashx) to download a file, like this:
DownloadFile.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect()
, like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request
object in the HttpContext
to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
I solved this issue by change to use latest buildToolsVersion
android {
//...
buildToolsVersion '26.0.2' // change from '23.0.2'
//...
}
Updated (11/2017) to take into consideration some comments.
Easy example:
wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, (sizeof(buf) / sizeof(wchar_t)), NULL);
localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3
<%@page import="java.util.Enumeration"%>
<%
Enumeration in = request.getParameterNames();
while(in.hasMoreElements()) {
String paramName = in.nextElement().toString();
out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
}
%>
key = datr
key2 = datr2
key3 = datr3
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
PDOStatement->execute()
returns true on success. There is also PDOStatement->errorCode()
which you can check for errors.
No- you can definitely handle more than that.
Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.
Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).
Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.
These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.
Another example is threads, which are units of code inside processes that allow concurrency as well.
The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.
The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.
Good luck!
*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another
To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
What worked for me at the end was adding the manifest file to the javaw.exe just like Heikki Juntunen said at https://bugs.eclipse.org/bugs/show_bug.cgi?id=421383#c66
The instructions about how to edit the registry and create the manifest file where written by Matthew Cochrane at https://bugs.eclipse.org/bugs/show_bug.cgi?id=421383#c60 and @KItis wrote the instructions here
I put here a copy of that post:
First you need to add this registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\PreferExternalManifest (DWORD) to 1
Next, a manifest file with the same name as the executable must be present in the same folder as the executable. The file is named eclipse.exe.manifest and consists of:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<description>eclipse</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3"
level="asInvoker"
ms_asmv3:uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.
An example in Swift 4.0 is as follows:
var stringArray = ["foundation","coredata","coregraphics"]
stringArray = stringArray.filter { $0.contains("core") }
In the above example, since each element in the array is a string you can use the contains
method to filter the array.
If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.
On ReactNative .53, the following works for me:
this.timeoutCheck = setTimeout(() => {
this.setTimePassed();
}, 400);
'setTimeout' is the ReactNative library function.
'this.timeoutCheck' is my variable to hold the time out object.
'this.setTimePassed' is my function to invoke at the time out.
If you just want to have the log output display when you run your app then you can go into XCode4 preferences -> Alerts and click on 'Run starts' on the left hand column.
Then select 'Show Debugger' and when you run the app the NSLog output will be displayed below the editor pane.
This way you don't have to select on the 'up arrow' button at the bottom bar.
I agree with the answers 1 and 2. However, I prefer to specify each library separately. This makes the depencencies clearer in big projects. Yet, there is the danger of mistyping the (case-sensitive) variable names. In that case there is no direct cmake error but some undefined references linker issues later on, which may take some time to resolve. Therefore I use the following cmake function:
function(VerifyVarDefined)
foreach(lib ${ARGV})
if(DEFINED ${lib})
else(DEFINED ${lib})
message(SEND_ERROR "Variable ${lib} is not defined")
endif(DEFINED ${lib})
endforeach()
endfunction(VerifyVarDefined)
For the example mentioned above, this looks like:
VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY)
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )
If I had written "BOOST_PROGRAM_OPTIONS_LIBRARY" there would have been an error triggered by cmake and not much later triggered by the linker.
It's simple and follow the small Steps to proceed:
$cd project and execute $git init --bare
Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git
, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, $cd
into the project folder which you want to push to git execute the below commands:
git init .
git remote add origin [email protected]:/home/ubuntu/workspace/project.git
git add .
git commit -m "Initial commit"
Below is an optional command but found it has been suggested as i was working to setup the same thing
git config --global remote.origin.receivepack "git receive-pack"
git pull origin master
git push origin master
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, cd project_folder/.git
and cat config
, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the project.git
folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.
I have a List<QuestionType>
that I fill a drop down with. I want to put that selection into the QuestionType
property on the Question
object that I'm creating in the form. I'm using Knockout.js
for the select binding. This sets the self.QuestionType
knockout observable property to a QuestionType
object when the user selects one.
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
I have a hidden field that will hold this object:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
In the subscription for the observable, I set the hidden field to a JSON.stringify
-ed version of the object.
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
In the Question
object, I have a field called QuestionTypeJson
that is filled when the user selects a question type. I use this field to get the QuestionType
in the Question
object like this:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
So if the QuestionTypeJson
field contains something, it will deserialize that and use it for QuestionType
, otherwise it'll just use what is in the backing field.
I have essentially 'passed' a JavaScript object to my model without using Razor
or an Ajax
call. You can probably do something similar to this without using Knockout.js
, but that's what I'm using so...
overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.
overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.
overflow: hidden;
would remove both scrollbars
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
Using @Saikh's answer above, the 2nd option, you can add a space between the time itself and the AM or PM.
REVERSE(LEFT(REVERSE(CONVERT(VARCHAR(20),CONVERT(TIME,myDateTime),100)),2) + ' ' + SUBSTRING(REVERSE(CONVERT(VARCHAR(20),CONVERT(TIME,myDateTime),100)),3,20)) AS [Time],
Messy I know, but it's the solution I chose. Strange that the CONVERT() doesn't add that space automatically. SQL Server 2008 R2
Quick and dirty: just use Redux + react-redux + redux-persist + AsyncStorage for react-native.
It fits almost perfectly the react native world and works like a charm for both android and ios. Also, there is a solid community around it, and plenty of information.
For a working example, see the F8App from Facebook.
What are the different options for data persistence?
With react native, you probably want to use redux and redux-persist. It can use multiple storage engines. AsyncStorage and redux-persist-filesystem-storage are the options for RN.
There are other options like Firebase or Realm, but I never used those on a RN project.
For each, what are the limits of that persistence (i.e., when is the data no longer available)? For example: when closing the application, restarting the phone, etc.
Using redux + redux-persist you can define what is persisted and what is not. When not persisted, data exists while the app is running. When persisted, the data persists between app executions (close, open, restart phone, etc).
AsyncStorage has a default limit of 6MB on Android. It is possible to configure a larger limit (on Java code) or use redux-persist-filesystem-storage as storage engine for Android.
For each, are there differences (other than general setup) between implementing in iOS vs Android?
Using redux + redux-persist + AsyncStorage the setup is exactly the same on android and iOS.
How do the options compare for accessing data offline? (or how is offline access typically handled?)
Using redux, offiline access is almost automatic thanks to its design parts (action creators and reducers).
All data you fetched and stored are available, you can easily store extra data to indicate the state (fetching, success, error) and the time it was fetched. Normally, requesting a fetch does not invalidate older data and your components just update when new data is received.
The same apply in the other direction. You can store data you are sending to server and that are still pending and handle it accordingly.
Are there any other considerations I should keep in mind?
React promotes a reactive way of creating apps and Redux fits very well on it. You should try it before just using an option you would use in your regular Android or iOS app. Also, you will find much more docs and help for those.
I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__
module, it will be accessible as if a global from any other module that includes __builtin__
-- which is all of them, by default.
a.py contains
print foo
b.py contains
import __builtin__
__builtin__.foo = 1
import a
The result is that "1" is printed.
Edit: The __builtin__
module is available as the local symbol __builtins__
-- that's the reason for the discrepancy between two of these answers. Also note that __builtin__
has been renamed to builtins
in python3.
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
_x000D_
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
_x000D_
I was not getting the RSA fingerprint pop up on my phone.
I had to go into the
C:\Users\<userName>\.android\adbkey and adbkey.pub
files, delete those and then do kill and restart of adb server. I had to stop and restart the debugger and connecting as USB in PTP mode.
Because the RSA authorisation key was getting stored in this path, killing and restarting the adb server didn't help.
You can rather use a List, so you can check the existence.
List<int> l = new List<int>();
l.Add(45);
...
...
if (l.Count == 25) {
doStuff();
}
int num = 45;
if (l.Contains(num)) {
doMoreStuff();
}
$(document).ready(function(){
$(window).scrollTop(0);
});
did not work for me as google chrome would just scroll back down after the page finished loading. What I used was
$(document).ready(function() {
var url = window.location.href;
console.log(url);
if( url.indexOf('#') < 0 ) {
window.location.replace(url + "#");
} else {
window.location.replace(url);
}
});
// This loads the page with a # at the end. So it will always load at the top.
You can also try this, if this is what you need:
<style type="text/css">
....
table td div {height:20px;overflow-y:hidden;}
table td.col1 div {width:100px;}
table td.col2 div {width:300px;}
</style>
<table>
<tbody>
<tr><td class="col1"><div>test</div></td></tr>
<tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>
For multiple radio buttons, you have to put same name attribute on your radio button tag. For example;
<input type="radio" name"gender" class="select_gender" value="male">
<input type="radio" name"gender" class="select_gender" value="female">
Once you have radio options, now you can do jQuery code like below to get he value of selected/checked radio option.
$(document).on("change", ".select_gender", function () {
console.log($(this).val()); // Here you will get the current selected/checked radio option value
});
Note: $(document) is used because if the radio button are created after DOM 100% loaded, then you need it, because if you don't use $(document) then jQuery will not know the scope of newly created radion buttons. It's a good practice to do jQuery event calls like this.
Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).
The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits
# the "maths" version
import math
def first_n_digits1(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# The "string" verions
def first_n_digits2(num, n):
return int(str(num)[:n])
%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
It appears to be working fine for mm/dd/yyyy format dates, example:
http://jsfiddle.net/niklasvh/xfrLm/
The only problem I had with your code was the fact that:
var ExpiryDate = document.getElementById(' ExpiryDate').value;
Had a space inside the brackets, before the element ID. Changed it to:
var ExpiryDate = document.getElementById('ExpiryDate').value;
Without any further details regarding the type of data that isn't working, there isn't much else to give input on.
I haven't tried it myself, but this is a free library you could try (I not so sure about the SSL part on this one):
http://www.codeproject.com/KB/IP/imaplibrary.aspx
Also, there is xemail, which has parameters for SSL:
http://xemail-net.sourceforge.net/
[EDIT] If you (or the client) have the money for a professional mail-client, this thread has some good recommendations:
Recommendations for a .NET component to access an email inbox
You can use Collections#sort
to sort things alphabetically.
Got a gotcha for those with their headspace in Pandas and moving to pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
sc = SparkContext(conf = spark_conf)
sqlContext = SQLContext(sc)
records = [
{"colour": "red"},
{"colour": "blue"},
{"colour": None},
]
pandas_df = pd.DataFrame.from_dict(records)
pyspark_df = sqlContext.createDataFrame(records)
So if we wanted the rows that are not red:
pandas_df[~pandas_df["colour"].isin(["red"])]
Looking good, and in our pyspark DataFrame
pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()
So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:
pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()
Although not a merge per se, sometimes the entire contents of another file on another branch are needed. Jason Rudolph's blog post provides a simple way to copy files from one branch to another. Apply the technique as follows:
$ git checkout branch1 # ensure in branch1 is checked out and active
$ git checkout branch2 file.py
Now file.py
is now in branch1.
first convert your array too JSON
while($query->fetch()){
$col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
then vonvert back it to array
foreach($col as &$array){
$array = json_decode($array,true);
}
good luck
Yes. Here's the way using pipe( | ) separator,
try
{
.......
}
catch
{
catch(IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e)
}
You also can use in this form:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
In the light of the evolving thread, I have updated the below:
* html .ie6 {property:value;}
or
.ie6 { _property:value;}
*+html .ie7 {property:value;}
or
*:first-child+html .ie7 {property:value;}
@media screen\9 {
.ie67 {property:value;}
}
or
.ie67 { *property:value;}
or
.ie67 { #property:value;}
@media \0screen\,screen\9 {
.ie678 {property:value;}
}
html>/**/body .ie8 {property:value;}
or
@media \0screen {
.ie8 {property:value;}
}
.ie8 { property /*\**/: value\9 }
@media screen\0 {
.ie8910 {property:value;}
}
@media screen and (min-width:0\0) and (min-resolution: .001dpcm) {
// IE9 CSS
.ie9{property:value;}
}
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.ie9up{property:value;}
}
@media screen and (min-width:0) {
.ie910{property:value;}
}
_:-ms-lang(x), .ie10 { property:value\9; }
_:-ms-lang(x), .ie10up { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.ie10up{property:value;}
}
The use of -ms-high-contrast
means that MS Edge will not be targeted, as Edge does not support -ms-high-contrast
.
_:-ms-fullscreen, :root .ie11up { property:value; }
Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element
Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to html
element:
data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
If possible, identify and fix any issue(s) without hacks. Support progressive enhancement and graceful degradation. However, this is an 'ideal world' scenario not always obtainable, as such- the above should help provide some good options.
If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):
<input name="o" required="required" aria-required="true" type="text">
You should use the submit
event instead of the click
event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault
:
$('form').on('submit', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment
As someone mentioned previously, return false
would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false
at the end.
So if you want to get rid of these default pop-ups, use the click
event on the submit button:
$('form input[type=submit]').on('click', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/
basically it requires a fixed height header and footer. and it absolute positions the table.
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
For Linux, "ps aux | grep kafka" see if kafka properties are shown in the results. E.g. /path/to/kafka/server.properties
if you are making a RecyclerView and using an adapter, what worked for me was:
@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
MODEL model = LIST.get(position);
holder.TEXTVIEW.setText(service.getTitle());
holder.TEXTVIEW.setText(service.getDesc());
Context context = holder.IMAGEVIEW.getContext();
Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}
Please check the answer here:
Possibly unhandled rejection in Angular 1.6
This has been fixed with 316f60f and the fix is included in the v1.6.1 release.
Whilst W3's validator may not complain about an empty href
attribute, the current HTML5 Working Draft specifies:
The
href
attribute ona
andarea
elements must have a value that is a valid URL potentially surrounded by spaces.
A valid URL is a URL which complies with the URL Standard. Now the URL Standard is a bit confusing to get your head around, however nowhere does it state that a URL can be an empty string.
...which means that an empty string is not a valid URL.
The HTML5 Working Draft goes on, however, to state:
Note: The
href
attribute ona
andarea
elements is not required; when those elements do not havehref
attributes they do not create hyperlinks.
This means we can simply omit the href
attribute altogether:
<a class="arrow"></a>
If your intention is that these href
-less a
elements should still require keyboard interraction, you'll have to go down the normal route of assigning a role
and tabindex
alongside your usual click/keydown handlers:
<a class="arrow" role="button" tab-index="0"></a>
by creating an absolute-positioned link inside relative-positioned div.. You need set the link width & height as button dimensions, and left&top coordinates for the left-top corner of button within the wrapping div.
<div style="position:relative">
<img src="" width="??" height="??" />
<a href="#" style="display:block; width:247px; height:66px; position:absolute; left: 48px; top: 275px;"></a>
</div>
Suppose you want to add an item at a position, then the list size must be more than the position.
add(2, item)
: this syntax means, move the old item at position 2 to next index and add the item at 2nd position.
If there is no item in 2nd position, then this will not work, It'll throw an exception.
That means if you want to add something in position 2,
your list size must be at least (2 + 1) =3,
so the items are available at 0,1,2 Position.
in that way it is ensured that the position 2 is accessed safely and there would be no exception.
Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.
Check it here:
http://malsup.com/jquery/form/#getting-started
It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.
Thank you
RAZOR syntax:
@(myNullableDateTime?.ToString("yyyy-MM-dd") ?? String.Empty)
Presumably you have it in a variable and are using JSON.parse(data);
. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because "
is not valid in a JSON object.
You can accept the license agreements of the stated SDKs by going to the SDK Manager (Settings > [Search for Android SDK]) then find the packages noted in the error message and find them there. Chances are, you'll find SDKs that are not fully installed and installing them will ask you to accept the license agreement.
I used format()
method to make a load bar. Here is my solution:
import time
loadbarwidth = 23
for i in range(1, loadbarwidth + 1):
time.sleep(0.1)
strbarwidth = '[{}{}] - {}\r'.format(
(i * '#'),
((loadbarwidth - i) * '-'),
(('{:0.2f}'.format(((i) * (100/loadbarwidth))) + '%'))
)
print(strbarwidth ,end = '')
print()
Output:
[#######################] - 100.00%
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
var val = '@ViewBag.ForSection';
If it's an integer you need to parse it as one i.e.
var val = parseInt(@ViewBag.ForSection);
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0
(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:
levels(df$species) <- c(levels(df$species), "unknown")
df$species[df$depth<10] <- "unknown"
What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:
var y = (x == 2 ? "yes" : "no");
So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:
if (x==2) doSomething();
This is a old question, but to me it still doesn't seem to have a complete answer to the OP's question. The chosen answer about security being the possible issue is actually often not the problem when using the Firefox 'Markdown Viewer' plug-in in my experience. Also, the OP seems to be using MS-Windows, so there is the added issue of specifying different drives.
So, here is a little more complete yet simple answer for the 'Markdown Viewer' plug-in on Windows (and other Markdown renderers I've seen): just enter the local path as you would normally, and if it is an absolute path make sure to start it with a slash. So:
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
That last one was probably what the OP was looking for given their example. Note this can also be used to display directories rather than files.
Though late, I hope this helps!
Are you explicitly setting the values as blank? For example:
<input type="text" name="textfield" value="">
That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete
attribute to the form tag:
<form autocomplete="off" ...></form>
PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.
>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'
You could use .each()
with .children()
and a selector within the parenthesis:
//Grab Each Instance of Box.
$(".box").each(function(i){
//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});
To get the 2 chars ISO 639-1 language identifier use:
System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
JS:
function fun(obj) {
var uid= $(obj).data('uid');
var name= $(obj).data('name');
var value= $(obj).data('value');
}
No, according to Apple here:
Note: You cannot install apps from the App Store in simulation environments.
arl.get(0)[1]
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.
In properties:
security:
datasource:
jdbcUrl: jdbc:mysql://ip:3306/security
username: user
password: pass
In java:
@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){
return DataSourceBuilder
.create()
.build();
}
You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.
If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.
The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.
What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.