TL;DR: Set CURLOPT_PROXYTYPE
to use CURLPROXY_SOCKS5_HOSTNAME
if you have a modern PHP, the value 7
otherwise, and/or correct the CURLOPT_PROXY
value.
As you correctly deduced, you cannot resolve .onion
domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.
Using CURLPROXY_SOCKS5
will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion
address unless it, too, is specifically forwarding such queries to Tor.
Instead of CURLPROXY_SOCKS5
, you must use CURLPROXY_SOCKS5_HOSTNAME
. Alternatively, you can also use CURLPROXY_SOCKS4A
, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion
domain.
There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:
Here is the correct code in full, with comments to indicate the changes.
<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($curl_error);
You can also omit setting CURLOPT_PROXYTYPE
entirely by changing the CURLOPT_PROXY
value to include the socks5h://
prefix:
// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');
There are no standards for REST other than HTTP. There are established REST services out there. I suggest you take a peek at them and get a feel for how they work.
For example, we borrowed a lot of ideas from Amazon's S3 REST service when developing our own. But we opted not to use the more advanced security model based on request signatures. The simpler approach is HTTP Basic auth over SSL. You have to decide what works best in your situation.
Also, I highly recommend the book RESTful Web Services from O'reilly. It explains the core concepts and does provide some best practices. You can generally take the model they provide and map it to your own application.
I don't think it's a good idea to caculate yourself.
If you just want a pretty output, just covert it into str
with str()
function or directly print()
it.
And if there's further usage of the hours and minutes, you can parse it to datetime
object use datetime.strptime()
(and extract the time part with datetime.time()
mehtod), for example:
import datetime
delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()
You can assign int
to char
directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
lambda
is an anonymous function, it is equivalent to:
def func(p):
return p.totalScore
Now max
becomes:
max(players, key=func)
But as def
statements are compound statements they can't be used where an expression is required, that's why sometimes lambda
's are used.
Note that lambda
is equivalent to what you'd put in a return statement of a def
. Thus, you can't use statements inside a lambda
, only expressions are allowed.
What does max
do?
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
So, it simply returns the object that is the largest.
How does key
work?
By default in Python 2 key
compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).
To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key
argument.
Example 1:
A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.
>>> lis = ['1', '100', '111', '2']
Here max
compares the items using their original values (strings are compared lexicographically so you'd get '2'
as output) :
>>> max(lis)
'2'
To compare the items by their integer value use key
with a simple lambda
:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
Example 2: Applying max
to a list of tuples.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
By default max
will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda
:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
List with mixed items:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
But this works, as we are comparing integer version of each object:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'
You can use a loop to do it. Here's an example using a with_items
loop:
- name: Set some kernel parameters
lineinfile:
dest: /etc/sysctl.conf
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
with_items:
- { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' }
- { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' }
- { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }
Based on multiple comments from stackoverflow, scikit-learn documentation and some other, I made a python package to plot ROC curve (and other metric) in a really simple way.
To install package : pip install plot-metric
(more info at the end of post)
To plot a ROC Curve (example come from the documentation) :
Let's load a simple dataset and make a train & test set :
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_classes=2, weights=[1,1], random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=2)
Train a classifier and predict test set :
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=50, random_state=23)
model = clf.fit(X_train, y_train)
# Use predict_proba to predict probability of the class
y_pred = clf.predict_proba(X_test)[:,1]
You can now use plot_metric to plot ROC Curve :
from plot_metric.functions import BinaryClassification
# Visualisation with plot_metric
bc = BinaryClassification(y_test, y_pred, labels=["Class 1", "Class 2"])
# Figures
plt.figure(figsize=(5,5))
bc.plot_roc_curve()
plt.show()
You can find more example of on the github and documentation of the package:
git log --pretty=oneline tagA...tagB
(i.e. three dots)
If you just wanted commits reachable from tagB but not tagA:
git log --pretty=oneline tagA..tagB
(i.e. two dots)
or
git log --pretty=oneline ^tagA tagB
Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:
conda install pyqt=4
This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example
conda install pyqt=4.11
would install the latest (or last) release of version 4.11.
Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.
All that being said, I can certainly see reasonable cases that none of those points really matter.
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
...you can (ab)use list comprehension scoping changes and do it in a single expression:
is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)
I think that it's because the locale is hardcoded into the DatePipe
. See this link:
And there is no way to update this locale by configuration right now.
baos.toString(StandardCharsets.UTF_8);
Converts the buffer's contents into a string by decoding the bytes using the named charset.
Are u using this datepicker http://jqueryui.com/demos/datepicker/ ? if yes there are options to set the default Date.If you didn't change anything , by default it will show the current date.
any way this will gives current date
$( ".selector" ).datepicker({ defaultDate: new Date() });
Assaf's response of
Depends on how much money you got...
sounds flippant, but actually it's pertinant.
Only today we had an issue where a record failed to be inserted into our Rate table, because one of the columns (GrossRate) is set to Decimal (11,4), and our Product department just got a contract for rooms in some amazing resort in Bora Bora, that sell for several million Pacific Francs per night... something that was never anticpated when the database schema was designed 10 years ago.
Another OOP method for DateTime with setting the exact hour:
$yesterday = new DateTime("yesterday 09:00:59", new DateTimeZone('Europe/London'));
echo $yesterday->format('Y-m-d H:i:s') . "\n";
I checked in macOS Sierra, the homebrew installed MySql 5.7.12
The support files are located at
/usr/local/opt/mysql/support-files
Just copy my-default.cnf
as /etc/my.cnf
or /etc/mysql/my.cnf
and the configuration will be picked up on restart.
I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.
As everyone else has mentioned, the first task is to add the certificate to the Trusted Root Authority.
There is a custom exe (selfssl.exe) which will create a certificate and allow you to specify the Issued to: value (the URL). This means Internet explorer will validate the issued to url with the custom intranet url.
Make sure you restart Internet Explorer to refresh changes.
I have used both Crypto
and PyCryptodomex
library and it is blazing fast...
import base64
import hashlib
from Cryptodome.Cipher import AES as domeAES
from Cryptodome.Random import get_random_bytes
from Crypto import Random
from Crypto.Cipher import AES as cryptoAES
BLOCK_SIZE = AES.block_size
key = "my_secret_key".encode()
__key__ = hashlib.sha256(key).digest()
print(__key__)
def encrypt(raw):
BS = cryptoAES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
raw = base64.b64encode(pad(raw).encode('utf8'))
iv = get_random_bytes(cryptoAES.block_size)
cipher = cryptoAES.new(key= __key__, mode= cryptoAES.MODE_CFB,iv= iv)
a= base64.b64encode(iv + cipher.encrypt(raw))
IV = Random.new().read(BLOCK_SIZE)
aes = domeAES.new(__key__, domeAES.MODE_CFB, IV)
b = base64.b64encode(IV + aes.encrypt(a))
return b
def decrypt(enc):
passphrase = __key__
encrypted = base64.b64decode(enc)
IV = encrypted[:BLOCK_SIZE]
aes = domeAES.new(passphrase, domeAES.MODE_CFB, IV)
enc = aes.decrypt(encrypted[BLOCK_SIZE:])
unpad = lambda s: s[:-ord(s[-1:])]
enc = base64.b64decode(enc)
iv = enc[:cryptoAES.block_size]
cipher = cryptoAES.new(__key__, cryptoAES.MODE_CFB, iv)
b= unpad(base64.b64decode(cipher.decrypt(enc[cryptoAES.block_size:])).decode('utf8'))
return b
encrypted_data =encrypt("Hi Steven!!!!!")
print(encrypted_data)
print("=======")
decrypted_data = decrypt(encrypted_data)
print(decrypted_data)
try this query below:
Insert into tab1 (tab1.column1,tab1.column2)
select tab2.column1, 'hard coded value'
from tab2
where tab2.column='value';
You can do it with a simple css/jq workaround: Create a fake button which triggers the browse button that is hidden.
HTML
<input type="file"/>
<button>Open</button>
CSS
input { display: none }
jQuery
$( 'button' ).click( function(e) {
e.preventDefault(); // prevents submitting
$( 'input' ).trigger( 'click' );
} );
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
it works:
type HtmlEvent = React.ChangeEvent<HTMLSelectElement>
const onChange: React.EventHandler<HtmlEvent> =
(event: HtmlEvent) => {
console.log(event.target.value)
}
Your code works as is for me. I'm verifying this by using netcat on Linux.
Using netcat, I can do nc -ul 127.0.0.1 5005
which will listen for packets at:
That being said, here's the output that I see when I run your script, while having netcat running.
[9:34am][wlynch@watermelon ~] nc -ul 127.0.0.1 5005
Hello, World!
For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:
var x = listOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToLookup(customObject => customObject);
Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.
You can also use this script to figure out more info:
EXEC sp_server_info
The result will be something like that:
attribute_id | attribute_name | attribute_value
-------------|-----------------------|-----------------------------------
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 2012 - 11.0.6020.0
10 | OWNER_TERM | owner
11 | TABLE_TERM | table
12 | MAX_OWNER_NAME_LENGTH | 128
13 | TABLE_LENGTH | 128
14 | MAX_QUAL_LENGTH | 128
15 | COLUMN_LENGTH | 128
16 | IDENTIFIER_CASE | MIXED
? ? ?
? ? ?
? ? ?
The equivalent in javascript is:
var text = `
This
Is
A
Multiline
String
`;
Here's the specification. See browser support at the bottom of this page. Here are some examples too.
This kind of JOIN
is not optimizable to a HASH JOIN
or a MERGE JOIN
.
It can be expressed as a concatenation of two resultsets:
SELECT *
FROM maintable m
JOIN othertable o
ON o.parentId = m.id
UNION
SELECT *
FROM maintable m
JOIN othertable o
ON o.id = m.parentId
, each of them being an equijoin, however, SQL Server
's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).
This worked for me:
The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with
conda install -c anaconda pandas
Unfortunately I do not know how to help with Eclipse.
System.IO.File.GetLastWriteTime is what you need.
In my case, this is working perfectly.. I have added below two line codes inside manifest file
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
Credit goes to this answer.
SSLSHopper has some pretty thorough articles about moving between different servers.
http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html
Just pick the relevant link at bottom of this page.
Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.
Because the method erase in vector return the next iterator of the passed iterator.
I will give example of how to remove element in vector when iterating.
void test_del_vector(){
std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
//method 1
for(auto it = vecInt.begin();it != vecInt.end();){
if(*it % 2){// remove all the odds
it = vecInt.erase(it); // note it will = next(it) after erase
} else{
++it;
}
}
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
// recreate vecInt, and use method 2
vecInt = {0, 1, 2, 3, 4, 5};
//method 2
for(auto it=std::begin(vecInt);it!=std::end(vecInt);){
if (*it % 2){
it = vecInt.erase(it);
}else{
++it;
}
}
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
// recreate vecInt, and use method 3
vecInt = {0, 1, 2, 3, 4, 5};
//method 3
vecInt.erase(std::remove_if(vecInt.begin(), vecInt.end(),
[](const int a){return a % 2;}),
vecInt.end());
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
}
output aw below:
024
024
024
A more generate method:
template<class Container, class F>
void erase_where(Container& c, F&& f)
{
c.erase(std::remove_if(c.begin(), c.end(),std::forward<F>(f)),
c.end());
}
void test_del_vector(){
std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
//method 4
auto is_odd = [](int x){return x % 2;};
erase_where(vecInt, is_odd);
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
}
If you're happy to require 'active_support/core_ext'
, then you can use
DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
Just to explain what others are saying (it took me some time to understand) is that, simply put, when you see this error, it means you already have a container and what you have to do is run it. While intuitively docker run
is supposed to run it, it doesn't. The command docker run
is used to only START a container for the very first time. To run an existing container what you need is docker start $container-name
. So much for asking developers to create meaningful/intuitive commands.
After little investigation I concluded the followings: You have 2 options:
go with transformations. Very usefull package for this: https://bundletransformer.codeplex.com/ you need following transformation for every problematic bundle:
BundleResolver.Current = new CustomBundleResolver();
var cssTransformer = new StyleTransformer();
standardCssBundle.Transforms.Add(cssTransformer);
bundles.Add(standardCssBundle);
Advantages: of this solution, you can name your bundle whatever you want => you can combine css files into one bundle from different directories. Disadvantages: You need to transform every problematic bundle
The ExtJS javascript library has a great class called Ext.util.TextMetrics that "provides precise pixel measurements for blocks of text so that you can determine exactly how high and wide, in pixels, a given block of text will be". You can either use it directly or view its source to code to see how this is done.
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
I note that the question is simply, "Is there any other way to break all of the loops?" I don't see any qualification but that it not be goto
, in particular the OP didn't ask for a good way. So, how about we longjmp
out of the inner loop? :-)
#include <stdio.h>
#include <setjmp.h>
int main(int argc, char* argv[]) {
int counter = 0;
jmp_buf look_ma_no_goto;
if (!setjmp(look_ma_no_goto)) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (i == 500 && j == 500) {
longjmp(look_ma_no_goto, 1);
}
counter++;
}
}
}
printf("counter=%d\n", counter);
}
The setjmp
function returns twice. The first time, it returns 0 and the program executes the nested for loops. Then when the both i
and j
are 500, it executes longjmp
, which causes setjmp
to return again with the value 1, skipping over the loop.
Not only will longjmp
get you out of nested loops, it works with nested functions too!
See answer here: How to control web page caching, across all browsers?
The list is just examples of different techniques, it's not for direct insertion. If copied, the second would overwrite the first and the fourth would overwrite the third because of the http-equiv declarations AND fail with the W3C validator. At most, one could have one of each http-equiv declarations; pragma, cache-control and expires. These are completely outdated when using modern up to date browsers. After IE9 anyway. Chrome and Firefox specifically does not work with these as you would expect, if at all.
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
Caching headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
The following command worked for me. Docker file was placed in my-app-master folder.
docker build -f my-app-master/Dockerfile -t my-app-master .
You can use the XML Instance Generator which is part of the Sun/Oracle Multi-Schema Validator.
It's README.txt states:
Sun XML Generator is a Java tool to generate various XML instances from several kinds of schemas. It supports DTD, RELAX Namespace, RELAX Core, TREX, and a subset of W3C XML Schema Part 1. [...]
This is a command-line tool that can generate both valid and invalid instances from schemas. It can be used for generating test cases for XML applications that need to conform to a particular schema.
Download and unpack xmlgen.zip
from the msv download page and run the following command to get detailed usage instructions:
java -jar xmlgen.jar -help
The tool appears to be released under a BSD license; the source code is accessible from here
What about
lstCountry.Items[lstCountry.SelectedIndex].Text;
If your app is launched from device, not IDE, you can do later in menu: Run
- Attach Debugger to Android Process
.
This can be useful when debugging notifications on closed application.
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.
Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.
Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.
For future Google'rs that use Laravel 5, you can now also use it with includes,
@include('views.otherView', ['variable' => 1])
The lstrip()
method will remove leading whitespaces, newline and tab characters on a string beginning:
>>> ' hello world!'.lstrip()
'hello world!'
Edit
As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ')
should be used:
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
Related question:
The most important reason of a String being made immutable in Java is Security consideration. Next would be Caching.
I believe other reasons given here, such as efficiency, concurrency, design and string pool follows from the fact that String in made immutable. For eg. String Pool could be created because String was immutable and not the other way around.
Check Gosling interview transcript here
From a strategic point of view, they tend to more often be trouble free. And there are usually things you can do with immutables that you can't do with mutable things, such as cache the result. If you pass a string to a file open method, or if you pass a string to a constructor for a label in a user interface, in some APIs (like in lots of the Windows APIs) you pass in an array of characters. The receiver of that object really has to copy it, because they don't know anything about the storage lifetime of it. And they don't know what's happening to the object, whether it is being changed under their feet.
You end up getting almost forced to replicate the object because you don't know whether or not you get to own it. And one of the nice things about immutable objects is that the answer is, "Yeah, of course you do." Because the question of ownership, who has the right to change it, doesn't exist.
One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it's doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you're in. But Strings are immutable, so that kind of attack doesn't work. That precise example is what really demanded that Strings be immutable
This is how you should initialize the NSString
:
Swift 2.X or older
let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)
Swift 3 or newer:
let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)
This doc explains the syntax.
Setting up a Library Project
A library project is a standard Android project, so you can create a new one in the same way as you would a new application project.
When you are creating the library project, you can select any application name, package, and set other fields as needed, as shown in figure 1.
Next, set the project's properties to indicate that it is a library project:
In the Package Explorer, right-click the library project and select Properties. In the Properties window, select the "Android" properties group at left and locate the Library properties at right. Select the "is Library" checkbox and click Apply. Click OK to close the Properties window. The new project is now marked as a library project. You can begin moving source code and resources into it, as described in the sections below.
I upgraded to Xcode 8, and iOS 10, but I had the problem.
I fixed it by going to project general tab, signing section.
Click "Enable signing....."
That is it.
Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.
Sort by picture and then by activity:
SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;
There are 2 Reasons why we have to Normalize Input Features before Feeding them to Neural Network:
Reason 1: If a Feature
in the Dataset
is big in scale compared to others then this big scaled feature becomes dominating and as a result of that, Predictions of the Neural Network will not be Accurate.
Example: In case of Employee Data, if we consider Age and Salary, Age will be a Two Digit Number while Salary can be 7 or 8 Digit (1 Million, etc..). In that Case, Salary will Dominate the Prediction of the Neural Network. But if we Normalize those Features, Values of both the Features will lie in the Range from (0 to 1).
Reason 2: Front Propagation of Neural Networks involves the Dot Product of Weights with Input Features. So, if the Values are very high (for Image and Non-Image Data), Calculation of Output takes a lot of Computation Time as well as Memory. Same is the case during Back Propagation. Consequently, Model Converges slowly, if the Inputs are not Normalized.
Example: If we perform Image Classification, Size of Image will be very huge, as the Value of each Pixel ranges from 0 to 255. Normalization in this case is very important.
Mentioned below are the instances where Normalization is very important:
I would simply recommend:
/* In your CSS code: */
pre
{
display:inline;
}
<!-- And then, in your HTML code: -->
<pre> This text comes after four spaces.</pre>
<span> Continue the line with other element without braking </span>
Azure Data Studio with Postgres addin is the tool of choice to manage postgres databases for me. Check it out. https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-postgres?view=sql-server-ver15
I've had lot of security issues after upgrading to OS X v10.9 (Mavericks):
trustAnchors
parameter must be non-emptyI applied this Java update and it fixed all my issues: http://support.apple.com/kb/DL1572?viewlocale=en_US
It can be achieved using RelativeLayout
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/icon"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
If you're searching for the location of the currently executed script, you can use sys.argv[0]
to get the full path.
You can use the old <xmp>
tag. I don't know about browser support, but it should still work.
<HTML>
your code/tables
<xmp>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<country>Columbia</country>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
</xmp>
Output:
your code/tables
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<country>Columbia</country>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
A pop-up is a child of the parent window, but it is not a child of the parent DOCUMENT. It is its own independent browser window and is not contained by the parent.
Use an absolutely-positioned DIV and a translucent overlay instead.
EDIT - example
You need jQuery for this:
<style>
html, body {
height:100%
}
#overlay {
position:absolute;
z-index:10;
width:100%;
height:100%;
top:0;
left:0;
background-color:#f00;
filter:alpha(opacity=10);
-moz-opacity:0.1;
opacity:0.1;
cursor:pointer;
}
.dialog {
position:absolute;
border:2px solid #3366CC;
width:250px;
height:120px;
background-color:#ffffff;
z-index:12;
}
</style>
<script type="text/javascript">
$(document).ready(function() { init() })
function init() {
$('#overlay').click(function() { closeDialog(); })
}
function openDialog(element) {
//this is the general dialog handler.
//pass the element name and this will copy
//the contents of the element to the dialog box
$('#overlay').css('height', $(document.body).height() + 'px')
$('#overlay').show()
$('#dialog').html($(element).html())
centerMe('#dialog')
$('#dialog').show();
}
function closeDialog() {
$('#overlay').hide();
$('#dialog').hide().html('');
}
function centerMe(element) {
//pass element name to be centered on screen
var pWidth = $(window).width();
var pTop = $(window).scrollTop()
var eWidth = $(element).width()
var height = $(element).height()
$(element).css('top', '130px')
//$(element).css('top',pTop+100+'px')
$(element).css('left', parseInt((pWidth / 2) - (eWidth / 2)) + 'px')
}
</script>
<a href="javascript:;//close me" onclick="openDialog($('#content'))">show dialog A</a>
<a href="javascript:;//close me" onclick="openDialog($('#contentB'))">show dialog B</a>
<div id="dialog" class="dialog" style="display:none"></div>
<div id="overlay" style="display:none"></div>
<div id="content" style="display:none">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisl felis, placerat in sollicitudin quis, hendrerit vitae diam. Nunc ornare iaculis urna.
</div>
<div id="contentB" style="display:none">
Moooo mooo moo moo moo!!!
</div>
Removing all focus styles is bad for accessibility and keyboard users in general. But outlines are ugly and providing a custom focussed style for every single interactive element can be a real pain.
So the best compromise I've found is to show the outline styles only when we detect that the user is using the keyboard to navigate. Basically, if the user presses TAB, we show the outlines and if he uses the mouse, we hide them.
It does not stop you from writing custom focus styles for some elements but at least it provides a good default.
This is how I do it:
// detect keyboard users_x000D_
_x000D_
const keyboardUserCssClass = "keyboardUser";_x000D_
_x000D_
function setIsKeyboardUser(isKeyboard) {_x000D_
const { body } = document;_x000D_
if (isKeyboard) {_x000D_
body.classList.contains(keyboardUserCssClass) || body.classList.add(keyboardUserCssClass);_x000D_
} else {_x000D_
body.classList.remove(keyboardUserCssClass);_x000D_
}_x000D_
}_x000D_
_x000D_
// This is a quick hack to activate focus styles only when the user is_x000D_
// navigating with TAB key. This is the best compromise we've found to_x000D_
// keep nice design without sacrifying accessibility._x000D_
document.addEventListener("keydown", e => {_x000D_
if (e.key === "Tab") {_x000D_
setIsKeyboardUser(true);_x000D_
}_x000D_
});_x000D_
document.addEventListener("click", e => {_x000D_
// Pressing ENTER on buttons triggers a click event with coordinates to 0_x000D_
setIsKeyboardUser(!e.screenX && !e.screenY);_x000D_
});_x000D_
_x000D_
document.addEventListener("mousedown", e => {_x000D_
setIsKeyboardUser(false);_x000D_
});
_x000D_
body:not(.keyboardUser) *:focus {_x000D_
outline: none;_x000D_
}
_x000D_
<p>By default, you'll see no outline. But press TAB key and you'll see focussed element</p>_x000D_
<button>This is a button</button>_x000D_
<a href="#">This is anchor link</a>_x000D_
<input type="checkbox" />_x000D_
<textarea>textarea</textarea>_x000D_
<select/>
_x000D_
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
It means parent/child
example:
html>body
that's saying that body is a child of html
Check out: Selectors
You can use custom camera with thumbnail image. You can look my project.
You can add simple white space with quotes sign: {" "}
Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):
`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.
Add
clear:both;
To the css of the parent div, or add a div at the bottom of the parent div that does clear:both;
That is the correct answer, because overflow:auto; may work for simple web layouts, but will mess with elements that start using things like negative margin, etc
Code example of ItemListener
implementation
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
Now we will get only selected item.
Then just add listener to your JComboBox
addItemListener(new ItemChangeListener());
You're looking for the /Y
switch.
It seems daft, but I think when you use the same bind variable twice you have to set it twice:
cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");
Certainly that's true with Native Dynamic SQL in PL/SQL:
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING';
4 end;
5 /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING', 'KING';
4 end;
5 /
PL/SQL procedure successfully completed.
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
Open the Servers view -> double click tomcat -> drop down the Timeouts section
There you can increase the startup time for each particular server.
On Linux use below to test (it would replace the whitespaces with comma)
sed 's/\s/,/g' /tmp/test.txt | head
later you can take the output into the file using below command:
sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt
PS: test is the file which you want to use
I solved this issue by using
Service.setSslSecurityProtocol(SSLSecurityProtocol.TLSv1_2);
You can use the excellent jquery-Json plugin:
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
The json.load() method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
json.loads() method, which is used for string arguments only.
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>
person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print(type(person_dict))
# Output : <type 'dict'>
Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like ?
.
You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing 'normalization' defined for unicode), but those methods are far from complete.
Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII.
Java 6 +
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
private static final FileFilter FOLDER_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
};
private static final FileFilter FILE_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
};
private static void compress(File file, ZipOutputStream outputStream, String path) throws IOException {
if (file.isDirectory()) {
File[] subFiles = file.listFiles(FILE_FILTER);
if (subFiles != null) {
for (File subFile : subFiles) {
compress(subFile, outputStream, new File(path, subFile.getName()).getAbsolutePath());
}
}
File[] subDirs = file.listFiles(FOLDER_FILTER);
if (subDirs != null) {
for (File subDir : subDirs) {
compress(subDir, outputStream, new File(path, subDir.getName()).getAbsolutePath());
}
}
} else if (file.exists()) {
outputStream.putNextEntry(new ZipEntry(path));
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, len);
}
outputStream.closeEntry();
}
}
public static void compress(String dirPath, String zipFilePath) throws IOException {
File file = new File(dirPath);
final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
compress(file, outputStream, "/");
outputStream.close();
}
}
Step I: include the file and plugin
../jspdf.plugin.addimage.js
Step II: build PDF content var doc = new jsPDF();
doc.setFontSize(12);
doc.text(35, 25, "Welcome to JsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 386, 386);
Step III: display image in new window
doc.output('dataurlnewwindow');
Stepv IV: save data
var output = doc.output();
return btoa( output);
if you want to open all your .cpp
files with one command, and have the window split in as many tiles as opened files, you can use:
vim -o $(find name ".cpp")
if you want to include a template in the place you are, you can use:
:r ~/myHeaderTemplate
will import the file "myHeaderTemplate in the place the cursor was before starting the command.
you can conversely select visually some code and save it to a file
when you select visualy, after type ":" in order to enter a command, you'll see "'<,'>" appear after the ":"
'<,'>w ~/myfile $
^ if you add "~/myfile" to the command, the selected part of the file will be saved to myfile.
if you're editing a file an want to copy it :
:saveas newFileWithNewName
Update your setuptools, too.
pip install setuptools --upgrade
If that fails too, you could try with additional --force
flag.
I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/
function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' +
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr +
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */
Greets
Gee
I reduce the whole crap now to:
function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' +
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};
Didn't get it to work in ie as well... 2b continued...
Greets
Gee
Use this code fist of your code:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
This works for me.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
I had a similar problem, which led me here:
$ phpunit --version
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/profiler.so' - /usr/lib/php5/20131226/profiler.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
Unlike the above, installing the software did not resolve my problem because I already had it.
$ sudo apt-get install php5-uprofiler
Reading package lists... Done
Building dependency tree
Reading state information... Done
php5-uprofiler is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 52 not upgraded.
I found my solution via : Debian Bug report logs
$ sudo vim /etc/php5/mods-available/uprofiler.ini
I edited the ini file, changing extension=profiler.so to extension=uprofiler.so .... the result, happily:
$ phpunit --version
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
i.e. no more warning.
To set focus,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.Focus()
End Sub
Set the TabIndex by
Me.TextBox1.TabIndex = 0
Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.
Change
position: absolute;
To
position: fixed;
W3C specifications for position: absolute
and for position: fixed
.
I also had a similar problem
My problem was solved by doing the following:
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
If you only need to support certain modern browsers then you can now use:
navigator.languages
which returns an array of the user's language preferences in the order specified by the user.
As of now (Sep 2014) this works on: Chrome (v37), Firefox (v32) and Opera (v24)
But not on: IE (v11)
An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file
<FilesMatch "\.(inc)$">
Order deny,allow
Deny from all
</FilesMatch>
When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.
The right way is putting it in an header file, and include this header file whenever needed.
This is the solution I like more, because it makes the code highly modular. I would code your struct as:
#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
struct a
{
int i;
struct b
{
int j;
}
};
#endif
I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").
And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.
If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:
struct a ;
Will be enough, and it decreases coupling.
This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.
In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.
I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.
The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:
struct MyStruct ; /* Forward declaration */
struct MyStruct
{
/* etc. */
} ;
void doSomething(struct MyStruct * p) /* parameter */
{
struct MyStruct a ; /* variable */
/* etc */
}
While a typedef will enable you to write it without the struct keyword.
struct MyStructTag ; /* Forward declaration */
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
void doSomething(MyStruct * p) /* parameter */
{
MyStruct a ; /* variable */
/* etc */
}
It is important you still keep a name for the struct. Writing:
typedef struct
{
/* etc. */
} MyStruct ;
will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)
Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.
Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.
Indeed, the code above could well be written as:
typedef struct MyStruct
{
/* etc. */
} MyStruct ;
IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:
// C++ explicit declaration by the user
struct MyStruct
{
/* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;
Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.
Simply, you use ADB, as follows:
adb install <path to apk>
Also see the section Installing an Application in Android Debug Bridge.
private static List<File> sortByLastModified(String dirPath) {
List<File> files = listFilesRec(dirPath);
Collections.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
return Long.compare(o1.lastModified(), o2.lastModified());
}
});
return files;
}
<input type="text" name="whatever" id="funkystyling" />
Here's the CSS for the image on the left:
#funkystyling {
background: white url(/path/to/icon.png) left no-repeat;
padding-left: 17px;
}
And here's the CSS for the image on the right:
#funkystyling {
background: white url(/path/to/icon.png) right no-repeat;
padding-right: 17px;
}
It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add
the !
as a postfix to the variable name:
makes!: any[];
The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.
The Panel does have outer HTML tags but does have some cool extra properties.
BackImageUrl: Gets/Sets the background image's URL for the panel
HorizontalAlign: Gets/Sets the
horizontal alignment of the parent's
contents
There is a good article at startvbnet here.
I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.
Use libraries https://jar-download.com/maven-repository-class-search.php?search_box=org.apache.http.entity.mime Download the library and put it in your project
My problem was to display the record even if no or only one phone number exists (full address book). Therefore I used a LEFT JOIN which takes all records from the left, even if no corresponding exists on the right. For me this works in Microsoft Access SQL (they require the parenthesis!)
SELECT t.PhoneNumber1, t.PhoneNumber2, t.PhoneNumber3
t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2, t3.someOtherFieldForPhone3
FROM
(
(
Table1 AS t LEFT JOIN Table2 AS t3 ON t.PhoneNumber3 = t3.PhoneNumber
)
LEFT JOIN Table2 AS t2 ON t.PhoneNumber2 = t2.PhoneNumber
)
LEFT JOIN Table2 AS t1 ON t.PhoneNumber1 = t1.PhoneNumber;
As somebody else already said, your design is not very clear and Object Oriented.
The most obvious error is that in your design a Card knows about a Deck of Cards. The Deck should know about cards and instantiate objects in its constructor. For Example:
public class DeckOfCards {
private Card cards[];
public DeckOfCards() {
this.cards = new Card[52];
for (int i = 0; i < ; i++) {
Card card = new Card(...); //Instantiate a Card
this.cards[i] = card; //Adding card to the Deck
}
}
Afterwards, if you want you can also extend Deck in order to build different Deck of Cards (for example with more than 52 cards, Jolly etc.). For Example:
public class SpecialDeck extends DeckOfCards {
....
Another thing that I'd change is the use of String arrays to represent suits and ranks. Since Java 1.5, the language supports Enumeration, which are perfect for this kind of problems. For Example:
public enum Suits {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
With Enum you get some benefits, for example:
1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. For Example, you could write your Card's constructor as following:
public class Card {
private Suits suit;
private Ranks rank;
public Card(Suits suit, Ranks rank) {
this.suit = suit;
this.rank = rank;
}
This way you are sure to build consistent cards that accept only values ??of your enumeration.
2) You can use Enum in Java inside Switch statement like int or char primitive data type (here we have to say that since Java 1.7 switch statement is allowed also on String)
3) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.
4) You can iterate through Enum, this can be very helpful when instantiating Cards. For Example:
/* Creating all possible cards... */
for (Suits s : Suits.values()) {
for (Ranks r : Ranks.values()) {
Card c = new Card(s,r);
}
}
In order to not invent again the wheel, I'd also change the way you keep Cards from array to a Java Collection, this way you get a lot of powerful methods to work on your deck, but most important you can use the Java Collection's shuffle function to shuffle your Deck. For example:
private List<Card> cards = new ArrayList<Card>();
//Building the Deck...
//...
public void shuffle() {
Collections.shuffle(this.cards);
}
(for MAC)
I tried all these answers and, for some still unknown reason, none of them worked.
I had to "force feed" the GOPATH by setting the environment variable per every command that required it. For example:
sudo env GOPATH=$HOME/goWorkDirectory go build ...
Even glide
was giving me the GOPATH not set
error. Resolved it, again, by "force feeding":
I tried all these answers and, for some still unknown reason, none of them worked.
I had to "force feed" the GOPATH by setting the environment variable per every command that required it.
sudo env GOPATH=$HOME/goWorkDirectory glide install
Hope this helps someone.
impdp
exports the DDL of a dmp
backup to a file if you use the SQLFILE
parameter. For example, put this into a text file
impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
Then check ddl_dump.txt
for the tablespaces, users, and schemas in the backup.
According to the documentation, this does not actually modify the database:
The SQL is not actually executed, and the target system remains unchanged.
So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.
Intuitively (and wrongly), most people assume that it looks something like this:
Local Computer | Remote Computer
--------------------------------
<local_ip>:80 | <foreign_ip>:80
^^ not actually what happens, but this is the conceptual model a lot of people have in mind.
This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.
Three things must be understood:
1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.
2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.
3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.
So, this is really what gets created when a client connects to a server:
Local Computer | Remote Computer | Role
-----------------------------------------------------------
0.0.0.0:80 | <none> | LISTENING
127.0.0.1:80 | 10.1.2.3:<random_port> | ESTABLISHED
First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).
netstat -atnp | grep -i ":500 "
As expected, the output is blank. Now let's start a web server:
sudo python3 -m http.server 500
Now, here is the output of running netstat again:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.
So now, let's connect a user to our machine:
quicknet -m tcp -t localhost:500 -p Test payload.
This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:54240 ESTABLISHED -
If you connect with another client and do netstat again, you will see the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:26813 ESTABLISHED -
... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.
List<? extends HasWord>
accepts any concrete classes that extends HasWord. If you have the following classes...
public class A extends HasWord { .. }
public class B extends HasWord { .. }
public class C { .. }
public class D extends SomeOtherWord { .. }
... the wordList
can ONLY contain a list of either As or Bs or mixture of both because both classes extend the same parent or null
(which fails instanceof checks for HasWorld
).
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
One of the weird behaviour and spec in Javascript is the typeof Array is Object
.
You can check if the variable is an array in couple of ways:
var isArr = data instanceof Array;
var isArr = Array.isArray(data);
But the most reliable way is:
isArr = Object.prototype.toString.call(data) == '[object Array]';
Since you tagged your question with jQuery, you can use jQuery isArray
function:
var isArr = $.isArray(data);
You can throw your own custom errors by extending the Exception class.
class CustomException : Exception {
[string] $additionalData
CustomException($Message, $additionalData) : base($Message) {
$this.additionalData = $additionalData
}
}
try {
throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
# NOTE: To access your custom exception you must use $_.Exception
Write-Output $_.Exception.additionalData
# This will produce the error message: Didn't catch it the second time
throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
Linux supports capabilities to support more fine-grained permissions than just "this application is run as root". One of those capabilities is CAP_NET_BIND_SERVICE
which is about binding to a privileged port (<1024).
Unfortunately I don't know how to exploit that to run an application as non-root while still giving it CAP_NET_BIND_SERVICE
(probably using setcap
, but there's bound to be an existing solution for this).
There is a ToObject method now.
var obj = jsonObject["date_joined"];
var result = obj.ToObject<DateTime>();
It also works with any complex type, and obey to JsonPropertyAttribute rules
var result = obj.ToObject<MyClass>();
public class MyClass
{
[JsonProperty("date_field")]
public DateTime MyDate {get;set;}
}
Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the printf()
-style functions.
Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:
char str[100];
float adc_read = 678.0123;
char *tmpSign = (adc_read < 0) ? "-" : "";
float tmpVal = (adc_read < 0) ? -adc_read : adc_read;
int tmpInt1 = tmpVal; // Get the integer (678).
float tmpFrac = tmpVal - tmpInt1; // Get fraction (0.0123).
int tmpInt2 = trunc(tmpFrac * 10000); // Turn into integer (123).
// Print as parts, note that you need 0-padding for fractional bit.
sprintf (str, "adc_read = %s%d.%04d\n", tmpSign, tmpInt1, tmpInt2);
You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented).
However, there are ways to handle this by further processing the fractional part, shifting it by four decimal digits each time (and using/subtracting the integer part) until you have the precision you desire.
Update:
One final point you mentioned that you were using avr-gcc
in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use %f
in your printf()
statements here.
As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.
However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.
In case that link ever disappears, what you have to do is ensure that your gcc command has "-Wl,-u,vfprintf -lprintf_flt -lm
". This translates to:
printf()
library for searching.Just to comment on the DOMAttrModified event listener browser support:
Cross-browser support
These events are not implemented consistently across different browsers, for example:
IE prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, DOMNodeInserted)
WebKit doesn't support DOMAttrModified (see webkit bug 8191 and the workaround)
"mutation name events", i.e. DOMElementNameChanged and DOMAttributeNameChanged are not supported in Firefox (as of version 11), and probably in other browsers as well.
Source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
This is the related github issue
This bug is related to the 2.0.0 version, you can solve it by simply upgrading to version 2.1.0.
You can run
npm i [email protected]
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
One of my clients was facing the same issue. Following steps are taken to fix this.
(1) Open Run.
(2) Type Services.msc
(3) Select ASP.NET State Service
(4) Right Click and Start it.
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
For Gradle
users, if you are using Eclipse or one of its offshoots(I am using STS 4.5.1.RELEASE
), all that you need to do is:
In build.gradle, you ONLY need these 2 "extra" instructions:
dependencies {
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
Right-click on your project > Gradle > Refresh Gradle Project. The lombok-"version".jar
will appear inside your project's Project and External Dependencies
Right-click on that lombok-"version".jar
> Run As > Java Application (similar to double-clicking on the actual jar or running java -jar lombok-"version".jar
on the command line.)
A GUI will appear, follow the instructions and one of the thing it does is to copy lombok.jar
to your IDE's root.
The only other thing you will need to do(outside of the GUI) is to add that lombok.jar
to your project build path
That's it!
Firstly, I don't think spaces for an id is valid.
So i'd change the id to not include spaces.
<label year="2010" month="6" id="currentMonth"> June 2010</label>
then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)
var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();
Prior to HTML5, input type="text" simply means a field to insert free text, regardless of what you want it be. that is the job of validations you would have to do in order to guarantee the user enters a valid number
If you're using HTML5, you can use the new input types, one of which is number that automatically validates the text input, and forces it to be a number
keep in mind though, that if you're building a server side app (php for example) you will still have to validate the input on that side (make sure it is really a number) since it's pretty easy to hack the html and change the input type, removing the browser validation
Use that code.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Your URL",
data: "{}",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
You can create it easily:
$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}
Always open in binary mode, in this case
file = open("Fruits.obj",'rb')
I had a similar error and fixed it by following steps: 1. Under Servers project (which gets created itself when you add Apache Tomcat Server in Eclipse), open server.xml 2. Comment out the line
<Context docBase=... />
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
If your data is always going to be repeatable, perhaps don't worry about it. However, you can unroll it too - this is especially useful if the incoming data could be large (for example, reading from disk/network):
if(objects == null) throw new ArgumentException();
using(var iter = objects.GetEnumerator()) {
if(!iter.MoveNext()) throw new ArgumentException();
var firstObject = iter.Current;
var list = DoSomeThing(firstObject);
while(iter.MoveNext()) {
list.Add(DoSomeThingElse(iter.Current));
}
return list;
}
Note I changed the semantic of DoSomethingElse a bit, but this is mainly to show unrolled usage. You could re-wrap the iterator, for example. You could make it an iterator block too, which could be nice; then there is no list
- and you would yield return
the items as you get them, rather than add to a list to be returned.
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
I don't suppose this is a "trick question" . . . "?:" isn't an conditional, it is an operator.
So use recursion and the ?: operator to detect the when to stop?
int recurse(i)
{
printf("%d\n", i);
int unused = i-1000?recurse(i+1):0;
}
recurse(1);
Or along a similar perverted line of thinking . . . the second clause in an "&" condition is only executed if the first value is true. So recurse something like this:
i-1000 & recurse(i+1);
Perhaps the interviewer considers that an expression instead of a conditional.
The correct answer is already stated (just use SortedDictionary).
However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...
Dictionary<string, int> dupcheck = new Dictionary<string, int>();
...some code that fills in "dupcheck", then...
if (dupcheck.Count > 0) {
Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
var keys_sorted = dupcheck.Keys.ToList();
keys_sorted.Sort();
foreach (var k in keys_sorted) {
Console.WriteLine("{0} = {1}", k, dupcheck[k]);
}
}
Don't forget using System.Linq;
for this.
In events handler you can get id as follows
function show(btn) {_x000D_
console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image
For more Details check this
https://learning.getpostman.com/docs/postman/sending_api_requests/responses/
Even I faced the same issue with the encoding that occurs when you try to print it, read/write it or open it. As others mentioned above adding .encoding="utf-8" will help if you are trying to print it.
soup.encode("utf-8")
If you are trying to open scraped data and maybe write it into a file, then open the file with (......,encoding="utf-8")
with open(filename_csv , 'w', newline='',encoding="utf-8") as csv_file:
My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.
Modifications made in a called function are not in scope of the calling function when passing by value.
Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.
Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.
For Mac OS X Yosemite I was able to use the open command.
Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments]
Help: Open opens files from a shell.
By default, opens each file using the default application for that file.
If the file is in the form of a URL, the file will be opened as a URL.
Options:
-a Opens with the specified application.
-b Opens with the specified application bundle identifier.
-e Opens with TextEdit.
-t Opens with default text editor.
-f Reads input from standard input and opens with TextEdit.
-F --fresh Launches the app fresh, that is, without restoring windows. Saved persistent state is lost, excluding Untitled documents.
-R, --reveal Selects in the Finder instead of opening.
-W, --wait-apps Blocks until the used applications are closed (even if they were already running).
--args All remaining arguments are passed in argv to the application's main() function instead of opened.
-n, --new Open a new instance of the application even if one is already running.
-j, --hide Launches the app hidden.
-g, --background Does not bring the application to the foreground.
-h, --header Searches header file locations for headers matching the given filenames, and opens them.
This worked for me:
open eclipse.app --args clean
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/[email protected]">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
Use:
PRAGMA table_info(your_table_name)
If the resulting table is empty then your_table_name
doesn't exist.
Documentation:
PRAGMA schema.table_info(table-name);
This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.
The table named in the table_info pragma can also be a view.
Example output:
cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0
With flatMap
var requestStream = Rx.Observable.just('https://api.github.com/users');
var responseMetastream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
responseMetastream.subscribe(json => {console.log(json)})
Without flatMap
var requestStream = Rx.Observable.just('https://api.github.com/users');
var responseMetastream = requestStream
.map(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
responseMetastream.subscribe(jsonStream => {
jsonStream.subscribe(json => {console.log(json)})
})
I think that const
solves the problem for most people looking for this anwwer. If you really need an immutable constant, look into the other answers.
To keep everything organized I save all constants on a folder and then require the whole folder.
src/main.js file
const constants = require("./consts_folder");
src/consts_folder/index.js
const deal = require("./deal.js")
const note = require("./note.js")
module.exports = {
deal,
note
}
Ps. here the deal
and note
will be first level on the main.js
src/consts_folder/note.js
exports.obj = {
type: "object",
description: "I'm a note object"
}
Ps. obj
will be second level on the main.js
src/consts_folder/deal.js
exports.str = "I'm a deal string"
Ps. str
will be second level on the main.js
Final result on main.js file:
console.log(constants.deal);
Ouput:
{ deal: { str: 'I\'m a deal string' },
console.log(constants.note);
Ouput:
note: { obj: { type: 'object', description: 'I\'m a note object' } }
The FOR-LOOP generally works, but there are some issues. The FOR doesn't accept empty lines and lines with more than ~8190 are problematic. The expansion works only reliable, if the delayed expansion is disabled.
Detection of CR/LF versus single LF seems also a little bit complicated.
Also NUL characters are problematic, as a FOR-Loop immediatly cancels the reading.
Direct binary reading seems therefore nearly impossible.
The problem with empty lines can be solved with a trick. Prefix each line with a line number, using the findstr command, and after reading, remove the prefix.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo(!var!
ENDLOCAL
)
Toggling between enable and disabled delayed expansion is neccessary for the safe working with strings, like !
or ^^^xy!z
.
That's because the line set "var=%%a"
is only safe with DisabledDelayedExpansion, else exclamation marks are removed and the carets are used as (secondary) escape characters and they are removed too.
But using the variable var
is only safe with EnabledDelayedExpansion, as even a call %%var%%
will fail with content like "&"&
.
EDIT: Added set/p variant
There is a second way of reading a file with set /p
, the only disadvantages are that it is limited to ~1024 characters per line and it removes control characters at the line end.
But the advantage is, you didn't need the delayed toggling and it's easier to store values in variables
@echo off
setlocal EnableDelayedExpansion
set "file=%~1"
for /f "delims=" %%n in ('find /c /v "" %file%') do set "len=%%n"
set "len=!len:*: =!"
<%file% (
for /l %%l in (1 1 !len!) do (
set "line="
set /p "line="
echo(!line!
)
)
For reading it "binary" into a hex-representation
You could look at SO: converting a binary file to HEX representation using batch file
If you are going to be changing a String many times, then it is usually more efficient to use a StringBuilder (but measure your performance to find out):
String str = "The rain in Spain falls mainly on the plain";
StringBuilder sb = new StringBuilder(str);
// do your replacing in sb - although you'll find this trickier than simply using String
String newStr = sb.toString();
Every time you do a replace on a String, a new String object is created, because Strings are immutable. StringBuilder is mutable, that is, it can be changed as much as you want.
I could totally be missing something here, but this solution seems a lot simpler than many others proposed.
extension UIPageViewController {
func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
if let currentViewController = viewControllers?[0] {
if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
}
}
}
}
Just bind to the hidden
property
[hidden]="!myVar"
See also
issues
hidden
has some issues though because it can conflict with CSS for the display
property.
See how some
in Plunker example doesn't get hidden because it has a style
:host {display: block;}
set. (This might behave differently in other browsers - I tested with Chrome 50)
workaround
You can fix it by adding
[hidden] { display: none !important;}
To a global style in index.html
.
another pitfall
hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;
are the same as
hidden="true"
and will not show the element.
hidden="false"
will assign the string "false"
which is considered truthy.
Only the value false
or removing the attribute will actually make the element
visible.
Using {{}}
also converts the expression to a string and won't work as expected.
Only binding with []
will work as expected because this false
is assigned as false
instead of "false"
.
*ngIf
vs [hidden]
*ngIf
effectively removes its content from the DOM while [hidden]
modifies the display
property and only instructs the browser to not show the content but the DOM still contains it.
I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.
The xml file:
<RelativeLayout
android:id="@+id/header_main_page_clist1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:paddingBottom="10dp"
android:background="#ffffff" >
<ListView
android:id="@+id/lv_msglist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/divider_color"
android:dividerHeight="1dp" />
<TextView
android:id="@+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO MESSAGES AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
</RelativeLayout>
The textView ("@+id/emptyElement") is the placeholder for the empty listview.
Here is the code for java page:
lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));
Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.
Output:
Use str.join
:
>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
The above steps, though helpful, didnt work for me on Windows 8. I don't know the co-relation, but the below steps worked. Basically a change in the cacert.pem file. Hope this helps someone.
The gorand package has a UUID method that returns a Version 4 (randomly generated) UUID in its canonical string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") and it's RFC 4122 compliant.
It also uses the crypto/rand package to ensure the most cryptographically secure generation of UUIDs across all platforms supported by Go.
import "github.com/leonelquinteros/gorand"
func main() {
uuid, err := gorand.UUID()
if err != nil {
panic(err.Error())
}
println(uuid)
}
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp
Hope this helps
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
%20+ high cpu usage + no lag
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
%0.1 cpu usage + high lag
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
add this to your application :
@app.route('/logout')
def logout():
return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})
You can do so starting with Postgres 9.1:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
create function t1_ins_into_t2()
returns trigger
as $$
begin
insert into table2 (val) values (new.id);
return new;
end;
$$ language plpgsql;
create trigger t1_ins_into_t2
after insert on table1
for each row
execute procedure t1_ins_into_t2();
Hi i tried this it is working.
$("#change_align").css({"margin-top":"-39px","margin-right":"0px","margin-bottom":"0px","margin-left":"719px"});
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite
Make the list a character vector (not a vector of names)
rm(list = c('temp1','temp2'))
or
rm(temp1, temp2)
Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept
property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
Although, if your doctype isn't html
then I think you'll need to use some javascript/jquery.
Try the following code:
private static void setStatusBarTransparent(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow(). setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
Behold, for the simplest answer is mind blowing:
Here is to do it with javascript even without jQuery
element.outerHTML = element.innerHTML
with jQuery element = $('b')[0];
or without jQuery element = document.querySelector('b');
If you want it as a function:
function unwrap(selector) {
var nodelist = document.querySelectorAll(selector);
Array.prototype.forEach.call(nodelist, function(item,i){
item.outerHTML = item.innerHTML; // or item.innerText if you want to remove all inner html tags
})
}
unwrap('b')
This should work in all major browser including old IE. in recent browser, we can even call forEach right on the nodelist.
function unwrap(selector) {
document.querySelectorAll('b').forEach( (item,i) => {
item.outerHTML = item.innerText;
} )
}
SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.
>>> reduce(lambda s, x: s*256 + x, bytearray("y\xcc\xa6\xbb"))
2043455163
Test 1: inverse:
>>> hex(2043455163)
'0x79cca6bb'
Test 2: Number of bytes > 8:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAA"))
338822822454978555838225329091068225L
Test 3: Increment by one:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAB"))
338822822454978555838225329091068226L
Test 4: Append one byte, say 'A':
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA"))
86738642548474510294585684247313465921L
Test 5: Divide by 256:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA"))/256
338822822454978555838225329091068226L
Result equals the result of Test 4, as expected.
I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.
Open app page on Google Play:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + context.getPackageName()));
startActivity(intent);
See Class Constants:
class MyClass
{
const MYCONSTANT = 'constant value';
function showConstant() {
echo self::MYCONSTANT. "\n";
}
}
echo MyClass::MYCONSTANT. "\n";
$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0
In this case echoing MYCONSTANT
by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT"
.
EDIT - Perhaps what you're looking for is this static properties / variables:
class MyClass
{
private static $staticVariable = null;
public static function showStaticVariable($value = null)
{
if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
{
self::$staticVariable = $value;
}
return self::$staticVariable;
}
}
MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"
So sad It's 2020 and we are not able to have private GithubPäges:
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed;
is a good idea, as the browser only needs to read the first row in order to compute and render the entire table
, so it loads faster.
But if not, I would suggest dumping table-layout: fixed;
and changing your css as follows:
table th, table td{
border: 1px solid #000;
width:20px; //or something similar
}
table td.wideRow, table th.wideRow{
width: 300px;
}
Understand box-shadow syntax and write it accordingly
box-shadow: h-offset v-offset blur spread color;
h-offset: Horizontal offset of the shadow. A positive value puts the shadow on the right side of the box, a negative value puts the shadow on the left side of the box - Required
v-offset: Vertical offset of the shadow. A positive value puts the shadow below the box, a negative value puts the shadow above the box - Required
blur: Blur radius (The higher the number, the more blurred the shadow will be) - Optional
color: Color of the shadow - Optional
spread: Spread radius. A positive value increases the size of the shadow, a negative value decreases the size of the shadow - Optional
inset: Changes the shadow from an outer shadow to an inner shadow - Optional
box-shadow: 0 0 10px #999;
box-shadow works better with spread
box-shadow: 0 0 10px 8px #999;
use 'inset' to apply shadow inside of the box
box-shadow: 0 0 8px inset #999;
(or)
box-shadow: 0 0 8px 8px inset #999;
use rgba (red green blue alpha) to adjust the shadow more efficiently
box-shadow: 0 0 8px inset rgba(153, 153, 153, 0.8);
(or)
box-shadow: 0 0 8px 8px inset rgba(153, 153, 153, 0.8);
It is often required to move both body and html objects together.
$('html,body').animate({
scrollTop: $("#divToBeScrolledTo").offset().top
});
ShiftyThomas is right:
$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.
So to increase the margin use:
$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.
For anyone using Ionic 3 and Angular 5, I had the same error pop up and I didn't find any solutions here. But I did find some steps that worked for me.
Steps to reproduce:
ionic:(run ionic info from a terminal/cmd prompt), check versions and make sure they're up to date. You can also check the angular versions and packages in the package.json folder in your project.
I checked my dependencies and packages and installed cordova. Restarted atom and the error went away. Hope this helps!
While you can have a default page in the MVC project, the more conventional implementation for a default view would be to use a default controller, implememented in the global.asax, through the 'RegisterRoutes(...)' method. For instance if you wanted your Public\Home controller to be your default route/view, the code would be:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Public", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);
}
For this to be functional, you are required to have have a set Start Page in the project.
There is no ranking functionality in MySQL. The closest you can get is to use a variable:
SELECT t.*,
@rownum := @rownum + 1 AS rank
FROM YOUR_TABLE t,
(SELECT @rownum := 0) r
so how would that work in my case? I'd need two variables, one for each of col1 and col2? Col2 would need resetting somehow when col1 changed..?
Yes. If it were Oracle, you could use the LEAD function to peak at the next value. Thankfully, Quassnoi covers the logic for what you need to implement in MySQL.
Using plotly
(adding solution from plotly
with primary and secondary y axis- It seems to be missing):
library(plotly)
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
df=cbind.data.frame(x,y1,y2)
plot_ly(df) %>%
add_trace(x=~x,y=~y1,name = 'Line 1',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE) %>%
add_trace(x=~x,y=~y2,name = 'Line 2',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE,yaxis = "y2") %>%
layout(title = 'Title',
xaxis = list(title = "X-axis title"),
yaxis2 = list(side = 'right', overlaying = "y", title = 'secondary y axis', showgrid = FALSE, zeroline = FALSE))
Screenshot from working demo:
when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one"
. so, as soon as it reaches return new Text(name)
, code exits the loop with return new Text("one")
. so, try to print it or use asynchronous returns.
I use a generic class that inherit from ArrayList and implement a constructor with a parameter with variable number or arguments :
public class MyArrayList<T> extends ArrayList<T> {
public MyArrayList(T...items){
for (T item : items) {
this.add(item);
}
}
}
Example:
MyArrayList<String>myArrayList=new MyArrayList<String>("s1","s2","s2");
Maybe it's too late for answering but, there's a working code:
sqlplus -s "/ as sysdba" << EOF
SET HEADING OFF
SET FEEDBACK OFF
SET LINESIZE 3800
SET TRIMSPOOL ON
SET TERMOUT OFF
SET SPACE 0
SET PAGESIZE 0
select (select instance_name from v\$instance) as DB_NAME,
file_name
from dba_data_files
order by 2;
I know two methods:
List<int> myList1 = new List<int>(myArray);
Or,
List<int> myList2 = myArray.ToList();
I'm assuming you know about data types and will change the types as you please.
I have this same problem. I fixed this using:
.element {
display: table
}
using jquery $.each
you can access all data and also set in table like this
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
While browsing around to figure out about the hash in the folder name, I came across (via this answer):
http://blogs.msdn.com/b/rprabhu/archive/2005/06/29/433979.aspx
(edit: Wayback Machine link: https://web.archive.org/web/20160307233557/http://blogs.msdn.com:80/b/rprabhu/archive/2005/06/29/433979.aspx)
The exact path of the
user.config
files looks something like this:
<Profile Directory>\<Company Name>\<App Name>_<Evidence Type>_<Evidence Hash>\<Version>\user.config
where
<Profile Directory>
- is either the roaming profile directory or the local one. Settings are stored by default in the localuser.config
file. To store a setting in the roaminguser.config
file, you need to mark the setting with theSettingsManageabilityAttribute
withSettingsManageability
set toRoaming
.
<Company Name>
- is typically the string specified by theAssemblyCompanyAttribute
(with the caveat that the string is escaped and truncated as necessary, and if not specified on the assembly, we have a fallback procedure).
<App Name>
- is typically the string specified by theAssemblyProductAttribute
(same caveats as for company name).
<Evidence Type>
and<Evidence Hash>
- information derived from the app domain evidence to provide proper app domain and assembly isolation.
<Version>
- typically the version specified in theAssemblyVersionAttribute
. This is required to isolate different versions of the app deployed side by side.The file name is always simply '
user.config
'.
I think adding try/catch for every SaveChanges()
operation is not a good practice, it's better to centralize this :
Add this class to the main DbContext
class :
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
}
This will overwrite your context's SaveChanges()
method and you'll get a comma separated list containing all the entity validation errors.
this also can improved, to log errors in production env, instead of just throwing an error.
hope this is helpful.