I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
The NSURLErrorDomain
error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes
However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.
fenomas's answer was really good...it got me off of looking into the HTML code. I know that jb was looking for something that works in Captivate, but the question is broad enough to include people working out of Flash (I'm using CS5), so I thought I'd throw in the specific answer to my situation here.
If you're using the stock Adobe FLVPlayback component in Flash (you probably are if you used File > Import > Import Video...), there's an option in the Properties panel, under Component Parameters. Look for 'autoPlay' and uncheck it. That'll stop autoplay when the page loads!
For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:
# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
Model.where(attributes).first || Model.create(attributes)
end
Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.
Python os module
Specifically for Python 3.6/3.7:
os.name
: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.
In your case, you want to check for 'nt' as os.name
output:
import os
if os.name == 'nt':
...
There is also a note on os.name
:
See also
sys.platform
has a finer granularity.os.uname()
gives system-dependent version information.The platform module provides detailed checks for the system’s identity.
#!/bin/sh
#Procedures = For DB Backup
#Scheduled at : Every Day 22:00
v_path=/etc/database_jobs/db_backup
logfile_path=/etc/database_jobs
v_file_name=DB_Production
v_cnt=0
MAILTO="[email protected]"
touch "$logfile_path/kaka_db_log.log"
#DB Backup
mysqldump -uusername -ppassword -h111.111.111.111 ddbname > $v_path/$v_file_name`date +%Y-%m-%d`.sql
if [ "$?" -eq 0 ]
then
v_cnt=`expr $v_cnt + 1`
mail -s "DB Backup has been done successfully" $MAILTO < $logfile_path/db_log.log
else
mail -s "Alert : kaka DB Backup has been failed" $MAILTO < $logfile_path/db_log.log
exit
fi
I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.
Because of the adds and removes in arbitrary places on the list,
I went with the LinkedList
implementation.
/* traverses tree starting with given node */
private static List<Node> traverse(Node n)
{
return traverse(Arrays.asList(n));
}
/* traverses tree starting with given nodes */
private static List<Node> traverse(List<Node> nodes)
{
List<Node> open = new LinkedList<Node>(nodes);
List<Node> visited = new LinkedList<Node>();
ListIterator<Node> it = open.listIterator();
while (it.hasNext() || it.hasPrevious())
{
Node unvisited;
if (it.hasNext())
unvisited = it.next();
else
unvisited = it.previous();
it.remove();
List<Node> children = getChildren(unvisited);
for (Node child : children)
it.add(child);
visited.add(unvisited);
}
return visited;
}
private static List<Node> getChildren(Node n)
{
List<Node> children = asList(n.getChildNodes());
Iterator<Node> it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
private static List<Node> asList(NodeList nodes)
{
List<Node> list = new ArrayList<Node>(nodes.getLength());
for (int i = 0, l = nodes.getLength(); i < l; i++)
list.add(nodes.item(i));
return list;
}
I know that it could be done with a FOR but I wanted to know if there's another way
There is another way. You can also do it with map and itemgetter:
>>> from operator import itemgetter
>>> map(itemgetter(1), elements)
This still performs a loop internally though and it is slightly slower than the list comprehension:
setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
Results:
Method 1: 1.25699996948 Method 2: 1.46600008011
If you need to iterate over a list then using a for
is fine.
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
use 'https-proxy-agent' like this
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = process.env.https_proxy || 'other proxy address';
var agent = new HttpsProxyAgent(proxy);
options = {
//...
agent : agent
}
https.get(options, (res)=>{...});
Edit: Note that this answer is now out of date. See Siarhei Kuchuk's answer below for a better fix
UrlEncoding will do what you are suggesting here. With C#, you simply use HttpUtility
, as mentioned.
You can also Regex the illegal characters and then replace, but this gets far more complex, as you will have to have some form of state machine (switch ... case, for example) to replace with the correct characters. Since UrlEncode
does this up front, it is rather easy.
As for Linux versus windows, there are some characters that are acceptable in Linux that are not in Windows, but I would not worry about that, as the folder name can be returned by decoding the Url string, using UrlDecode
, so you can round trip the changes.
can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
});
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock
option.
If you are on Unix, you could use the access time of the files in there. Just enable access time for your filesystem, then run a clean build of all your projects you would like to keep dependencies for and then do something like this (UNTESTED!):
find ~/.m2 -amin +5 -iname '*.pom' | while read pom; do parent=`dirname "$pom"`; rm -Rf "$parent"; done
This will find all *.pom files which have last been accessed more than 5 minutes ago (assuming you started your builds max 5 minutes ago) and delete their directories.
Add "echo " before the rm to do a 'dry-run'.
One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.
>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0
Therefore, I use the following to test if a numpy array has elements:
>>> def elements(array):
... return array.ndim and array.size
>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24
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 to offer this as a better approach - you don't always have the luxury of an identity field:
UPDATE m
SET [status]=10
FROM (
Select TOP (10) *
FROM messages
WHERE [status]=0
ORDER BY [priority] DESC
) m
You can also make the sub-query as complicated as you want - joining multiple tables, etc...
Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages
table. It can be used to update the top N rows from any table, even if that table has no unique key at all.
As @PavelAnossov answered, the canonical answer, use the word_tokenize
function in nltk:
from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)
If your sentence is truly simple enough:
Using the string.punctuation
set, remove punctuation then split using the whitespace delimiter:
import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames
set TEXT_T="myfile.txt"
set /a c=1
setlocal ENABLEDELAYEDEXPANSION
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c=c+1
set OUTPUT_FILE_NAME=output_!c!.txt
echo Output file is !OUTPUT_FILE_NAME!
echo %%i, !c!
)
endlocal
To make cell width exactly same as the longest word of the text, just set width of the cell to 1px
i.e.
td {
width: 1px;
}
This is experimental and i came to know about this while doing trial and error
Live fiddle: http://jsfiddle.net/harshjv/5e2oLL8L/2/
Use:
#include <windows.h>
Sleep(sometime_in_millisecs); // Note uppercase S
And here's a small example that compiles with MinGW and does what it says on the tin:
#include <windows.h>
#include <stdio.h>
int main() {
printf( "starting to sleep...\n" );
Sleep(3000); // Sleep three seconds
printf("sleep ended\n");
}
The problem with your macro is that once you have opened your destination Workbook (xlw
in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Dim myWb as Excel.Workbook
Set myWb = ActiveWorkbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
If you prefer, you could also use myWb.Activate
to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
Answer: Go to the folder where you have installed ORACLE DATABASE. such as E:\oracle\product\10.2.0 [or as your oracle version]\db-1\network\ADMIN
and then copy the two files (1) sqlnet.ora, (2) tnsnames.ora and close this folder.
Go to the folder where you have installed ORACLE DEVELOPER. such as E:\DevSuitHome_1\NETWORK\ADMIN
then rename the two files (1) sqlnet.ora, (2) tnsnames.ora and paste the two copied files here and Your are OK.
I'm surprised that nobody has mentioned InfluxDB retention policies for automatic data removal. You can set a default retention policy and also set them on a per-database level.
From the docs:
CREATE RETENTION POLICY <retention_policy_name> ON <database_name> DURATION <duration> REPLICATION <n> [DEFAULT]
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?) {
Field field = null;
int resId = 0;
try {
field = ?.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
An xmlns
is a unique identifier within the document - it doesn't have to be a URI to the schema:
XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.
xsi:schemaLocation
is supposed to give a hint as to the actual schema location:
can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList
)
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";
To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;
.
If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource
implements IBindingList
; one such structure is BindingList<T>
.
Tip: make sure that you are binding the DisplayMember
to a Property on the class and not a public field. If you class uses public string Name { get; set; }
it will work but if it uses public string Name;
it will not be able to access the value and instead will display the object type for each line in the combo box.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
Not sure if this is the best way to do it, but this makes the spinners disappear on Chrome 8.0.552.5 dev:
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
You can simply use background
CSS property as follows:
tr:hover{
background: #F1F1F2;
}
For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).
Express has a helper for this to make life easier.
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
res.setHeader('Content-type', 'video/quicktime');
If you want something more in-depth, here ya go.
var path = require('path');
var mime = require('mime');
var fs = require('fs');
app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.
Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.
I have had this issue, and I use the following :
ls -dl $PWD/* | grep $PWD
It has always got me the listingI have wanted, but your mileage may vary.
when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically: 4500/1000 = 4.5 --> int(4.5) = 4 and ceil of 4 obviouslly is 4
using 4500/1000.0 the result will be 4.5 and ceil of 4.5 --> 5
Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as "numeric type" and return a result directly as float
Good Luck!!
Solved! The call build job: project, parameters: params
fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List
when params = [:]
. Replacing it with params = null
solved the issue.
Here the working code below.
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1')
}
}
The first line of new text view is unnecessary
t=new TextView(this);
you can just do this
TextView t = (TextView)findViewById(R.id.TextView01);
as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html
Thread thr = new Thread(mTask);
thr.start();
}
Runnable mTask = new Runnable() {
public void run() {
// just sleep for 30 seconds.
try {
Thread.sleep(3000);
runOnUiThread(done);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable done = new Runnable() {
public void run() {
// t.setText("done");
}
};
I find another way of doing the same thing by using @PathParam
. Here is the code sample.
@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
If you really want to got nuts, add a new method to the prototype:
if (!('empty' in Array.prototype)) {
Array.prototype.empty = function () {
return this.length === 0;
};
}
[1, 2].empty() // false
[].empty() // true
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
If your table is MyISAM
:
SELECT *
FROM pages
WHERE MATCH(title, content) AGAINST ('keyword' IN BOOLEAN MODE)
This will be much faster if you create a FULLTEXT
index on your columns:
CREATE FULLTEXT INDEX fx_pages_title_content ON pages (title, content)
, but will work even without the index.
Found solution in http://senthilkl.blogspot.lu/2012/11/how-to-send-html-emails-using-sendemail.html
sendEmail -f "oracle@server" -t "[email protected]" -u "Alert: Backup complete" -o message-content-type=html -o message-file=$LOG_FILE -a $LOG_FILE_ATTACH
Perfectly described here https://www.smashingmagazine.com/2014/05/moving-git-repository-new-server/
First, we have to fetch all of the remote branches and tags from the existing repository to our local index:
git fetch origin
We can check for any missing branches that we need to create a local copy of:
git branch -a
Let’s use the SSH-cloned URL of our new repository to create a new remote in our existing local repository:
git remote add new-origin [email protected]:manakor/manascope.git
Now we are ready to push all local branches and tags to the new remote named new-origin:
git push --all new-origin
git push --tags new-origin
Let’s make new-origin the default remote:
git remote rm origin
Rename new-origin to just origin, so that it becomes the default remote:
git remote rename new-origin origin
In a nutshell, this is the code which works for me :)
WebDriver driver;
WebElement element;
String value;
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
I was creating a JSON-LD to create a site review script.
**DECLARE @json VARCHAR(MAX);**
The actual JSON is about 94K.
I got this to work by using the CAST('' AS VARCHAR(MAX)) + @json, as explained by other contributors:-
so **SET @json = CAST('' AS VARCHAR(MAX)) + (SELECT .....**
2/ I also had to change the Query Options:- Query Options -> 'results' -> 'grid' -> 'Maximum Characters received' -> 'non-XML Data' SET to 2000000. (I left the 'results' -> 'text' -> 'Maximum number of characters displayed in each column' as the default)
On the basic question of why openssl is not found: Short answer:Some installation packages for openssl have a default openssl.cnf pre-included. Other packages do not. In the latter case you will include one from the link shown below; You can enter additional user-specifics --DN name,etc-- as needed.
From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:
"OPENSSL LIBRARY CONFIGURATION
Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.
To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.
The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"
So it appears one must self configure openssl.cnf according to your Distinguished Name (DN), along with other entries specific to your use.
Here is the template file from which you can generate openssl.cnf with your specific entries.
One Application actually has a demo installation that includes a demo .cnf file.
Additionally, if you need to programmatically access .cnf files, you can include appropriate headers --openssl/conf.h-- and parse your .cnf files using
CONF_modules_load_file(const char *filename, const char *appname,
unsigned long flags);
Here are docs for "CONF_modules_load_file";
What git-revert does is create a commit which undoes changes made in a given commit, creating a commit which is reverse (well, reciprocal) of a given commit. Therefore
git revert <SHA-1>
should and does work.
If you want to rewind back to a specified commit, and you can do this because this part of history was not yet published, you need to use git-reset, not git-revert:
git reset --hard <SHA-1>
(Note that --hard
would make you lose any non-committed changes in the working directory).
By the way, perhaps it is not obvious, but everywhere where documentation says <commit>
or <commit-ish>
(or <object>
), you can put an SHA-1 identifier (full or shortened) of commit.
On a large iteration I like using interrupts. Just press Ctrl + C to quit:
my $exitflag = 0;
$SIG{INT} = sub { $exitflag=1 };
while(!$exitflag) {
# Do your stuff
}
I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel
wasn’t installed in the virtualenv.
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
Concatenate with & operator
Dim str as String 'no need to create a string instance
str = "Hello " & "World"
You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.
Concatenate with String.Concat()
str = String.Concat("Hello ", "World")
Useful when concatenating array of strings
StringBuilder.Append()
When concatenating large amounts of strings use StringBuilder, it will result in much better performance.
Dim sb as new System.Text.StringBuilder()
str = sb.Append("Hello").Append(" ").Append("World").ToString()
Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.
Select your repository from Dashboard or Repository tab.
And then just click on Download tab having icon of download. It will Let you download whole repository in zip format.
If you're using rbenv
running rbenv rehash
can solve this after you've installed bundler
and are still getting the issue.
Apart from checking 'Import Maven projects automatically', make sure that settings.xml file from File > Settings > Maven > User Settings file exist, If doesn't exist then override and provide your settings.xml file path.
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
You can use ping:
ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul:
It will wait 10 seconds.
The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait.
Keep in mind that the purpose of the -w
is not to wait one second. It's to ensure that you wait no more than one second in the event that there are network problems. ping
on its own will send one ICMP packet per second. It's probably not required for localhost, but old habits die hard.
It's better to have a proper JSON format instead of directly using the one converted from XML.
[
{
"number": "2013-W45",
"days": [
{
"dow": "1",
"templateDay": "Monday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
},
{
"name": "work 9-5",
}
]
},
{
"dow": "2",
"templateDay": "Tuesday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
}
]
}
]
}
]
This will make things much easier and easy to loop through.
Now you can write the loop as -
<div ng-repeat="week in myData">
<div ng-repeat="day in week.days">
{{day.dow}} - {{day.templateDay}}
<b>Jobs:</b><br/>
<ul>
<li ng-repeat="job in day.jobs">
{{job.name}}
</li>
</ul>
</div>
</div>
Use the getWidth method in the following class:
import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
class StringMetrics {
Font font;
FontRenderContext context;
public StringMetrics(Graphics2D g2) {
font = g2.getFont();
context = g2.getFontRenderContext();
}
Rectangle2D getBounds(String message) {
return font.getStringBounds(message, context);
}
double getWidth(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getWidth();
}
double getHeight(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getHeight();
}
}
You can use .css()
to get the value of "visibility":
if( ! ( $("#singlechatpanel-1").css('visibility') === "hidden")){
}
assertTrue
will fail if the second parameter evaluates to false
(in other words, it ensures that the value is true). assertFalse
does the opposite.
assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);
assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);
As with many other things, the best way to become familiar with these methods is to just experiment :-).
Most minimal way to achieve this (that I know of):
.text-monospace
to all texts in in the card.Add .text-truncate
in the card's title and or other texts. This forces texts to a single line. Making the cards have same height.
Get the XML using Ajax call, find the main element, loop through all the element and append data in table.
Sample code
//ajax call to load XML and parse it
$.ajax({
type: 'GET',
url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml', // The file path.
dataType: 'xml',
success: function(xml) {
//find all book tags, loop them and append to table body
$(xml).find('book').each(function() {
// Append new data to the tbody element.
$('#tableBody').append(
'<tr>' +
'<td>' +
$(this).find('author').text() + '</td> ' +
'<td>' +
$(this).find('title').text() + '</td> ' +
'<td>' +
$(this).find('genre').text() + '</td> ' +
'<td>' +
$(this).find('price').text() + '</td> ' +
'<td>' +
$(this).find('description').text() + '</td> ' +
'</tr>');
});
}
});
Fiddle link: https://jsfiddle.net/pn9xs8hf/2/
with a reference to Microsoft.VisualBasic
Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);
This is much simple and easy way.
import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)
check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html
FutureWarning: The sheetname
keyword is deprecated for newer Pandas versions, use sheet_name
instead.
As an alternative to reading a data from a stream to a byte array, you could let the framework handle everything and just use a StreamReader
set up with an ASCII encoding to read in the string. That way you don't need to worry about getting the appropriate buffer size or larger data sizes.
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
string theString = reader.ReadToEnd();
// do something with theString
}
I've connected to USB port directly in my laptop and timeout issue has been resolved.
Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.
So make sure that it is visible by your OS.
It bugged me too to find a solution to mimic interfaces with the lower impacts possible.
One solution could be to make a tool :
/**
@parameter {Array|object} required : method name list or members types by their name
@constructor
*/
let Interface=function(required){
this.obj=0;
if(required instanceof Array){
this.obj={};
required.forEach(r=>this.obj[r]='function');
}else if(typeof(required)==='object'){
this.obj=required;
}else {
throw('Interface invalid parameter required = '+required);
}
};
/** check constructor instance
@parameter {object} scope : instance to check.
@parameter {boolean} [strict] : if true -> throw an error if errors ar found.
@constructor
*/
Interface.prototype.check=function(scope,strict){
let err=[],type,res={};
for(let k in this.obj){
type=typeof(scope[k]);
if(type!==this.obj[k]){
err.push({
key:k,
type:this.obj[k],
inputType:type,
msg:type==='undefined'?'missing element':'bad element type "'+type+'"'
});
}
}
res.success=!err.length;
if(err.length){
res.msg='Class bad structure :';
res.errors=err;
if(strict){
let stk = new Error().stack.split('\n');
stk.shift();
throw(['',res.msg,
res.errors.map(e=>'- {'+e.type+'} '+e.key+' : '+e.msg).join('\n'),
'','at :\n\t'+stk.join('\n\t')
].join('\n'));
}
}
return res;
};
Exemple of use :
// create interface tool
let dataInterface=new Interface(['toData','fromData']);
// abstract constructor
let AbstractData=function(){
dataInterface.check(this,1);// check extended element
};
// extended constructor
let DataXY=function(){
AbstractData.apply(this,[]);
this.xy=[0,0];
};
DataXY.prototype.toData=function(){
return [this.xy[0],this.xy[1]];
};
// should throw an error because 'fromData' is missing
let dx=new DataXY();
With classes
class AbstractData{
constructor(){
dataInterface.check(this,1);
}
}
class DataXY extends AbstractData{
constructor(){
super();
this.xy=[0,0];
}
toData(){
return [this.xy[0],this.xy[1]];
}
}
It's still a bit performance consumming and require dependancy to the Interface class, but can be of use for debug or open api.
You can solve it like this:
git reset --hard sha
where sha
e.g.: 85a108ec5d8443626c690a84bc7901195d19c446
You can get the desired sha with the command:
git log
* for python 2.x *
Use a trailing comma to avoid a newline.
print "Hey Guys!",
print "This is how we print on the same line."
The output for the above code snippet would be,
Hey Guys! This is how we print on the same line.
* for python 3.x *
for i in range(10):
print(i, end="<separator>") # <separator> = \n, <space> etc.
The output for the above code snippet would be (when <separator> = " "
),
0 1 2 3 4 5 6 7 8 9
There is a difference between find
and find_by
in that find
will return an error if not found, whereas find_by
will return null.
Sometimes it is easier to read if you have a method like find_by email: "haha"
, as opposed to .where(email: some_params).first
.
I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)
#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]
DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)
The first question is what are your needs? UTF-8 encoding is a pretty good compromise between taking text created with a cheap editor and support for a wide variety of languages. In regards to the browser identifying the encoding, the response (from the web server) should tell the browser the encoding. Still most browsers will attempt to guess, because this is either missing or wrong in so many cases. They guess by reading some amount of the result stream to see if there is a character that does not fit in the default encoding. Currently all browser(? I did not check this, but it is pretty close to true) use utf-8 as the default.
So use utf-8 unless you have a compelling reason to use one of the many other encoding schemes.
I've solved my problems, so I post here the correct code in case someone needs similar stuff.
Open Port
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );
Set parameters
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
Write
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1)
worked fine.
At last, read:
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( USB, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
This one worked for me. Thank you all!
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
On my mac version of VS Code, I select the section, then the shortcut is Ctrl+j to remove line breaks.
As stated in the relevant RxJS documentation, the .subscribe()
method can take a third argument that is called on completion if there are no errors.
For reference:
[onNext]
(Function
): Function to invoke for each element in the observable sequence.[onError]
(Function
): Function to invoke upon exceptional termination of the observable sequence.[onCompleted]
(Function
): Function to invoke upon graceful termination of the observable sequence.
Therefore you can handle your routing logic in the onCompleted
callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
As a side note, there is also a .finally()
method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).
Rx.Observable.prototype.finally(action)
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
For instance, here is a basic example:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
If you just want the node closest to the text you're searching for, you could use this:
$('*:contains("my text"):last');
This will even work if your HTML looks like this:
<p> blah blah <strong>my <em>text</em></strong></p>
Using the above selector will find the <strong>
tag, since that's the last tag which contains that entire string.
You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
Had the very same problem, but in my case the reason was update of Ubuntu and php version - from 18.04 and php-7.2 up to 20.04 and php-7.4.
The Nginx server was the same, so in my /etc/nginx/sites-available/default was old data:
server {
location /pma {
location ~ ^/pma/(.+\.php)$ {
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
}
}
I could not get phpmyadmin to work with any of php.ini changes and all answers from this thread, but at some moment I had opened the /etc/nginx/sites-available/default and realised, that I still had old version of php. So I just changed it to
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
and the issue was gone, phpmyadmin magically started to work without any mysqli-file complaint. I even double checked it, but yeap, that's how it works - if you have wrong version for php-fpm.sock in your nginx config file, your phpmyadmin will not work, but the shown reason will be 'The mysqli extension is missing'
Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8
Reference: https://developer.android.com/studio/releases/index.html
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
You should use thenReturn
or doReturn
when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.
thenReturn(T value)
Sets a return value to be returned when the method is called.
@Test
public void test_return() throws Exception {
Dummy dummy = mock(Dummy.class);
int returnValue = 5;
// choose your preferred way
when(dummy.stringLength("dummy")).thenReturn(returnValue);
doReturn(returnValue).when(dummy).stringLength("dummy");
}
Answer
is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.
Use
doAnswer()
when you want to stub a void method with genericAnswer
.Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
@Test
public void test_answer() throws Exception {
Dummy dummy = mock(Dummy.class);
Answer<Integer> answer = new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
String string = invocation.getArgumentAt(0, String.class);
return string.length() * 2;
}
};
// choose your preferred way
when(dummy.stringLength("dummy")).thenAnswer(answer);
doAnswer(answer).when(dummy).stringLength("dummy");
}
If you're still getting that page, it's likely that it's blowing up before getting past the Web.Config
Make sure that ASP.Net has permissions it needs to things like the .Net Framework folders, the IIS Metabase, etc. Do you have any way of checking that ASP.Net is installed correctly and associated in IIS correctly?
Edit: After Greg's comment it occured to me I assumed that what you posted was your entire very minimal web.config, is there more to it? If so can you post the entire web.config?
This error
Failure [INSTALL_FAILED_OLDER_SDK]
Means that you're trying to install an app that has a higher minSdkVersion
specified in its manifest than the device's API level. Change that number to 8
and it should work. I'm not sure about the other error, but it may be related to this one.
I added the DLLs manually. Right clicked on References in the project, select Add Reference and then in the dialog pressed the Browse button. The NuGet DLLs where in the packages directory of the solution. To get the names of them you can right click on references in another project that's working properly and select properties and look in the path property.
Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.
This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.
For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:
Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543
Your Outlook recipient will see the information all smashed together, as follows:
Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543
There doesn't seem to be an easy solution. Alternatives are:
A newer way to do this in .NET Core is with TagHelpers
.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
Building on these examples (MaxLength, Label), you can extend the existing TagHelper
to suit your needs.
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("input", Attributes = "asp-for")]
public class RequiredTagHelper : TagHelper
{
public override int Order
{
get { return int.MaxValue; }
}
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["required"] == null)
{
var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
if (isRequired)
{
var requiredAttribute = new TagHelperAttribute("required");
output.Attributes.Add(requiredAttribute);
}
}
}
}
}
You'll then need to add it to be used in your views:
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
Given the following model:
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectName.Models
{
public class Foo
{
public int Id { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
}
}
and view (snippet):
<label asp-for="Name"></label>
<input asp-for="Name"/>
Will result in this HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
I hope this is helpful to anyone with same question but using .NET Core.
It would seem to me that you are fighting with the question what mutable/immutable actually means. So here is a simple explenation:
First we need a foundation to base the explenation on.
So think of anything that you program as a virtual object, something that is saved in a computers memory as a sequence of binary numbers. (Don't try to imagine this too hard, though.^^) Now in most computer languages you will not work with these binary numbers directly, but rather more you use an interpretation of binary numbers.
E.g. you do not think about numbers like 0x110, 0xaf0278297319 or similar, but instead you think about numbers like 6 or Strings like "Hello, world". Never the less theses numbers or Strings are an interpretation of a binary number in the computers memory. The same is true for any value of a variable.
In short: We do not program with actual values but with interpretations of actual binary values.
Now we do have interpretations that must not be changed for the sake of logic and other "neat stuff" while there are interpretations that may well be changed. For example think of the simulation of a city, in other words a program where there are many virtual objects and some of these are houses. Now may these virtual objects (the houses) be changed and can they still be considered to be the same houses? Well of course they can. Thus they are mutable: They can be changed without becoming a "completely" different object.
Now think of integers: These also are virtual objects (sequences of binary numbers in a computers memory). So if we change one of them, like incrementing the value six by one, is it still a six? Well of course not. Thus any integer is immutable.
So: If any change in a virtual object means that it actually becomes another virtual object, then it is called immutable.
Final remarks:
(1) Never mix up your real-world experience of mutable and immutable with programming in a certain language:
Every programming language has a definition of its own on which objects may be muted and which ones may not.
So while you may now understand the difference in meaning, you still have to learn the actual implementation for each programming language. ... Indeed there might be a purpose of a language where a 6 may be muted to become a 7. Then again this would be quite some crazy or interesting stuff, like simulations of parallel universes.^^
(2) This explenation is certainly not scientific, it is meant to help you to grasp the difference between mutable and immutable.
The copy() runs for the least length of dst and src, so you must initialize the dst to the desired length.
A := []int{1, 2, 3}
B := make([]int, 3)
copy(B, A)
C := make([]int, 2)
copy(C, A)
fmt.Println(A, B, C)
Output:
[1 2 3] [1 2 3] [1 2]
You can initialize and copy all elements in one line using append() to a nil slice.
x := append([]T{}, []...)
Example:
A := []int{1, 2, 3}
B := append([]int{}, A...)
C := append([]int{}, A[:2]...)
fmt.Println(A, B, C)
Output:
[1 2 3] [1 2 3] [1 2]
Comparing with allocation+copy(), for greater than 1,000 elements, use append. Actually bellow 1,000 the difference may be neglected, make it a go for rule of thumb unless you have many slices.
BenchmarkCopy1-4 50000000 27.0 ns/op
BenchmarkCopy10-4 30000000 53.3 ns/op
BenchmarkCopy100-4 10000000 229 ns/op
BenchmarkCopy1000-4 1000000 1942 ns/op
BenchmarkCopy10000-4 100000 18009 ns/op
BenchmarkCopy100000-4 10000 220113 ns/op
BenchmarkCopy1000000-4 1000 2028157 ns/op
BenchmarkCopy10000000-4 100 15323924 ns/op
BenchmarkCopy100000000-4 1 1200488116 ns/op
BenchmarkAppend1-4 50000000 34.2 ns/op
BenchmarkAppend10-4 20000000 60.0 ns/op
BenchmarkAppend100-4 5000000 240 ns/op
BenchmarkAppend1000-4 1000000 1832 ns/op
BenchmarkAppend10000-4 100000 13378 ns/op
BenchmarkAppend100000-4 10000 142397 ns/op
BenchmarkAppend1000000-4 2000 1053891 ns/op
BenchmarkAppend10000000-4 200 9500541 ns/op
BenchmarkAppend100000000-4 20 176361861 ns/op
See my answer to Stack Overflow question Finish All previous activities.
What you need is to add the Intent.FLAG_CLEAR_TOP
. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.
Another thing that you need is the SINGLE_TOP
flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.
Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent)
(you need to overload it to handle it) in the target activity.
Then in onNewIntent
you have a method called restart or something that will call finish()
and launch a new intent toward itself, or have a repopulate()
method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the
onCreate
logic into a separate method that you can call for populate.
I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.
var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));
If you use <tbody>
or <tfoot>
in your table, you'll have to use the following syntax or you'll get a incorrect value:
var rowCount = $('#myTable >tbody >tr').length;
Specifying a default value would also work, assuming a default value is appropriate.
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
It depends on which Ruby version you use:
Ruby 2.4 and higher:
It just works, as since Ruby v2.4.0 supports Unicode case mapping:
"?????".capitalize #=> ?????
Ruby 2.3 and lower:
"maria".capitalize #=> "Maria"
"?????".capitalize #=> ?????
The problem is, it just doesn't do what you want it to, it outputs ?????
instead of ?????
.
If you're using Rails there's an easy workaround:
"?????".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte
Otherwise, you'll have to install the unicode gem and use it like this:
require 'unicode'
Unicode::capitalize("?????") #=> ?????
Ruby 1.8:
Be sure to use the coding magic comment:
#!/usr/bin/env ruby
puts "?????".capitalize
gives invalid multibyte char (US-ASCII)
, while:
#!/usr/bin/env ruby
#coding: utf-8
puts "?????".capitalize
works without errors, but also see the "Ruby 2.3 and lower" section for real capitalization.
I was looking at this problem just now and found this solution. If your RowSource points to a range of cells, the column headings in a multi-column listbox are taken from the cells immediately above the RowSource.
Using the example pictured here, inside the listbox, the words Symbol and Name appear as title headings. When I changed the word Name in cell AB1, then opened the form in the VBE again, the column headings changed.
The example came from a workbook in VBA For Modelers by S. Christian Albright, and I was trying to figure out how he got the column headings in his listbox :)
import os
import ftplib
from contextlib import closing
with closing(ftplib.FTP()) as ftp:
try:
ftp.connect(host, port, 30*5) #5 mins timeout
ftp.login(login, passwd)
ftp.set_pasv(True)
with open(local_filename, 'w+b') as f:
res = ftp.retrbinary('RETR %s' % orig_filename, f.write)
if not res.startswith('226 Transfer complete'):
print('Downloaded of file {0} is not compile.'.format(orig_filename))
os.remove(local_filename)
return None
return local_filename
except:
print('Error during download from FTP')
Take a look at the very recently released SSHD, which is based on the Apache MINA project.
for online solution try maqetta and aloha editor
for offline solution (download-able) try blue griffon
they are free :) oh yeah, one more, my favorite editor :) and game editor also: construct2
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
Just in case anyone else runs into this. I troubleshooted all of these steps and it turns out because I unzipped some files from a MAC, Microsoft automatically without any notification Encrypted the files. After hours of trying to set folder permissions I went in and saw the file names were green which means the files were encrypted and IIS will throw the same error even if folder permissions are correct.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).
With this, amongst many other things, you can mock the construction of new objects in a very easy way.
If I'm not wrong, you can start your application using command line and thus also using a batch file. In that case it is not a very hard task to start it with Windows login.
You just create a batch file with the following content:
node C:\myapp.js
and save it with .bat extention. Here myapp.js is your app, which in this example is located in C: drive (spcify the path).
Now you can just throw the batch file in your startup folder which is located at C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just open it using %appdata% in run dailog box and locate to >Roaming>Microsoft>Windows>Start Menu>Programs>Startup
The batch file will be executed at login time and start your node application from cmd.
How to run a shell script from a Perl program
1. Using system
system($command, @arguments);
For example:
system("sh", "script.sh", "--help" ); system("sh script.sh --help");
System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.
2. Using
exec
This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.
3. Using backticks or
qx//
my $output = `script.sh --option`; my $output = qx/script.sh --option/;
The backtick operator and it's equivalent
qx//
, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.
It looks like Microsoft invaded brains of all other respondents and made them write as complicated solutions as possible. Here is the simplest way without any additional functions/declare statements:
SELECT geography::Point(LATITUDE_1, LONGITUDE_1, 4326).STDistance(geography::Point(LATITUDE_2, LONGITUDE_2, 4326))
Simply substitute your data instead of LATITUDE_1
, LONGITUDE_1
, LATITUDE_2
, LONGITUDE_2
e.g.:
SELECT geography::Point(53.429108, -2.500953, 4326).STDistance(geography::Point(c.Latitude, c.Longitude, 4326))
from coordinates c
Converting from java.lang.Object
directly to ArrayList<T>
which has elements of T is not recommended as it can lead to casting Exceptions. The recommended way is to first convert to a primitive array of T
and then use Arrays.asList(T[])
One of the ways how you get entity from a java javax.ws.rs.core.Response
is as follows -
T[] t_array = response.readEntity(object);
ArrayList<T> t_arraylist = Arrays.asList(t_array);
You will still get Unchecked cast warnings.
see http://en.wikipedia.org/wiki/Globally_unique_identifier
There is no guarantee that an alpha will actually be there.
The simplest one got to be:
def html = "http://google.com".toURL().text
FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>
(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss
to your modal tag)
app.directive('easyDismiss', function() {
return {
restrict: 'A',
link: function ($scope, $element) {
var clickSubmit = function (e) {
if (e.which == 13) {
$element.find('[type="submit"]').click();
}
};
$element.on('show.bs.modal', function() {
$(document).on('keypress', clickSubmit);
});
$element.on('hide.bs.modal', function() {
$(document).off('keypress', clickSubmit);
});
}
};
});
For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.
String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)
mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);
You can set the "value" property
dateTimePicker1.Value = DateTime.Today;
Try the following:
adb kill-server
adb start-server
Step 1: Define attributes in $appends
Step 2: Define accessor for that attributes.
Example:
<?php
...
class Movie extends Model{
protected $appends = ['cover'];
//define accessor
public function getCoverAttribute()
{
return json_decode($this->InJson)->cover;
}
If you are using Linux environment then you can use the PHP's exec command to invoke the linux curl. Here is a sample code, which will make a Asynchronous HTTP post.
function _async_http_post($url, $json_string) {
$run = "curl -X POST -H 'Content-Type: application/json'";
$run.= " -d '" .$json_string. "' " . "'" . $url . "'";
$run.= " > /dev/null 2>&1 &";
exec($run, $output, $exit);
return $exit == 0;
}
This code does not need any extra PHP libs and it can complete the http post in less than 10 milliseconds.
First, you need to understand the difference between window
and document
. The window
object is a top level client side object. There is nothing above the window
object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document
object is an object of the window
object. To change the document
's background color, you'd set the document
's bgcolor
property.
window.document.bgcolor = "red"
To answer your question, There is no difference in the end result between window
and document
scrollTop
. Both will give the same output.
In general use document
mainly to register events and use window
to do things like scroll
, scrollTop
, and resize
.
Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update: ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"/>
You can create simple float-based forms without having to lose your liquid layout. For example:
<style type="text/css">
.row { clear: left; padding: 6px; }
.row label { float: left; width: 10em; }
.row .field { display: block; margin-left: 10em; }
.row .field input, .row .field select {
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;
}
</style>
<div class="row">
<label for="f-firstname">First name</label>
<span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
</div>
<div class="row">
<label for="f-state">State</label>
<span class="field"><select name="state" id="f-state">
<option value="NY">NY</option>
</select></span>
</div>
This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.
For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.
Using Jquery for active link:
$(function(){
$('#nav a').filter(function() {
return this.href==location.href
})
.parent().addClass('active').siblings().removeClass('active')
$('#nav a').click(function(){
$(this).parent().addClass('active').siblings().removeClass('active')
})
});
Use Component life cycle method or document ready function as specified in Jquery.
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
You can follow this pattern also
<form action="/action_page.php">
E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
<input type="submit">
</form>
Ref : In W3Schools
File modification:
ls -t
Inode change:
ls -tc
File access:
ls -tu
"Newest" one at the bottom:
ls -tr
None of this is a creation time. Most Unix filesystems don't support creation timestamps.
In both cases yes it can, and this is the default behaviour for both IE and Edge.
The other answers add valuable insight but chiefly describe the behaviour in Chrome. it's important to note that the behaviour is completely different in IE. CMBuckley's very helpful test script demonstrates that in (say) Chrome, the cookies are not shared between root and subdomains when no domain is specified. However the same test in IE shows that they are shared. This IE case is closer to the take-home description in CMBuckley's www-or-not-www link. I know this to be the case because we have a system that used different servicestack cookies on both the root and subdomain. It all worked fine until someone accessed it in IE and the two systems fought over whose session cookie would win until we blew up the cache.
SELECT
*
FROM
(SELECT MAX(PriceDate) AS MaxP, Partid FROM MyPrices GROUP BY Partid) MaxP
JOIN
MyPrices MP On MaxP.Partid = MP.Partid AND MaxP.MaxP = MP.PriceDate
JOIN
MyParts P ON MP.Partid = P.Partid
You to get the latest pricedate for partid first (a standard aggregate), then join it back to get the prices (which can't be in the aggregate), followed by getting the part details.
You can try:
SELECT *
FROM public."my_table"
Don't forget double quotes near my_table.
When you import a module,
import file_name
Python stores the compiled bytecode in __pycache__
directory so that future imports can use it directly, rather than having to parse and compile the source again.
It does not do that for merely running a script, only when a file is imported.
(Previous versions used to store the cached bytecode as .pyc files that littered up the same directory as the .py files, but starting in Python 3 they were moved to a subdirectory to make things tidier.)
PYTHONDONTWRITEBYTECODE ---> If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
UPDATE `tbl_user` SET `name`=concat('tbl_user.first_name','tbl_user.last_name') WHERE student_roll>965
For it was betternet extension was causing issue. I think any kind of proxy extension installed on Chrome causing issue.
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
=VLOOKUP(A2,IF(B1:B3="B",A1:C3,""),1,FALSE)
Ctrl+Shift+Enter
to enter.
Like so
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.
It is easier with Kotlin using for-in loop:
for (childView in ll.children) {
//childView is a child of ll
}
Here ll
is id
of LinearLayout
defined in layout XML.
Code:
string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";
Console.WriteLine(someString1);
Console.WriteLine(someString2);
Output:
Hello
World!
\tHello\r\n\tWorld!\r\n
Is this what you want?
It's a simple "&" function.
=cell&"yourtexthere"
Example - your cell says Mickey, and you want Mickey Mouse. Mickey is in A2. In B2, type
=A2&" Mouse"
Then, copy and "paste special" for values.
B2 now reads "Mickey Mouse"
Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":
class AddColumnToWidgets < ActiveRecord::Migration
def change
add_column :widgets, :colour, :string, default: 'red'
end
end
This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.
Use the throw statement.
JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".
If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.
position:absolute;
top:0px;
margin:5px;
Solved my problem.
Using the backtick (`) works fine for me if I put them in the following places:
$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""
$cmd
returns as:
\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"
Is that what you were looking for?
The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.
The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:
$cmd=@'
"\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'""
'@
The opening and closing symbols must be on their own line as shown above.
Try this:
In the Restore DB wizard window, go to Files tab, Uncheck "Relocate All files to folder" check box then change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will get restored successfully.
ORACLE/PLSQL:
NVL FUNCTION
SELECT NVL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
This SQL statement would return 0
if the SUM(Price)
returned a null value. Otherwise, it would return the SUM(Price)
value.
I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:
protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(catalog)
.withFunctionName(functionName)
.withReturnValue()
.declareParameters(buildSqlParameters());
return call;
}
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
};
}
The buildSqlParameters method should have included the SqlOutParameter:
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
new SqlOutParameter("l_clob", Types.CLOB) // <-- This was missing!
};
}
I spent many hours spent tearing out my hair over this. The build output wasn't consistent; different projects would be "not up to date" for different reasons from one build to the next consecutive build. I eventually found that the culprit was DropBox (3.0.4). I junction my source folder from ...\DropBox into my projects folder (not sure if this is the reason), but DropBox somehow "touches" files during a build. Paused syncing and everything is consistently up-to-date.
Another way to use target="_blank"
is:
onclick="this.target='_blank'"
Example:
<a href="http://www.url.com" onclick="this.target='_blank'">Your Text<a>
In Python 3, dict.values()
(along with dict.keys()
and dict.items()
) returns a view
, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values()
in a call to list
like so:
v = list(d.values())
{names[i]:v[i] for i in range(len(names))}
I'm partial to the following approach for files that have headers:
File.open(file, "r") do |fh|
header = fh.readline
# Process the header
while(line = fh.gets) != nil
#do stuff
end
end
This allows you to process a header line (or lines) differently than the content lines.
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php
file (in your theme) add new function
In functions.php
file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.
Documenting in detail for future readers:
The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url)
method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.
The below is the skeleton on how you would accomplish this:
class CustomWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Based on some condition you need to determine if you are going to load the url
// in your web view itself or in a browser.
// You can use `host` or `scheme` or any part of the `uri` to decide.
if (/* any condition */) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// e.g. open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
}
Just like shouldOverrideUrlLoading
, you can come up with a similar approach for shouldInterceptRequest
method.
When I find myself thinking about using Manager
or Helper
in a class name, I consider it a code smell that means I haven't found the right abstraction yet and/or I'm violating the single responsibility principle, so refactoring and putting more effort into design often makes naming much easier.
But even well-designed classes don't (always) name themselves, and your choices partly depend on whether you're creating business model classes or technical infrastructure classes.
Business model classes can be hard, because they're different for every domain. There are some terms I use a lot, like Policy
for strategy classes within a domain (e.g., LateRentalPolicy
), but these usually flow from trying to create a "ubiquitous language" that you can share with business users, designing and naming classes so they model real-world ideas, objects, actions, and events.
Technical infrastructure classes are a bit easier, because they describe domains we know really well. I prefer to incorporate design pattern names into the class names, like InsertUserCommand,
CustomerRepository,
or SapAdapter.
I understand the concern about communicating implementation instead of intent, but design patterns marry these two aspects of class design - at least when you're dealing with infrastructure, where you want the implementation design to be transparent even while you're hiding the details.
I think Mehmet Duran is almost right, but there were some problems when using multiple classes with the same tooltip and their placement. The following code also avoids js errors checking if there is any class called "tooltip_class". Hope this helps.
if (jQuery(".tooltip_class")[0]){
jQuery('.tooltip_class')
.attr('title', 'New Title.')
.attr('data-placement', 'right')
.tooltip('fixTitle')
.tooltip('hide');
}
I wrote this based on Maerlyn's response. This function will work regardless of the character encoding on the page. It also won't turn single quotes in to dashes :)
function slugify ($string) {
$string = utf8_encode($string);
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$string = preg_replace('/[^a-z0-9- ]/i', '', $string);
$string = str_replace(' ', '-', $string);
$string = trim($string, '-');
$string = strtolower($string);
if (empty($string)) {
return 'n-a';
}
return $string;
}
Yes, play with figuresize
and dpi
like so (before you call your subplot):
fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')
As @tacaswell and @Hagne pointed out, you can also change the defaults if it's not a one-off:
plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower
Another easy way:
//In your ListViewActivity:
public void refreshListView() {
listAdapter = new ListAdapter(this);
setListAdapter(listAdapter);
}
You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).
Detecting a loop in a linked list can be done in one of the simplest ways, which results in O(N) complexity using hashmap or O(NlogN) using a sort based approach.
As you traverse the list starting from head, create a sorted list of addresses. When you insert a new address, check if the address is already there in the sorted list, which takes O(logN) complexity.
As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with:
navigationView.findViewById(R.id.navigation_header_text)
no longer works.
A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.
For example:
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);
Ideally there should be a method getHeaderView()
but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.
You can use like
My table is bellow like..
<table>
<thead>
<tr>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr th:each="user: ${staffList}">
<td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
</tr>
</tbody>
</table>
Here is my controller ..
@GetMapping(value = "/details-view/{userId}")
public String details(@PathVariable String userId) {
Logger.getLogger(getClass().getName()).info("userId-->" + userId);
return "user-details";
}
No, unless you want to break compatibility and your compiler supports it.
this is how:
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url )
{
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
$options = array(
CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get
CURLOPT_POST =>false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file
CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
Example
//Read a web page and check for errors:
$result = get_web_page( $url );
if ( $result['errno'] != 0 )
... error: bad url, timeout, redirect loop ...
if ( $result['http_code'] != 200 )
... error: no page, no permissions, no service ...
$page = $result['content'];
You can invoke a PHP script manually from the command line
hello.php
<?php
echo 'hello world!';
?>
Command line:
php hello.php
Output:
hello world!
See the documentation: http://php.net/manual/en/features.commandline.php
EDIT OP edited the question to add a critical detail: the script is to be executed by another script.
There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include
(docs) and/or require
(docs) (note: include_once
and require_once
are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:
include('hello.php');
/* output
hello world!
*/
Second and slightly more complex is to use shell_exec
(docs). With shell_exec
, you will call the php binary and pass the desired script as the argument. Your code would look like this:
$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/
Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)
$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/
Documentation for functions used
include
: http://us2.php.net/manual/en/function.include.phprequire
: http://us2.php.net/manual/en/function.require.phpshell_exec
: http://us2.php.net/manual/en/function.shell-exec.phpcurl_init
: http://us2.php.net/manual/en/function.curl-init.phpcurl_setopt
: http://us2.php.net/manual/en/function.curl-setopt.phpcurl_exec
: http://us2.php.net/manual/en/function.curl-exec.phpcurl_close
: http://us2.php.net/manual/en/function.curl-close.phpthis was available in php 5.6 in php 7+ you should declare the array first
$users = array(); // not $users = ";
$users[] = "762";
See my comment above asking for clarification on what you really want. Hopefully this is it:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;
Found out that there's no bug there. Just add:
<base href="/" />
to your <head />
.
Try This one.
function containsSpecialCharacters(str){_x000D_
var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;_x000D_
return regex.test(str);_x000D_
}
_x000D_
example :0.0.1-SNAPSHOT
Just add xmlns:tools="http://schemas.android.com/tools"
to your manifest tag, and then you need to add tools:replace="android:icon"
before android:icon="@mipmap/ic_launcher"
.
On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:
html {
margin: 0px;
height: 100%;
width: 100%;
}
body {
margin: 0px;
min-height: 100%;
width: 100%;
}
height
for the html
and min-height
for the body
.
In your example number
is a primitive, so will be stored as a value.
If you want to use a reference then you should use one of the wrapper types (e.g. Integer
)
ESP
is the current stack pointer, which will change any time a word or address is pushed or popped onto/off off the stack. EBP
is a more convenient way for the compiler to keep track of a function's parameters and local variables than using the ESP
directly.
Generally (and this may vary from compiler to compiler), all of the arguments to a function being called are pushed onto the stack by the calling function (usually in the reverse order that they're declared in the function prototype, but this varies). Then the function is called, which pushes the return address (EIP
) onto the stack.
Upon entry to the function, the old EBP
value is pushed onto the stack and EBP
is set to the value of ESP
. Then the ESP
is decremented (because the stack grows downward in memory) to allocate space for the function's local variables and temporaries. From that point on, during the execution of the function, the arguments to the function are located on the stack at positive offsets from EBP
(because they were pushed prior to the function call), and the local variables are located at negative offsets from EBP
(because they were allocated on the stack after the function entry). That's why the EBP
is called the Frame Pointer, because it points to the center of the function call frame.
Upon exit, all the function has to do is set ESP
to the value of EBP
(which deallocates the local variables from the stack, and exposes the entry EBP
on the top of the stack), then pop the old EBP
value from the stack, and then the function returns (popping the return address into EIP
).
Upon returning back to the calling function, it can then increment ESP
in order to remove the function arguments it pushed onto the stack just prior to calling the other function. At this point, the stack is back in the same state it was in prior to invoking the called function.
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script? The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();
select * from table where column_date > now()- INTERVAL '6 hours';
add method container css in your script like this :
$("#your_select_id").select2({
containerCss : {"display":"block"}
});
it will set your select's width same as width your div.
dup2( STDIN_FILENO, newfd )
And read:
char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
perror( "dup2( )" );
exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
printf( "<%s>", reading );
memset( reading, '\0', 1025 );
}
if( r_control < 0 )
perror( "read( )" );
close( fdin );
But, I think that fcntl
can be a better solution
echo "salut" | code
I found nice document on MSDN for it.
How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)
There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.
the 2.0/3.0 version is:
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
My tests over this method give:
Invalid: @majjf.com
Invalid: A@b@[email protected]
Invalid: Abc.example.com
Valid: [email protected]
Valid: [email protected]
Invalid: js*@proseware.com
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: [email protected]
Invalid: [email protected]
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: [email protected]
Invalid: -------
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Valid: j_9@[129.126.118.1]
Valid: [email protected]
Invalid: js#[email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
You can use:
array_search()
in_array()
array_flip()
and array_key_exists()
If your background image is a vertically aligned sprite sheet, you can horizontally center each sprite like this:
#doit {
background-image: url('images/pic.png');
background-repeat: none;
background-position: 50% [y position of sprite];
}
If your background image is a horizontally aligned sprite sheet, you can vertically center each sprite like this:
#doit {
background-image: url('images/pic.png');
background-repeat: none;
background-position: [x position of sprite] 50%;
}
If your sprite sheet is compact, or you are not trying to center your background image in one of the aforementioned scenarios, these solutions do not apply.
You'll have to jailbreak your device.
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
function getTime(offset)
{
var d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
//nd = 3600000 + nd;
utc = new Date(utc);
// return time as a string
$("#local").html(nd.toLocaleString());
$("#utc").html(utc.toLocaleString());
}
You can overlay a big, semi-transparent <div>
that takes all the clicks. Just append a new <div>
to <body>
with this style:
.overlay {
background-color: rgba(1, 1, 1, 0.7);
bottom: 0;
left: 0;
position: fixed;
right: 0;
top: 0;
}
Just replace:
return d.age - d1.age;
By:
return ((Integer)d.age).compareTo(d1.age);
Or invert to reverse the list:
return ((Integer)d1.age).compareTo(d.age);
EDIT:
Fixed the "memory problem".
Indeed, the better solution is change the age
field in the Dog
class to Integer
, because there many benefits, like the null
possibility...
I tried everything to fix this issue on my Mac. I think the issue started when I had already downloaded npm from Node.js and then reinstalled it with Homebrew while following along with a Team Treehouse video.
From https://docs.npmjs.com/misc/removing-npm
sudo npm uninstall npm -g
sudo make uninstall
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm*
From How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
In the end, the only thing that worked for me was to clone down the npm-reinstall repo from GitHub that completely removed everything related to npm on my Mac.
https://github.com/brock/node-reinstall
I then had to reinstall node and npm from Node.js.
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
Converting a range to a table as described in this answer:
Sub CreateTable() ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _ "Table1" 'No go in 2003 ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2" End Sub
Can you guys please check this out i think it is awesome and easy to understand.
i = 0
First_Value = 0
Second_Value = 1
while(i < Number):
if(i <= 1):
Next = i
else:
Next = First_Value + Second_Value
First_Value = Second_Value
Second_Value = Next
print(Next)
i = i + 1
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
I would suggest using originalUrl instead of URL:
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
See the description of originalUrl here: http://expressjs.com/api.html#req.originalUrl
In our system, we do something like this, so originalUrl is important to us:
foo = express();
express().use('/foo', foo);
foo.use(require('/foo/blah_controller'));
blah_controller looks like this:
controller = express();
module.exports = controller;
controller.get('/bar/:barparam', function(req, res) { /* handler code */ });
So our URLs have the format:
www.example.com/foo/bar/:barparam
Hence, we need req.originalUrl in the bar controller get handler.