Anyone who is still stuck - follow the instructions on this page.
Basically:
Follow the steps as initially described by AWS.
source activate python3
Don't cut and paste anything. Instead open a new terminal window without closing the first one.
In the new window enter enter the SSH command as described in the above link.
Open a web browser and go to http://127.0.0.1:8157
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
$json = array('tag' => 'Odómetro'); // Original array
$json = json_encode($json); // {"Tag":"Od\u00f3metro"}
$json = json_decode($json); // Od\u00f3metro becomes Odómetro
echo $json->{'tag'}; // Odómetro
echo utf8_decode($json->{'tag'}); // Odómetro
You were close, just use utf8_decode.
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
Put this at the top of your file:
$Logfile = "D:\Apps\Logs\$(gc env:computername).log"
Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
}
Then replace your Write-host
calls with LogWrite
.
I ran across this error on a Beaglebone Black using the standard Angstrom distribution. It is currently running Python 2.7.3, but does not include distutils. The solution for me was to install distutils. (It required su privileges.)
su
opkg install python-distutils
After that installation, the previously erroring command ran fine.
python setup.py build
Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check
Languages -> Visual C++ -> Common tools for Visual C++
Windows and web development -> Tools for universal windows apps -> Tools (1.4.1)
and Windows 10 SDK ([version])
Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])
and install. Then right click on solution -> Re-target and it will compile
list() and [] work differently:
>>> def a(p):
... print(id(p))
...
>>> for r in range(3):
... a([])
...
139969725291904
139969725291904
139969725291904
>>> for r in range(3):
... a(list())
...
139969725367296
139969725367552
139969725367616
list() always create new object in heap, but [] can reuse memory cell in many reason.
Below is example you can use:
create temp table test2 (
id1 numeric,
id2 numeric,
id3 numeric,
id4 numeric,
id5 numeric,
id6 numeric,
id7 numeric,
id8 numeric,
id9 numeric,
id10 numeric)
with (oids = false);
do
$do$
declare
i int;
begin
for i in 1..100000
loop
insert into test2 values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;
You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.
As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
If you have a special character in the column names, either select
or select_
may not work as expected.
This property of dplyr
of using "."
. To refer to the data set in the question, the following line can be used to solve this problem:
drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% .[,setdiff(names(.),drop.cols)]
They're essentially horses for courses.
Scanner
is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.String.split()
and Pattern.split()
give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.StringTokenizer
is even more restrictive than String.split()
, and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split()
. (See my comparison of String.split()
and StringTokenizer
.) It also predates the regular expressions API, of which String.split()
is a part.You'll note from my timings that String.split()
can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer
that it gives you the output as a string array, which is usually what you want. Using an Enumeration
, as provided by StringTokenizer
, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer
is a bit of a waste of space nowadays, and you may as well just use String.split()
.
If you are using reactive forms and want to disable some input associated with a form control, you should place this disabled
logic into you code and call yourFormControl.disable()
or yourFormControl.enable()
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
Unlike accepted answer, I use usermod
instead.
Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:
apt update && apt install sudo
adduser fruit
usermod -aG sudo fruit
Remember to save image after update. Use docker ps
to get current running docker's <CONTAINER ID> and <IMAGE>, then run docker commit -m "added sudo user" <CONTAINER ID> <IMAGE>
to save docker image.
Then test with:
su fruit
sudo whoami
Or test by direct login(ensure save image first) as that non-root user when launch docker:
docker run -it --user fruit <IMAGE>
sudo whoami
You can use sudo -k
to reset password prompt timestamp:
sudo whoami # No password prompt
sudo -k # Invalidates the user's cached credentials
sudo whoami # This will prompt for password
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
You can use overflow:auto;
You can also control the x or y axis individually with the overflow-x
and overflow-y
properties.
Example:
.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}
FWIW, the multiprocessing
module has a nice interface for this using the Pool
class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool
class as a drop-in replacement.
def foo(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo
# do some other stuff in the main process
return_val = async_result.get() # get the return value from your function.
Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;
A pure Javascript example, using the services of https://geolocation-db.com They provide a JSON and JSONP-callback solution.
No jQuery required!
<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geolocation-db.com</title>
</head>
<body>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Postal: <span id="postal"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP address: <span id="ipv4"></span></div>
</body>
<script>
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = document.getElementById('city');
var postal = document.getElementById('postal');
var latitude = document.getElementById('latitude');
var longitude = document.getElementById('longitude');
var ip = document.getElementById('ipv4');
function callback(data)
{
country.innerHTML = data.country_name;
state.innerHTML = data.state;
city.innerHTML = data.city;
postal.innerHTML = data.postal;
latitude.innerHTML = data.latitude;
longitude.innerHTML = data.longitude;
ip.innerHTML = data.IPv4;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://geoilocation-db.com/json/geoip.php?jsonp=callback';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(script, h);
</script>
</html>
It wont work like this.
When you try to insert the row using a query all values should be there in query.
With the above problem you want to insert
magazine_subscription_id, subscription_name, magazine_id, status
in select query you have
magazine_subscription_id, subscription_name, magazine_id, status
1 it is not possible.
If you want to insert either you need to insert using query of direct values
Unless there is a definite requirement of writing on external storage, you can always choose to save files in app directory. In my case I had to save files and after wasting 2 to 3 days I found out if I change the storage path from
Environment.getExternalStorageDirectory()
to
getApplicationContext().getFilesDir().getPath() //which returns the internal app files directory path
it works like charm on all the devices. This is because for writing on External storage you need extra permissions but writing in internal app directory is simple.
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
You can create a datasource bean in servlet context as:
<beans:bean id="dataSource"
class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<beans:property name="dataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<beans:property name="maximumPoolSize" value="5" />
<beans:property name="maxLifetime" value="30000" />
<beans:property name="idleTimeout" value="30000" />
<beans:property name="dataSourceProperties">
<beans:props>
<beans:prop key="url">jdbc:mysql://localhost:3306/exampledb</beans:prop>
<beans:prop key="user">root</beans:prop>
<beans:prop key="password"></beans:prop>
<beans:prop key="prepStmtCacheSize">250</beans:prop>
<beans:prop key="prepStmtCacheSqlLimit">2048</beans:prop>
<beans:prop key="cachePrepStmts">true</beans:prop>
<beans:prop key="useServerPrepStmts">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
The name will be something like "Australia/Sydney", or "Europe/Lisbon".
Since it sounds like you might only care about the continent, that might be all you need.
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
It sounds like you probably want to get ahold of json-lib:
http://json-lib.sourceforge.net/
Douglas Crockford is the guy who invented JSON; his Java library is here:
It sounds like the folks at json-lib picked up where Crockford left off. Both fully support JSON, both use (compatible, as far as I can tell) JSONObject, JSONArray and JSONFunction constructs.
'Hope that helps ..
I submit that it is better to leave your data stacked as it is:
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])
Then it's a bit more intuitive to say
df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)
This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot
, it's purely based on column convention as to what semantic entity it is that you are reshaping.
go to the url about:config
and paste each line:
network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10
Give the Exec Maven plugin a try
You can try using:
select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual
Add reference to Microsoft.VisualBasic
and use this function:
string response = Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);
The last 2 number is an X/Y position to display the input dialog.
public static void convertStringToDecimal(String binary)
{
int decimal=0;
int power=0;
while(binary.length()>0)
{
int temp = Integer.parseInt(binary.charAt((binary.length())-1)+"");
decimal+=temp*Math.pow(2, power++);
binary=binary.substring(0,binary.length()-1);
}
System.out.println(decimal);
}
Do not use eval
! It has a major risk of introducing arbitrary code execution.
Put it in an array and expand all the words with double-quotes "${arr[@]}"
to not let the IFS
split the words due to Word Splitting.
cmdArgs=()
cmdArgs=('date' '+%H:%M:%S')
and see the contents of the array inside. The declare -p
allows you see the contents of the array inside with each command parameter in separate indices. If one such argument contains spaces, quoting inside while adding to the array will prevent it from getting split due to Word-Splitting.
declare -p cmdArgs
declare -a cmdArgs='([0]="date" [1]="+%H:%M:%S")'
and execute the commands as
"${cmdArgs[@]}"
23:15:18
(or) altogether use a bash
function to run the command,
cmd() {
date '+%H:%M:%S'
}
and call the function as just
cmd
POSIX sh
has no arrays, so the closest you can come is to build up a list of elements in the positional parameters. Here's a POSIX sh
way to run a mail program
# POSIX sh
# Usage: sendto subject address [address ...]
sendto() {
subject=$1
shift
first=1
for addr; do
if [ "$first" = 1 ]; then set --; first=0; fi
set -- "$@" --recipient="$addr"
done
if [ "$first" = 1 ]; then
echo "usage: sendto subject address [address ...]"
return 1
fi
MailTool --subject="$subject" "$@"
}
Note that this approach can only handle simple commands with no redirections. It can't handle redirections, pipelines, for/while loops, if statements, etc
Another common use case is when running curl
with multiple header fields and payload. You can always define args like below and invoke curl
on the expanded array content
curlArgs=('-H' "keyheader: value" '-H' "2ndkeyheader: 2ndvalue")
curl "${curlArgs[@]}"
Another example,
payload='{}'
hostURL='http://google.com'
authToken='someToken'
authHeader='Authorization:Bearer "'"$authToken"'"'
now that variables are defined, use an array to store your command args
curlCMD=(-X POST "$hostURL" --data "$payload" -H "Content-Type:application/json" -H "$authHeader")
and now do a proper quoted expansion
curl "${curlCMD[@]}"
Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
<script>
function access() {
var iframe = document.getElementById("iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(innerDoc.body);
}
</script>
Just edit your your catalina/bin/startup.sh script. Add the following commands in it:
#Adjust it to the size you want. Ignore the from bit.
export CATALINA_OPTS="-Xmx1024m"
#This should point to your catalina base directory
export CATALINA_BASE=/usr/local/tomcat
#This is only used if you editing the instance of your tomcat
/usr/share/tomcat6/bin/startup.sh
In Vim you can do one of the following:
:%s/^/#
:10,15s/^/#
:10,.s/^/#
:10,$s/^/#
or using visual block:
The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.
Basic usage required two things:
First include the Facade in your file
use Illuminate\Support\Facades\Hash;
and use Make
Method to generate password.
$hashedPassword = Hash::make($request->newPassword);
and when you want to match the Hashed string you can use the below code:
Hash::check($request->newPasswordAtLogin, $hashedPassword)
You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing
list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])
Just in case anyone falls here, the (only) solution that worked for me is creating the OkHttpClient
like explained here.
Here is the code:
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
public int count = 0;
}
public boolean haveSameElements(final List<String> list1, final List<String> list2) {
// (list1, list1) is always true
if (list1 == list2) return true;
// If either list is null, or the lengths are not equal, they can't possibly match
if (list1 == null || list2 == null || list1.size() != list2.size())
return false;
// (switch the two checks above if (null, null) should return false)
Map<String, Count> counts = new HashMap<>();
// Count the items in list1
for (String item : list1) {
if (!counts.containsKey(item)) counts.put(item, new Count());
counts.get(item).count += 1;
}
// Subtract the count of items in list2
for (String item : list2) {
// If the map doesn't contain the item here, then this item wasn't in list1
if (!counts.containsKey(item)) return false;
counts.get(item).count -= 1;
}
// If any count is nonzero at this point, then the two lists don't match
for (Map.Entry<String, Count> entry : counts.entrySet()) {
if (entry.getValue().count != 0) return false;
}
return true;
}
- My first question is about the abstract factory. Is its role to allow you to create families of concrete objects in (that can depend on what specific factory you use) rather than just a single concrete object?
Yes. The intent of Abstract Factory is:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- Does the abstract factory only return one very large object or many objects depending on what methods you call?
Ideally it should return one object per the method client is invoking.
- My understanding is that the factory method pattern has a Creator interface that will make the ConcreteCreator be in charge of knowing which ConcreteProduct to instantiate. Is this what it means by using inheritance to handle object instantiation?
Yes. Factory method uses inheritance.
- Abstract Factory pattern delegate the responsibility of object instantiation to another object via composition? What does this mean?
AbstractFactory defines a FactoryMethod and ConcreteFactory is responsible for building a ConcreteProduct. Just follow through the code example in this article.
You can find more details in related SE posts:
What is the basic difference between the Factory and Abstract Factory Patterns?
Design Patterns: Factory vs Factory method vs Abstract Factory
How to print:
NSLog(@"Something To Print");
Or
NSString * someString = @"Something To Print";
NSLog(@"%@", someString);
For other types of variables, use:
NSLog(@"%@", someObject);
NSLog(@"%i", someInt);
NSLog(@"%f", someFloat);
/// etc...
Can you show it in phone?
Not by default, but you could set up a display to show you.
print("Print this string")
print("Print this \(variable)")
print("Print this ", variable)
print(variable)
Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.
With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.
Then you just modify the following code:
ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh
You can also turn off background refresh in VBA:
ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False
If you actually want a static property of your class, that isn't currently supported in Swift. The current advice is to get around that by using global constants:
let testStr = "test"
let testStrLen = countElements(testStr)
class MyClass {
func myFunc() {
}
}
If you want these to be instance properties instead, you can use a lazy stored property for the length -- it will only get evaluated the first time it is accessed, so you won't be computing it over and over.
class MyClass {
let testStr: String = "test"
lazy var testStrLen: Int = countElements(self.testStr)
func myFunc() {
}
}
There are some great answers, but many use functions that are flagged as not cryptographically secure. If you want a random 6 digit number that is cryptographically secure you can use something like this:
$key = random_int(0, 9999999);
$key = str_pad($key, 6, 0, STR_PAD_LEFT);
return $key;
This will also include numbers like 000182 and others that would otherwise be excluded from the other examples.
In Python 3, we can encode the string as UTF-8, then check whether the length stays the same. If so, then the original string is ASCII.
def isascii(s):
"""Check if the characters in string s are in ASCII, U+0-U+7F."""
return len(s) == len(s.encode())
To check, pass the test string:
>>> isascii("?O???O??")
False
>>> isascii("Python")
True
SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;
An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:
Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);
// This is not possible: It would throw an
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");
// This is still possible:
realMap.put("E", "F");
// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F".
In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.
Update:
As pointed out in a comment, an immutable map can also be created with the standard API using
Map<String, String> immutableMap =
Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap));
This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap
without having to add the dependency to Guava.
First make link with @bold bot . Then Copy text and paste it to remove "via @bold"
I found this on React's Github issues: Works like a charm (v15.6.2)
Here is how I implemented to a Text input:
changeInputValue = newValue => {
const e = new Event('input', { bubbles: true })
const input = document.querySelector('input[name=' + this.props.name + ']')
console.log('input', input)
this.setNativeValue(input, newValue)
input.dispatchEvent(e)
}
setNativeValue (element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set
const prototype = Object.getPrototypeOf(element)
const prototypeValueSetter = Object.getOwnPropertyDescriptor(
prototype,
'value'
).set
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value)
} else {
valueSetter.call(element, value)
}
}
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
Or even:
std::vector<int> v(2);
v = { 34,23 };
On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:
int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);
Or, for the case of assignment to an existing vector:
int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);
Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:
template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }
And then you can do this without having to repeat the size all over:
int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));
In my case I had to add the boundary to the header like the following:
const form = new FormData();
form.append(item.name, fs.createReadStream(pathToFile));
const response = await axios({
method: 'post',
url: 'http://www.yourserver.com/upload',
data: form,
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
},
});
This solution is also useful if you're working with React Native.
Please post your Model Class.
To check the errors in your ModelState
use the following code:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
OR: You can also use
var errors = ModelState.Values.SelectMany(v => v.Errors);
Place a break point at the above line and see what are the errors in your ModelState
.
At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be
replace: ((TypeName)$0)
For me, nobody explains it better than mindpro.com:
Gotchas
java.util.GregorianCalendar
has far fewer bugs and gotchas than theold java.util.Date
class but it is still no picnic.Had there been programmers when Daylight Saving Time was first proposed, they would have vetoed it as insane and intractable. With daylight saving, there is a fundamental ambiguity. In the fall when you set your clocks back one hour at 2 AM there are two different instants in time both called 1:30 AM local time. You can tell them apart only if you record whether you intended daylight saving or standard time with the reading.
Unfortunately, there is no way to tell
GregorianCalendar
which you intended. You must resort to telling it the local time with the dummy UTC TimeZone to avoid the ambiguity. Programmers usually close their eyes to this problem and just hope nobody does anything during this hour.Millennium bug. The bugs are still not out of the Calendar classes. Even in JDK (Java Development Kit) 1.3 there is a 2001 bug. Consider the following code:
GregorianCalendar gc = new GregorianCalendar(); gc.setLenient( false ); /* Bug only manifests if lenient set false */ gc.set( 2001, 1, 1, 1, 0, 0 ); int year = gc.get ( Calendar.YEAR ); /* throws exception */
The bug disappears at 7AM on 2001/01/01 for MST.
GregorianCalendar
is controlled by a giant of pile of untyped int magic constants. This technique totally destroys any hope of compile-time error checking. For example to get the month you useGregorianCalendar. get(Calendar.MONTH));
GregorianCalendar
has the rawGregorianCalendar.get(Calendar.ZONE_OFFSET)
and the daylight savingsGregorianCalendar. get( Calendar. DST_OFFSET)
, but no way to get the actual time zone offset being used. You must get these two separately and add them together.
GregorianCalendar.set( year, month, day, hour, minute)
does not set the seconds to 0.
DateFormat
andGregorianCalendar
do not mesh properly. You must specify the Calendar twice, once indirectly as a Date.If the user has not configured his time zone correctly it will default quietly to either PST or GMT.
In GregorianCalendar, Months are numbered starting at January=0, rather than 1 as everyone else on the planet does. Yet days start at 1 as do days of the week with Sunday=1, Monday=2,… Saturday=7. Yet DateFormat. parse behaves in the traditional way with January=1.
For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
This can be the solution:
git fetch
git checkout origin/master -- FolderPathName/fileName
Thanks.
This code works for fragments:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
QMessageBox
includes static methods to quickly ask such questions:
#include <QApplication>
#include <QMessageBox>
int main(int argc, char **argv)
{
QApplication app{argc, argv};
while (QMessageBox::question(nullptr,
qApp->translate("my_app", "Test"),
qApp->translate("my_app", "Are you sure you want to quit?"),
QMessageBox::Yes|QMessageBox::No)
!= QMessageBox::Yes)
// ask again
;
}
If your needs are more complex than provided for by the static methods, you should construct a new QMessageBox
object, and call its exec()
method to show it in its own event loop and obtain the pressed button identifier. For example, we might want to make "No" be the default answer:
#include <QApplication>
#include <QMessageBox>
int main(int argc, char **argv)
{
QApplication app{argc, argv};
auto question = new QMessageBox(QMessageBox::Question,
qApp->translate("my_app", "Test"),
qApp->translate("my_app", "Are you sure you want to quit?"),
QMessageBox::Yes|QMessageBox::No,
nullptr);
question->setDefaultButton(QMessageBox::No);
while (question->exec() != QMessageBox::Yes)
// ask again
;
}
std::string replace(std::string str, const std::string& sub1, const std::string& sub2)
{
if (sub1.empty())
return str;
std::size_t pos;
while ((pos = str.find(sub1)) != std::string::npos)
str.replace(pos, sub1.size(), sub2);
return str;
}
I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET
It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.
Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.
Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.
http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html
/Damian
If you want to avoid the regex, or must target an earlier JVM, String.replace() will do:
str=str.replace("\r","").replace("\n","");
And to remove a CRLF pair:
str=str.replace("\r\n","");
The latter is more efficient than building a regex to do the same thing. But I think the former will be faster as a regex since the string is only parsed once.
In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript
document.getElementById("The id of the element").value = "The value"
And that would set the value and make the current value selected in the combo box. Tested in firefox.
it was easier than keep googling a solution for jQuery
If you use ES6 anon functions, it will conflict with $(this)
This works:
$('.dna-list').on('click', '.card', function(e) {
console.log($(this));
});
This doesn't work:
$('.dna-list').on('click', '.card', (e) => {
console.log($(this));
});
Another thing that you should check is the Target Framework of any referenced projects to make sure that the calling project is using the same or later version of the framework.
I had this issue, I tried all of the previously suggested answers and then on a hunch checked the frameworks. One of projects being referenced was targeting 4.6.1 when the calling project was only 4.5.2.
The simplest and shortest way is to use CmdTool library.
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
You can find more examples here.
Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.
<style>
#myFrame { width:100%; height:100%; }
</style>
<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>
Probable cause that remount
fails is you are not running adb
as root
.
Shell Script should be as follow.
# Script to mount Android Device as read/write.
# List the Devices.
adb devices;
# Run adb as root (Needs root access).
adb root;
# Since you're running as root su is not required
adb shell mount -o rw,remount /;
If this fails, you could try the below:
# List the Devices.
adb devices;
# Run adb as root
adb root;
adb remount;
adb shell su -c "mount -o rw,remount /";
To find which user
you are:
$ adb shell whoami
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
try
/usr/lib/mongodb/mongod.exe --dbpath c:data\db
--dbpath (should be followed by the path of your db)
nbconvert allows you to run notebooks with the --execute
flag:
jupyter nbconvert --execute <notebook>
If you want to run a notebook and produce a new notebook, you can add --to notebook
:
jupyter nbconvert --execute --to notebook <notebook>
Or if you want to replace the existing notebook with the new output:
jupyter nbconvert --execute --to notebook --inplace <notebook>
Since that's a really long command, you can use an alias:
alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>
On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.
On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.
A well written blog post: http://www.johnpapa.net/angular-growth-structure/
Example App: https://github.com/angular-app/angular-app
An interesting observation I made while passing previous state params from one route to another is that $stateParams gets hoisted and overwrites the previous route's state params that were passed with the current state params, but using $state.param
s doesn't.
When using $stateParams
:
var stateParams = {};
stateParams.nextParams = $stateParams; //{item_id:123}
stateParams.next = $state.current.name;
$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{next:'app.details'}}
When using $state.params:
var stateParams = {};
stateParams.nextParams = $state.params; //{item_id:123}
stateParams.next = $state.current.name;
$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{item_id:123}}
Lets say ClassOne
is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
var slug = function(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "ãàáäâ?èéëêìíïîõòóöôùúüûñç·/_,:;";
var to = "aaaaaeeeeeiiiiooooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
};
and try
slug($('#field').val())
original by: http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/
EDIT: extended for more language specific chars:
var from = "ÁÄÂÀÃÅCÇCDÉEËÈÊ?E?GÍÌÎÏINÑÓÖÒÔÕØRRŠSTÚUÜÙÛÝŸŽáäâàãåcçcdéeëèê?e?gíìîïinñóöòôõøðrršstúuüùûýÿžþÞÐdßÆa·/_,:;";
var to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";
In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b
or --bind
flag.
python -m http.server 8000 --bind 127.0.0.1
The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
You will then have access to network via wifi card.
Try this
chdir /d D:\Work\Root
Enjoy rooting ;)
If you have it available, using curl is your best option.
You can see if it is enabled by doing phpinfo()
and searching the page for curl.
If it is enabled, try this:
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);
Even easier, just CSS can resolve the problem:
input[type="text"], input[type="password"], textarea, select {
width: 200px;
border: 1px solid;
border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
background: #FFF;
padding: 8px 5px;
font: 16px Arial, Tahoma, Helvetica, sans-serif;
-moz-box-shadow: 0 0 5px #C0C0C0;
-moz-border-radius: 5px;
-webkit-box-shadow: 0 0 5px #C0C0C0;
-webkit-border-radius: 5px;
box-shadow: 0 0 5px #C0C0C0;
border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus {
border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
outline: none;
-moz-box-shadow: 0 0 10px #B6D5F7;
-webkit-box-shadow: 0 0 10px #B6D5F7;
box-shadow: 0 0 10px #B6D5F7;
}
For a package manager that can install and manage multiple versions of python, these are good choices:
The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.
This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile
and ~/.bashrc
or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.
You'll need root privileges for this method.
See the official python documentation for building from source for additional considerations and options.
/usr/local
is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.
Install any build dependencies. On Debian-based systems, use:
apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev
Choose which python version you want to install. See the Python Source Releases page for a listing.
Download and unzip file in /usr/local/src
, replacing X.X.X
below with the python version (i.e. 3.8.2
).
cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz
Before building and installing, set the CFLAGS
environment variable with C compiler flags necessary (see GNU's make
documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC
, with the following:
export CFLAGS='-fPIC'
Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations
option on the ./configure
command for profile guided optimization. Use --prefix=/usr/local
to install to the proper subdirectories (/usr/local/bin
, /usr/local/lib
, etc.).
cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local
Build the project with make
and install with make altinstall
to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.
make -j 4
make altinstall
Then you should be able to run your new python and pip versions with pythonX.X
and pipX.X
(i.e python3.8
and pip3.8
). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X
) or set an alias to use this version.
$items = array();
foreach ($haystacks as $haystack) {
if (preg_match($pattern, $haystack, $matches)
$items[] = $matches[1];
}
Go to Project settings --> Hooks --> (Under) Pre-receive hooks
Disable cp require issue reference in commits
How come no-one seems to like repr
?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr
Order matters
If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang:
func remove(slice []int, s int) []int {
return append(slice[:s], slice[s+1:]...)
}
However, this is inefficient because you may end up with moving all of the elements, which is costy.
Order is not important
If you do not care about ordering, you have the much faster possibility to swap the element to delete with the one at the end of the slice and then return the n-1 first elements:
func remove(s []int, i int) []int {
s[len(s)-1], s[i] = s[i], s[len(s)-1]
return s[:len(s)-1]
}
With the reslicing method, emptying an array of 1 000 000 elements take 224s, with this one it takes only 0.06ns. I suspect that internally, go only changes the length of the slice, without modifying it.
Edit 1
Quick notes based on the comments below (thanks to them !).
As the purpose is to delete an element, when the order does not matter a single swap is needed, the second will be wasted :
func remove(s []int, i int) []int {
s[i] = s[len(s)-1]
// We do not need to put s[i] at the end, as it will be discarded anyway
return s[:len(s)-1]
}
Also, this answer does not perform bounds-checking. It expects a valid index as input. This means that negative values or indices that are greater or equal to len(s) will cause Go to panic. Slices and arrays being 0-indexed, removing the n-th element of an array implies to provide input n-1. To remove the first element, call remove(s, 0), to remove the second, call remove(s, 1), and so on and so forth.
Just encountered this issue. Deleting breakpoints didn't work, or at least not just on its own. After this failed I Went Tools > Options > Debugging > Symbols and "Empty Symbol Cache"
and then cleaned the solution and rebuilt.
Now seems to be working correctly. So if you try all the other things listed, and it still makes no differnce, these additional bits of info may help...
Use html-pdf
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
Array.from(new Array(row), () => new Array(col).fill(0));
.borders {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background-color: black;_x000D_
border-width: 40px;_x000D_
border-style: solid;_x000D_
border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
Better use int.TryParse
to avoid exceptions;
var numbers = sNumbers
.Split(',')
.Where(x => int.TryParse(x, out _))
.Select(int.Parse)
.ToList();
Some feedback on the segment of code, though for the most part, it should work...
void main(int c,char **args)
int main
- the standard defines main
as returning an int
.c
and args
are typically named argc
and argv
, respectfully, but you are allowed to name them anything...
{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
args[1]
is longer than 50 bytes, buffer
will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy
......
dir=opendir(buffer); //this part
If this returning NULL
, it can be for a few reasons:
./your_program my directory
, which will fail, because it tries to opendir("my")
)Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
HTML:
<ul>
<li onclick="myfunction(this)">
<span></span>
<p>This Text</p>
</li>
</ul>?
JavaScript:
function myfunction(foo) {
var elem = foo.getElementsByTagName('p');
var TextInsideLi = elem[0].innerHTML;
}?
CURSORS are an option here, but generally frowned upon as they often do not make best use of the query engine. Consider investigating 'SET Based Queries' to see if you can achieve what it is you want to do without using a CURSOR.
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
A char can hold a single character only, a character literal is a single character in single quote, i.e. '&'
- if you have more characters than one you want to use a string, for that you have to use double quotes:
case "&&":
There are tools which profile code and provide code coverage data. This lets you see (as code is run) how much of it is being called. You can get any of these tools to find out how much orphan code you have.
let threshold = 100.0 // threshold from bottom of tableView
var isLoadingMore = false // flag
func scrollViewDidScroll(scrollView: UIScrollView) {
let contentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
if !isLoadingMore && (maximumOffset - contentOffset <= threshold) {
// Get more data - API call
self.isLoadingMore = true
// Update UI
dispatch_async(dispatch_get_main_queue()) {
tableView.reloadData()
self.isLoadingMore = false
}
}
}
The DISTINCT
keyword doesn't really work the way you're expecting it to. When you use SELECT DISTINCT col1, col2, col3
you are in fact selecting all unique {col1, col2, col3} tuples.
To change image by using code
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setImageResource(R.drawable.ImageName);
}
}
Or, using an XML file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
In OnClick
, just add this code:
ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));
how to convert JTextField to string and string to JTextField in java
If you mean how to get and set String from jTextField then you can use following methods:
String str = jTextField.getText() // get string from jtextfield
and
jTextField.setText(str) // set string to jtextfield
//or
new JTextField(str) // set string to jtextfield
You should check JavaDoc for JTextField
If you have multiple rows for parent_id.
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;
If you want to replace space with comma.
SELECT REPLACE(id,' ',',') FROM table_level where parent_id=4;
The border is given the whole html element. If you want half bottom border, you can wrap it with some other identifiable block like span.
HTML code:
<div> <span>content here </span></div>
CSS as below:
div{
width:200px;
height:50px;
}
span{
width:100px;
border-bottom:1px solid magenta;
}
I understand that this question is old, but there is a good solution for it in HTML5.
You can wrap it all in a <figure></figure>
tag. The code would look something like this:
<div id="wrapper">
<figure>
<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>
</figure>
</div>
and the CSS:
#wrapper{
text-align:center;
}
I was facing the same problem . Solution is given below
Right click on Source Program > Properties > Configuration Properties > C/C++ > Language > Now change Open MP support flag to Yes....
You will get the desired result.
Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind?
Take 2 minutes tour with me:
(?=) - positive lookahead
(?<=) - positive lookbehind
Suppose
A B C #in a line
Now, we ask B, Where are you?
B has two solutions to declare it location:
One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.
As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.
You should use your custom input reader for faster results instead of extracting first character from reading String. Link for Custom ScanReader and explanation: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8
Code for scanning Char :
BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();
To center it, you can use the technique shown here: Absolute centering.
To make it as big as possible, give it max-width
and max-height
of 100%
.
To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit
as explained here.
.className {
max-width: 100%;
max-height: 100%;
bottom: 0;
left: 0;
margin: auto;
overflow: auto;
position: fixed;
right: 0;
top: 0;
-o-object-fit: contain;
object-fit: contain;
}
_x000D_
<img src="https://i.imgur.com/HmezgW6.png" class="className" />
<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
_x000D_
If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.
For this example however I don't think you need the first s:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html
List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();
REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).
If not having ugly URI is a concern (e.g. not including the url encoded version of :
, -
, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g.
http://example.com/start/1331162374
). The URL looks a little cleaner, but you certainly lose readability.
The /2012/03/07
is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.
Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).
The problem is that PHP mail()
function has a very limited functionality. There are several ways to send mail from PHP.
mail()
uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.mail()
uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail()
function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer
class or interface with abstract send()
method. Inherit two classes MyPhpMailer
and MySwiftMailer
. Implement send()
method in appropriate ways.
<input type="image" name="your_image_name" src="your_image_url.png" />
This will send the your_image_name.x
and your_image_name.y
values as it submits the form, which are the x and y coordinates of the position the user clicked the image.
1 Go to your project directory and check if this folder exists android/app/src/main/assets
index.android.bundle
and index.android.bundle.meta
2.From your root project directory do
cd android && ./gradlew clean
3.Finally, navigate back to the root directory and check if there is one single entry file calledindex.js
If there is only one file i.e. index.js then run following command react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
If there are two files i.e index.android.js and index.ios.js then run this react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
react-native run-android
Please try:
SELECT * INTO NewTable FROM OldTable
This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:
clear() {
this.myForm.get('someControlName').reset()
}
To run the batch file when the VM
user logs in:
Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.
Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\
.
As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:
start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"
But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.
You can use inline assembly for the function call. (in this code I assume the arguments are characters).
void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
{
va_list argumentsToPass;
va_start(argumentsToPass, fmt);
char *list = new char[numOfArgs];
for(int n = 0; n < numOfArgs; n++)
list[n] = va_arg(argumentsToPass, char);
va_end(argumentsToPass);
for(int n = numOfArgs - 1; n >= 0; n--)
{
char next;
next = list[n];
__asm push next;
}
__asm push fmt;
__asm call format_string;
fprintf(stdout, fmt);
}
Find file:
[XAMPP Installation Directory]\php\php.ini
php.ini
.max_execution_time
and increase the value of it as you requiredI like one-line notation for GCD, it's more elegant:
DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
// do stuff 42 seconds later
}
Also, in iOS 10 we have new Timer methods, e.g. block initializer:
(so delayed action may be canceled)
let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
// do stuff 42 seconds later
}
Btw, keep in mind: by default, timer is added to the default run loop mode. It means timer may be frozen when the user is interacting with the UI of your app (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode:
RunLoop.current.add(timer, forMode: .common)
At this blog post you can find more details.
function _showModalDialog(url, width, height, closeCallback) {
var modalDiv,
dialogPrefix = window.showModalDialog ? 'dialog' : '',
unit = 'px',
maximized = width === true || height === true,
w = width || 600,
h = height || 500,
border = 5,
taskbar = 40, // windows taskbar
header = 20,
x,
y;
if (maximized) {
x = 0;
y = 0;
w = screen.width;
h = screen.height;
} else {
x = window.screenX + (screen.width / 2) - (w / 2) - (border * 2);
y = window.screenY + (screen.height / 2) - (h / 2) - taskbar - border;
}
var features = [
'toolbar=no',
'location=no',
'directories=no',
'status=no',
'menubar=no',
'scrollbars=no',
'resizable=no',
'copyhistory=no',
'center=yes',
dialogPrefix + 'width=' + w + unit,
dialogPrefix + 'height=' + h + unit,
dialogPrefix + 'top=' + y + unit,
dialogPrefix + 'left=' + x + unit
],
showModal = function (context) {
if (context) {
modalDiv = context.document.createElement('div');
modalDiv.style.cssText = 'top:0;right:0;bottom:0;left:0;position:absolute;z-index:50000;';
modalDiv.onclick = function () {
if (context.focus) {
context.focus();
}
return false;
}
window.top.document.body.appendChild(modalDiv);
}
},
removeModal = function () {
if (modalDiv) {
modalDiv.onclick = null;
modalDiv.parentNode.removeChild(modalDiv);
modalDiv = null;
}
};
// IE
if (window.showModalDialog) {
window.showModalDialog(url, null, features.join(';') + ';');
if (closeCallback) {
closeCallback();
}
// Other browsers
} else {
var win = window.open(url, '', features.join(','));
if (maximized) {
win.moveTo(0, 0);
}
// When charging the window.
var onLoadFn = function () {
showModal(this);
},
// When you close the window.
unLoadFn = function () {
window.clearInterval(interval);
if (closeCallback) {
closeCallback();
}
removeModal();
},
// When you refresh the context that caught the window.
beforeUnloadAndCloseFn = function () {
try {
unLoadFn();
}
finally {
win.close();
}
};
if (win) {
// Create a task to check if the window was closed.
var interval = window.setInterval(function () {
try {
if (win == null || win.closed) {
unLoadFn();
}
} catch (e) { }
}, 500);
if (win.addEventListener) {
win.addEventListener('load', onLoadFn, false);
} else {
win.attachEvent('load', onLoadFn);
}
window.addEventListener('beforeunload', beforeUnloadAndCloseFn, false);
}
}
}
TL;DR
For accessing OS use: System.getProperty("os.name")
.
But why not create a utility class, make it reusable! And probably much faster on multiple calls. Clean, clear, faster!
Create a Util class for such utility functions. Then create public enums for each operating system type.
public class Util {
public enum OS {
WINDOWS, LINUX, MAC, SOLARIS
};// Operating systems.
private static OS os = null;
public static OS getOS() {
if (os == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
os = OS.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
os = OS.LINUX;
} else if (operSys.contains("mac")) {
os = OS.MAC;
} else if (operSys.contains("sunos")) {
os = OS.SOLARIS;
}
}
return os;
}
}
Now, you can easily invoke class from any class as follows,(P.S. Since we declared os variable as static, it will consume time only once to identify the system type, then it can be used until your application halts. )
switch (Util.getOS()) {
case WINDOWS:
//do windows stuff
break;
case LINUX:
and That is it!
In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.
If ctrl + c doesn't work use this:
ctrl +shift+ c
Sometimes people change the behaviour of ctrl + c for copy/pasting so you may need this.
Of course, you should also ensure that the terminal window has keyboard focus, ctrl + c won't work if your browser window has focus.
Add a CSS class to the <option>
tag to style it: http://jsfiddle.net/Ahreu/
Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?
iPad Detection
You should be able to detect an iPad user by taking a look at the userAgent
property:
var is_iPad = navigator.userAgent.match(/iPad/i) != null;
iPhone/iPod Detection
Similarly, the platform
property to check for devices like iPhones or iPods:
function is_iPhone_or_iPod(){
return navigator.platform.match(/i(Phone|Pod))/i)
}
Notes
While it works, you should generally avoid performing browser-specific detection as it can often be unreliable (and can be spoofed). It's preferred to use actual feature-detection in most cases, which can be done through a library like Modernizr.
As pointed out in Brennen's answer, issues can arise when performing this detection within the Facebook app. Please see his answer for handling this scenario.
Related Resources
yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).
@Component({
...
host: {
'(document:keydown)': 'handleKeyboardEvents($event)'
}
})
export class MyComponent {
...
handleKeyboardEvents(event: KeyboardEvent) {
this.key = event.which || event.keyCode;
}
}
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Open"/>
<MenuItem Header="_Close"/>
<MenuItem Header="_Save"/>
</MenuItem>
</Menu>
<StackPanel></StackPanel>
</DockPanel>
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
Following query helped me. Instead of using LIKE
, you can use ~*
.
select id, name from hosts where name ~* 'julia|lena|jack';
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
On click it can be done using below code
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').slideToggle(500);
});
Look into using grunt to automate this, there are numerous tutorials around, but here's a quick start.
For a folder structure like:
blah/
blah/one.ts
blah/two.ts
blah/example/
blah/example/example.ts
blah/example/package.json
blah/example/Gruntfile.js
blah/example/index.html
You can watch and work with typescript easily from the example folder with:
npm install
grunt
With package.json:
{
"name": "PROJECT",
"version": "0.0.1",
"author": "",
"description": "",
"homepage": "",
"private": true,
"devDependencies": {
"typescript": "~0.9.5",
"connect": "~2.12.0",
"grunt-ts": "~1.6.4",
"grunt-contrib-watch": "~0.5.3",
"grunt-contrib-connect": "~0.6.0",
"grunt-open": "~0.2.3"
}
}
And a grunt file:
module.exports = function (grunt) {
// Import dependencies
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-ts');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: { // <--- Run a local server on :8089
options: {
port: 8089,
base: './'
}
}
},
ts: {
lib: { // <-- compile all the files in ../ to PROJECT.js
src: ['../*.ts'],
out: 'PROJECT.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: true,
removeComments: false
}
},
example: { // <--- compile all the files in . to example.js
src: ['*.ts'],
out: 'example.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: false,
removeComments: false
}
}
},
watch: {
lib: { // <-- Watch for changes on the library and rebuild both
files: '../*.ts',
tasks: ['ts:lib', 'ts:example']
},
example: { // <--- Watch for change on example and rebuild
files: ['*.ts', '!*.d.ts'],
tasks: ['ts:example']
}
},
open: { // <--- Launch index.html in browser when you run grunt
dev: {
path: 'http://localhost:8089/index.html'
}
}
});
// Register the default tasks to run when you run grunt
grunt.registerTask('default', ['ts', 'connect', 'open', 'watch']);
}
Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.
To set VSCODE Default Formatter
File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)
Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.
This article describes how to get information about locked MySQL resources. mysqladmin debug
might also be of some use.
Since JavaMail version 1.4, there is an overload of setText
method that accepts the subtype.
// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );
The tables you are looking for are probably in a different schema. There are a couple of options. You can either click on Other Users in the tree under your connection, or right click on the connection and select Schema Browser and then select the desired schema.
I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.
I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.
Just make sure to execute commit
or rollback
after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.
Just as maasg says you can create a new DataFrame from the result of a map applied to the old DataFrame. An example for a given DataFrame df
with two rows:
val newDf = sqlContext.createDataFrame(df.map(row =>
Row(row.getInt(0) + SOMETHING, applySomeDef(row.getAs[Double]("y")), df.schema)
Note that if the types of the columns change, you need to give it a correct schema instead of df.schema
. Check out the api of org.apache.spark.sql.Row
for available methods: https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Row.html
[Update] Or using UDFs in Scala:
import org.apache.spark.sql.functions._
val toLong = udf[Long, String] (_.toLong)
val modifiedDf = df.withColumn("modifiedColumnName", toLong(df("columnName"))).drop("columnName")
and if the column name needs to stay the same you can rename it back:
modifiedDf.withColumnRenamed("modifiedColumnName", "columnName")
I'm posting this since I have always been struggling when renaming a project in XCode
.
Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.
REF links:
Rename Project.
Rename Source Folder and other files.
1- Backup your project.
If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).
2- Open your project.
3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.
NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.
4- Rename the Scheme
a) Click the menu right next to the stop button and select Manage Schemes.
b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.
c) Click ok.
5 - Build and run to make sure it works.
NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.
6- Close the project.
7- Rename the main and the source folder.
8- Right click the project bundle .xcodeproj
file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.
9- Search and replace any occurrence of the original folder name with the new folder name.
10- Save the file.
11- Open XCode project, test it.
12- Done.
There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer
Here is a variant for dynamically adding a class
function setClassStyle(class_name, css) {
var style_sheet = document.createElement('style');
if (style_sheet) {
style_sheet.setAttribute('type', 'text/css');
var cstr = '.' + class_name + ' {' + css + '}';
var rules = document.createTextNode(cstr);
if(style_sheet.styleSheet){// IE
style_sheet.styleSheet.cssText = rules.nodeValue;
} else {
style_sheet.appendChild(rules);
}
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(style_sheet);
}
}
}
If you are using Carbon you can do the following. You could also format this date to set an Expire
HTTP Header.
Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)
It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!
I am using this base class connection with mysql:
"base.js"
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 10,
host: Config.appSettings().database.host,
user: Config.appSettings().database.username,
password: Config.appSettings().database.password,
database: Config.appSettings().database.database
});
var DB = (function () {
function _query(query, params, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
callback(null, err);
throw err;
}
connection.query(query, params, function (err, rows) {
connection.release();
if (!err) {
callback(rows);
}
else {
callback(null, err);
}
});
connection.on('error', function (err) {
connection.release();
callback(null, err);
throw err;
});
});
};
return {
query: _query
};
})();
module.exports = DB;
Just use it like that:
var DB = require('../dal/base.js');
DB.query("select * from tasks", null, function (data, error) {
callback(data, error);
});
Something along these lines, using ABC
import abc
class Shape(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def method_to_implement(self, input):
"""Method documentation"""
return
Also read this good tutorial: http://www.doughellmann.com/PyMOTW/abc/
You can also check out zope.interface which was used prior to introduction of ABC in python.
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
My way of testing this is quite simple, within each abstractUnitTest.java
. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.
SWIFT 4
Let's say you want to store a number from the array called cardButtons into cardNumber, you can do it this way:
let cardNumber = cardButtons.index(of: sender)
sender is the name of your button
A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.
For instance, place your property file in a new folder src/main/config, and add the following to your pom:
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
</build>
From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>my-config.properties</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
We can also use
return $this->db->count_all('table_name');
or
$this->db->from('table_name');
return $this->db->count_all_result();
or
return $this->db->count_all_result('table_name');
or
$query = $this->db->query('select * from tab');
return $query->num_rows();
\
does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.
Consider this command:
mysql -uroot \ -hlocalhost
If there is a space after \
, the line continuation will not work. The reason is that \
removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \
in this example.
Based on @Eyal Ben Dov's answer you may want to create a category to make it flexible to use within another apps of yours.
Obs.: I've updated his code to make compatible with iOS 7
-Header file
#import <UIKit/UIKit.h>
@interface UILabel (DynamicFontSize)
-(void) adjustFontSizeToFillItsContents;
@end
-Implementation file
#import "UILabel+DynamicFontSize.h"
@implementation UILabel (DynamicFontSize)
#define CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE 35
#define CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE 3
-(void) adjustFontSizeToFillItsContents
{
NSString* text = self.text;
for (int i = CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE; i>CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE; i--) {
UIFont *font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
CGRect rectSize = [attributedText boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (rectSize.size.height <= self.frame.size.height) {
self.font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
break;
}
}
}
@end
-Usage
#import "UILabel+DynamicFontSize.h"
[myUILabel adjustFontSizeToFillItsContents];
Cheers
You can display flex items inline, providing your assumption is based on wanting flexible inline items in the 1st place. Using flex implies a flexible block level element.
The simplest approach is to use a flex container with its children set to a flex property. In terms of code this looks like this:
.parent{
display: inline-flex;
}
.children{
flex: 1;
}
flex: 1
denotes a ratio, similar to percentages of a element's width.
Check these two links in order to see simple live Flexbox examples:
If you use the 1st example:
https://njbenjamin.com/flex/index_1.htm
You can play around with your browser console, to change the display
of the container element between flex
and inline-flex
.
Simple Solution:
Check whether in gen[generated Java Files], under your project package, there is a R.java file.
If no,
If yes,
To achieve this use following html:
<a href="www.mysite.com" onclick="make(event)">Item</a>
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
Here's an example that shows how table(.)
(or, more closely matching your desired output, data.frame(table(.))
does what it sounds like you are asking for.
Note also how to share reproducible sample data in a way that others can copy and paste into their session.
Here's the (reproducible) sample data:
mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L),
MONTH.YEAR = c("JAN. 2012", "JAN. 2012",
"FEB. 2012", "FEB. 2012",
"MAR. 2012"),
VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)),
.Names = c("ID", "MONTH.YEAR", "VALUE"),
class = "data.frame", row.names = c(NA, -5L))
mydf
# ID MONTH.YEAR VALUE
# 1 110 JAN. 2012 1000
# 2 111 JAN. 2012 2000
# 3 121 FEB. 2012 3000
# 4 131 FEB. 2012 4000
# 5 141 MAR. 2012 5000
Here's the calculation of the number of rows per group, in two output display formats:
table(mydf$MONTH.YEAR)
#
# FEB. 2012 JAN. 2012 MAR. 2012
# 2 2 1
data.frame(table(mydf$MONTH.YEAR))
# Var1 Freq
# 1 FEB. 2012 2
# 2 JAN. 2012 2
# 3 MAR. 2012 1
The only real solution I could find is this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = ...; // Instantiate with a "common" method you'll use again in cellForRowAtIndexPath:
return cell.frame.size.height;
}
This works and allows not to have an horrible switch/if duplicating the logic already in the StoryBoard. Not sure about performance but I guess when arriving in cellForRow:
the cell being already initalized it's as fast. Of course there are probably collateral damages here, but it looks like it works fine for me here.
I also posted this here: https://devforums.apple.com/message/772464
EDIT: Ortwin Gentz reminded me that heightForRowAtIndexPath:
will be called for all cells of the TableView, not only the visible ones. Sounds logical since iOS needs to know the total height to be able to show the right scrollbars. It means it's probably fine on small TableViews (like 20 Cells) but forget about it on a 1000 Cell TableView.
Also, the previous trick with XML: Same as first comment for me. The correct value was already there.
Since this appears to be a simple parent/child relationship between pets
and pets_activities
, you would be better off creating your foreign key constraint with a deleting cascade.
That way, when a pets
row is deleted, the pets_activities
rows associated with it are automatically deleted as well.
Then your query becomes a simple:
delete from `pets`
where `order` > :order
and `pet_id` = :pet_id
Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :
public static long integerToLong (int minute ){
int delay = minute*1000;
long diff = (long) delay;
return diff ;
}
Note that for "Untitled" editor ("Untitled-1
", "Untitled-2
"), you now can set the language in the settings.
The previous setting was:
"files.associations": {
"untitled-*": "javascript"
}
This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-
"
See "Untitled editor improvements"
Regarding the associated language for those "Untitled" editors:
By default, untitled files do not have a specific language mode configured.
VS Code has a setting,
files.defaultLanguage
, to configure a default language for untitled files.With this release, the setting can take a new value
{activeEditorLanguage}
that will dynamically use the language mode of the currently active editor instead of a fixed default.In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:
And see workbench.editor.untitled.labelFormat
in VSCode 1.43.
AFAIK the session object is not accessible at the client, as it is stored at the web server. However, the session id is stored as a Cookie and it lets the web server track the user's session.
To prevent session hijacking using the session id, you can store a hashed string inside the session object, made using a combination of two attributes, remote addr and remote port, that can be accessed at the web server inside the request object. These attributes tie the user session to the browser where the user logged in.
If the user logs in from another browser or an incognito mode on the same system, the IP addr would remain the same, but the port will be different. Therefore, when the application is accessed, the user would be assigned a different session id by the web server.
Below is the code I have implemented and tested by copying the session id from one session into another. It works quite well. If there is a loophole, let me know how you simulated it.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String sessionKey = (String) session.getAttribute("sessionkey");
String remoteAddr = request.getRemoteAddr();
int remotePort = request.getRemotePort();
String sha256Hex = DigestUtils.sha256Hex(remoteAddr + remotePort);
if (sessionKey == null || sessionKey.isEmpty()) {
session.setAttribute("sessionkey", sha256Hex);
// save mapping to memory to track which user attempted
Application.userSessionMap.put(sha256Hex, remoteAddr + remotePort);
} else if (!sha256Hex.equals(sessionKey)) {
session.invalidate();
response.getWriter().append(Application.userSessionMap.get(sessionKey));
response.getWriter().append(" attempted to hijack session id ").append(request.getRequestedSessionId());
response.getWriter().append("of user ").append(Application.userSessionMap.get(sha256Hex));
return;
}
response.getWriter().append("Valid Session\n");
}
I used the SHA-2 algorithm to hash the value using the example given at SHA-256 Hashing at baeldung
Looking forward to your comments.
According to the website, sizeof()
is an alias of count()
, so they should be running the same code. Perhaps sizeof()
has a little bit of overhead because it needs to resolve it to count()
? It should be very minimal though.
Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.
Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.
Sorry, now I've read what you expected better, so I'm updating the answer.
Based on the HTML5 Specs from W3C, nothing is wrong. I created this JSFiddle test and it's behaving correctly based on the specs (for those browsers based on the specs, like Chrome 11 and Firefox 4):
<form>_x000D_
<input type="checkbox" name="q" id="a-0" required autofocus>_x000D_
<label for="a-0">a-1</label>_x000D_
<br>_x000D_
_x000D_
<input type="checkbox" name="q" id="a-1" required>_x000D_
<label for="a-1">a-2</label>_x000D_
<br>_x000D_
_x000D_
<input type="checkbox" name="q" id="a-2" required>_x000D_
<label for="a-2">a-3</label>_x000D_
<br>_x000D_
_x000D_
<input type="submit">_x000D_
</form>
_x000D_
I agree that it isn't very usable (in fact many people have complained about it in the W3C's mailing lists).
But browsers are just following the standard's recommendations, which is correct. The standard is a little misleading, but we can't do anything about it in practice. You can always use JavaScript for form validation, though, like some great jQuery validation plugin.
Another approach would be choosing a polyfill that can make (almost) all browsers interpret form validation rightly.
Selenium is the best for scraping JS and Ajax content.
Check this article for extracting data from the web using Python
$ pip install selenium
Then download Chrome webdriver.
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("https://www.python.org/")
nav = browser.find_element_by_id("mainnav")
print(nav.text)
Easy, right?
no. You can use UDF in which you can pass parameters.
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
A few others have posted answers. There are some obvious problems, like it returns false
when the Regex passes, and the ^
and $
operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).
Besides that, the issue is just a typo.
Change this...
var reWhiteSpace = new RegExp("/^\s+$/");
To this...
var reWhiteSpace = new RegExp("\\s+");
When using a regex within RegExp()
, you must do the two following things...
/
brackets.\\s
in place of \s
, etc.Full working demo from source code....
$(document).ready(function(e) { function hasWhiteSpace(s) {
var reWhiteSpace = new RegExp("\\s+");
// Check for white space
if (reWhiteSpace.test(s)) {
//alert("Please Check Your Fields For Spaces");
return 'true';
}
return 'false';
}
$('#whitespace1').html(hasWhiteSpace(' '));
$('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
div {_x000D_
background: inherit;_x000D_
width: 250px;_x000D_
height: 350px;_x000D_
position: absolute;_x000D_
overflow: hidden; /* Adding overflow hidden */_x000D_
}_x000D_
_x000D_
div:before {_x000D_
content: ‘’;_x000D_
width: 300px;_x000D_
height: 400px;_x000D_
background: inherit;_x000D_
position: absolute;_x000D_
left: -25px; /* Giving minus -25px left position */_x000D_
right: 0;_x000D_
top: -25px; /* Giving minus -25px top position */_x000D_
bottom: 0;_x000D_
box-shadow: inset 0 0 0 200px rgba(255, 255, 255, 0.3);_x000D_
filter: blur(10px);_x000D_
}
_x000D_
You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.
Tl;dr of the blog post:
import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))
gives you
utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ? ?
protected void sendJson(final String play, final String prop) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the childThread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.44:80");
json.put("play", play);
json.put("Properties", prop);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch (Exception e) {
e.printStackTrace();
showMessage("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The difference can be demonstrated by this example:
generate a matrix
>>> A = numpy.matrix(numpy.ones((3,3)))
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.array
to modify A
. Doesn't work because you are modifying a copy
>>> numpy.array(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.asarray
to modify A
. It worked because you are modifying A
itself
>>> numpy.asarray(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Hope this helps!
if its a dict, flask can return it directly (Version 1.0.2)
def summary():
d = make_summary()
return d, 200
I would use printf instead of echo because it's more reliable and processes formatting such as new line \n
properly.
This example produces an output similar to echo in previous examples:
printf "hello world" >> read.txt
cat read.txt
hello world
However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent
printf "hello\nworld" >> read.txt
cat read.txt
hello
world
Fn + Up/Down can scroll Terminal in Mac OS X 10.11
I think what you need might be simply:
\d( \w)?
Note that your regex would have worked too if it was written as \d \w|\d
instead of \d|\d \w
.
This is because in your case, once the regex matches the first option, \d
, it ceases to search for a new match, so to speak.
SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.
DO NOT EDIT studio.vmoptions
,It may not work.
In gradle.properties
file (in app directory) add this :
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx7g -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
It's just an addition, with this you can get the data into CSV format
import sys,os
try:
import pandas as pd
except:
os.system("pip3 install pandas")
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv" #I want to get only csv files
pattern = "*.*" # Note: Use this pattern to get all types of files and folders
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch(name, pattern):
lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")
By using document.getElementById()
function you don't have to pass #
before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo: JSFiddle
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
From version 2.13.0
of Dart Code, emulators can be launched directly from within Code but This feature relies on support from the Flutter tools which means it will only show emulators when using a very recent Flutter SDK. Flutter’s master channel already has this change, but it may take a little longer to filter through to the dev and beta channels.
I tested this feature and worked very well on flutter version 0.5.6-pre.61 (master channel)
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd
and type hostname
(example result: LAPTOP-G666P000
, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E
> right click 'This PC'
> press N
(It's Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U:
or G:
or Z:
or whatever you want
Example Address: \\LAPTOP-G666P000\c$\Users\username\
Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button>
like in your question
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
related2: I have used http://localhost/c$
etc before on some WAMP/apache servers too before, you can use .htaccess
for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google
For reference, cursor.rowcount
will only return on CREATE
, UPDATE
and DELETE
statements:
| rowcount
| This read-only attribute specifies the number of rows the last DML statement
| (INSERT, UPDATE, DELETE) affected. This is set to -1 for SELECT statements.
You have it exactly right, all you have to do is set selectedIndex in your ng-click.
ng-click="selectedIndex = 1"
Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.
<div id="sidebar" ng-init="partial = 'main'">
<div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
</div>
and this in my controller.
$scope.router = function(endpoint) {
$location.path("/" + ($scope.partial = endpoint));
};
I already have used Reportlab in one project.
I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.
So I cleared the .Net Temp folder.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.
My issue was sorted.
comdlg32.dll is not really a COM dll (you can't register it).
What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx
.
ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`)
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
There is a great moment
method called fromNow()
that will return the time from a specific time in nice human readable form, like this:
moment('2019-04-30T07:30:53.000Z').fromNow() // an hour ago || a day ago || 10 days ago
Or if you want that between two specific dates you can use:
var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "a day ago"
Taken from the Docs:
Use "%%"
. The man page describes this requirement:
%
A '%' is written. No argument is converted. The complete conversion specification is '%%
'.
Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!
My best advice would be that there is no standard tree data structure because there are so many ways you could implement it that it would be impossible to cover all bases with one solution. The more specific a solution, the less likely it is applicable to any given problem. I even get annoyed with LinkedList - what if I want a circular linked list?
The basic structure you'll need to implement will be a collection of nodes, and here are some options to get you started. Let's assume that the class Node is the base class of the entire solution.
If you need to only navigate down the tree, then a Node class needs a List of children.
If you need to navigate up the tree, then the Node class needs a link to its parent node.
Build an AddChild method that takes care of all the minutia of these two points and any other business logic that must be implemented (child limits, sorting the children, etc.)
Normally you use the statement
String userHome = System.getProperty( "user.home" );
to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.
There may be access problems you might want to avoid by using this workaround (Using a security policy file)
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb