I'm not entirely surprised that your example exhibits no strange behaviour. Try copying str1
to str1+2
instead and see what happens then. (May not actually make a difference, depends on compiler/libraries.)
In general, memcpy is implemented in a simple (but fast) manner. Simplistically, it just loops over the data (in order), copying from one location to the other. This can result in the source being overwritten while it's being read.
Memmove does more work to ensure it handles the overlap correctly.
EDIT:
(Unfortunately, I can't find decent examples, but these will do). Contrast the memcpy and memmove implementations shown here. memcpy just loops, while memmove performs a test to determine which direction to loop in to avoid corrupting the data. These implementations are rather simple. Most high-performance implementations are more complicated (involving copying word-size blocks at a time rather than bytes).
Another approach instead of saving the file on the server and retrieving it, is to use .NET 4.0+ ObjectCache with a short expiration until the second Action (at which time it can be definitively dumped). The reason that I want to use JQuery Ajax to do the call, is that it is asynchronous. Building my dynamic PDF file takes quite a bit of time, and I display a busy spinner dialog during that time (it also allows other work to be done). The approach of using the data returned in the "success:" to create a Blob does not work reliably. It depends on the content of the PDF file. It is easily corrupted by data in the response, if it is not completely textual which is all that Ajax can handle.
List comprehension will lead you to a solution.
But the right way to copy a object in python is using python module copy - Shallow and deep copy operations.
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
If instead of this,
import copy
l=[1,2,3,0,0,1]
duplicate_l = copy.copy(l)
for i in range(0,len(l)):
if l[i]==0:
m.remove(i)
l = m
Then, your own code would have worked. But for optimization, list comprehension is a good solution.
Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach
is the preferred way of doing it, I like to use an AnyRef
pimp that allows me to write:
getObject ifNotNull ( QueueManager.add(_) )
I find it reads better.
And, in a more general way, I sometimes write
val returnVal = getObject ifNotNull { obj =>
returnSomethingFrom(obj)
} otherwise {
returnSomethingElse
}
... replacing ifNotNull with ifSome if I'm dealing with an Option
. I find it clearer than first wrapping in an option and then pattern-matching it.
(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0
/Otherwise1
classes.)
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb_to_gray(img):
grayImage = np.zeros(img.shape)
R = np.array(img[:, :, 0])
G = np.array(img[:, :, 1])
B = np.array(img[:, :, 2])
R = (R *.299)
G = (G *.587)
B = (B *.114)
Avg = (R+G+B)
grayImage = img
for i in range(3):
grayImage[:,:,i] = Avg
return grayImage
image = mpimg.imread("your_image.png")
grayImage = rgb_to_gray(image)
plt.imshow(grayImage)
plt.show()
Fixed positioning will do what you need:
#main
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
}
From the documentation for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
From the documentation for next():
A complete token is preceded and followed by input that matches the delimiter pattern.
Pure JS solution is as follows:
function clearForm(myFormElement) {
var elements = myFormElement.elements;
myFormElement.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
The best and easiest way is auto-py-to-exe for sure, and I have given all the steps and red flags below which will take you just 5 mins to get a final .exe file as you don't have to learn anything to use it.
1.) It may not work for python 3.9 on some devices I guess.
2.) While installing python, if you had selected 'add python 3.x to path', open command prompt from start menu and you will have to type pip install auto-py-to-exe
to install it. You will have to press enter on command prompt to get the result of the line that you are typing.
3.) Once it is installed, on command prompt itself, you can simply type just auto-py-to-exe
to open it. It will open a new window. It may take up to a minute the first time. Also, closing command prompt will close auto-py-to-exe also so don't close it till you have your .exe file ready.
4.) There will be buttons for everything you need to make a .exe file and the screenshot of it is shared below. Also, for the icon, you need a .ico file instead of an image so to convert it, you can use https://convertio.co/
5.) If your script uses external files, you can add them through auto-py-to-exe and in the script, you will have to do some changes to their path. First, you have to write import sys
if not written already, second, you have to make a variable for eg, location=getattr(sys,"_MEIPASS",".")+"/"
, third, the location of example.png would be location+"/example.png"
if it is not in any folder.
6.) If it is showing any error, it may probably be because of a module called setuptools not being at the latest version. To upgrade it to the latest version, on command prompt, you will have to write pip install --upgrade setuptools
. Also, in the script, writing import setuptools
may help. If the version of setuptools is more than 50.0.0 then everything should be fine.
7.) After all these steps, in auto-py-to-exe, when the conversion is complete, the .exe file will be in the folder that you would have chosen (by default, it is 'c:/users/name/output') or it would have been removed by your antivirus if you have one. Every antivirus has different methods to restore a file so just experiment if you don't know.
Here is how the simple GUI of auto-py-to-exe can be used to make a .exe file.
you can download .whl in LFD . Then use "pip install ***.whl" in CMD
This is the best solution I ever seen. Its more generic.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="100"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
I finally got this to work in a Bash script used to insert a unique timestamp in each item in an RSS feed:
sed "1,/====RSSpermalink====/s/====RSSpermalink====/${nowms}/" \
production-feed2.xml.tmp2 > production-feed2.xml.tmp.$counter
It changes the first occurrence only.
${nowms}
is the time in milliseconds set by a Perl script, $counter
is a counter used for loop control within the script, \
allows the command to be continued on the next line.
The file is read in and stdout is redirected to a work file.
The way I understand it, 1,/====RSSpermalink====/
tells sed when to stop by setting a range limitation, and then s/====RSSpermalink====/${nowms}/
is the familiar sed command to replace the first string with the second.
In my case I put the command in double quotation marks becauase I am using it in a Bash script with variables.
Use a CASE
statement and do it like this:
SELECT
T1.Id [Id]
,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
TABLE1 [T1]
LEFT OUTER JOIN
TABLE2 [T2]
ON
T2.Id = T1.Id
Many of you must be landing here to find a solution for opaque border instead of a transparent one. In that case you can use rgba
, where a
stands for alpha
.
.your_class {
height: 100px;
width: 100px;
margin: 100px;
border: 10px solid rgba(255,255,255,.5);
}
Here, you can change the opacity
of the border
from 0-1
If you simply want a complete transparent border, the best thing to use is transparent
, like border: 1px solid transparent;
In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}.
you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.
Explanation: In project urls.py path('', include('blog.urls',namespace='blog')),
and in app's urls.py you have to specify the app_name. like app_name = 'blog'
. namespace_name is the app_name.
JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....
Have a look on this tutorial on how to make dialogs.
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
for foo in *.gz
do
tar xf "$foo"
rm "$foo"
done
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...
Say I have the following DataFrame
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
You could count a single column by
df.A.count()
#or
df['A'].count()
both evaluate to 5.
The cool thing (or one of many w.r.t. pandas
) is that if you have NA
values, count takes that into consideration.
So if I did
df['A'][1::2] = np.NAN
df.count()
The result would be
A 3
B 5
Use the DataGridView.ReadOnly
property
The code in the MSDN example illustrates the use of this property in a DataGridView
control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.
Observe these settings in the sample code:
// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.DisableResizing;
At any stage of maven build life cycle, all the previous goals are performed.
Ex: mvn install will invoke mvn validate, mvn compile, mvn test, mvn package etc.
For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.
If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it
Then my understanding is that it cant connect for one of the following below. Now which..
1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.
2) Error comes from a .php file. So, check your dbconnect.php.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>
Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!
3) Error comes when you login to phpmyadmin. So, check your my.ini.
Open my.ini by left clicking the green icon --> click MariaDB -->
; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock
; Here follows entries for some specific programs
; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock
Make sure the ports match the port MariaDB is being testing on. Then finally..
[mysqld]
port = 3307
At the bottom of my.ini, make sure this port matches as well.
4) 1-3 done? restart your WAMP and cross your fingers!
Try this code:
<input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}"
title="Phone number with 7-9 and remaing 9 digit with 0-9">
This code will inputs only in the following format:
9238726384 (starting with 9 or 8 or 7 and other 9 digit using any number)
8237373746
7383673874
Incorrect format:
2937389471(starting not with 9 or 8 or 7)
32796432796(more than 10 digit)
921543(less than 10 digit)
I suspect the condition you are looking for is DUP_VAL_ON_INDEX
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')
var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.
thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
Take a look at ISO 11179-5: Naming and identification principles You can get it here: http://metadata-standards.org/11179/#11179-5
I blogged about it a while back here: ISO-11179 Naming Conventions
First, create the derived value:
df.loc[0, 'C'] = df.loc[0, 'D']
Then iterate through the remaining rows and fill the calculated values:
for i in range(1, len(df)):
df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']
Index_Date A B C D
0 2015-01-31 10 10 10 10
1 2015-02-01 2 3 23 22
2 2015-02-02 10 60 290 280
Do a (recursive) Revert operation from a level above the directory you deleted.
get HTML from UIWebView`
let content = uiWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")
set HTML into UIWebView
//Do not forget to extend a class from `UIWebViewDelegate` and nil the delegate
func someFunction() {
let uiWebView = UIWebView()
uiWebView.loadHTMLString("<html><body></body></html>", baseURL: nil)
uiWebView.delegate = self as? UIWebViewDelegate
}
func webViewDidFinishLoad(_ webView: UIWebView) {
//ready to be processed
}
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset
to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The git diff
command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.
If you had a branch named origin
, the commit hash at tip of the branch would have been used if you supplied origin
to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin
.
An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:
git diff origin/<branchname>
git diff <branchname> origin/<branchname>
Edit: Having read further, I realise I'm slightly wrong, git diff origin
is shorthand for diffing against the head of the specified remote, so git diff origin
= git diff origin/HEAD
(compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)
It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.
Running git branch -r
will show you if origin/HEAD
is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>
).
beside all other good answers, this could happen if you use merge
to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following example
merge(A);
B.setA(A);
persist(B);
In this case, you merge A
but forget to use merged object of A
. to solve the problem you must rewrite the code like this.
A=merge(A);//difference is here
B.setA(A);
persist(B);
It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.
I did it and my problem solved.
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);
The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.
If you cannot detach the production db you should use backup and restore.
You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.
You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.
This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.
If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...
(Manually repair, or, restore backups)
Specify a height and a width:
.header-shadow{
background-image: url('../images/header-shade.jpg');
height: 10px;
width: 10px;
}
Or shorter:
$("form#data").submit(function() {
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
i use this in linux :
sed -i 's/utf8mb4/utf8/g' your_file.sql
sed -i 's/utf8_unicode_ci/utf8_general_ci/g' your_file.sql
sed -i 's/utf8_unicode_520_ci/utf8_general_ci/g' your_file.sql
then restore your_file.sql
mysql -u yourdBUser -p yourdBPasswd yourdB < your_file.sql
Emmanuel,
I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
To get a list of columns you can simply use:
.schema tablename
I am working on TF-2.1 and torch, so I don't want to specific this automacit choosing in any ML frame. I just use original nvidia-smi and os.environ to get a vacant gpu.
def auto_gpu_selection(usage_max=0.01, mem_max=0.05):
"""Auto set CUDA_VISIBLE_DEVICES for gpu
:param mem_max: max percentage of GPU utility
:param usage_max: max percentage of GPU memory
:return:
"""
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
log = str(subprocess.check_output("nvidia-smi", shell=True)).split(r"\n")[6:-1]
gpu = 0
# Maximum of GPUS, 8 is enough for most
for i in range(8):
idx = i*3 + 2
if idx > log.__len__()-1:
break
inf = log[idx].split("|")
if inf.__len__() < 3:
break
usage = int(inf[3].split("%")[0].strip())
mem_now = int(str(inf[2].split("/")[0]).strip()[:-3])
mem_all = int(str(inf[2].split("/")[1]).strip()[:-3])
# print("GPU-%d : Usage:[%d%%]" % (gpu, usage))
if usage < 100*usage_max and mem_now < mem_max*mem_all:
os.environ["CUDA_VISIBLE_EVICES"] = str(gpu)
print("\nAuto choosing vacant GPU-%d : Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]\n" %
(gpu, mem_now, mem_all, usage))
return
print("GPU-%d is busy: Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]" %
(gpu, mem_now, mem_all, usage))
gpu += 1
print("\nNo vacant GPU, use CPU instead\n")
os.environ["CUDA_VISIBLE_EVICES"] = "-1"
If I can get any GPU, it will set CUDA_VISIBLE_EVICES to BUSID of that gpu :
GPU-0 is busy: Memory:[5738MiB/11019MiB] , GPU-Util:[60%]
GPU-1 is busy: Memory:[9688MiB/11019MiB] , GPU-Util:[78%]
Auto choosing vacant GPU-2 : Memory:[1MiB/11019MiB] , GPU-Util:[0%]
else, set to -1 to use CPU:
GPU-0 is busy: Memory:[8900MiB/11019MiB] , GPU-Util:[95%]
GPU-1 is busy: Memory:[4674MiB/11019MiB] , GPU-Util:[35%]
GPU-2 is busy: Memory:[9784MiB/11016MiB] , GPU-Util:[74%]
No vacant GPU, use CPU instead
Note: Use this function before you import any ML frame that require a GPU, then it can automatically choose a gpu. Besides, it's easy for you to set multiple tasks.
Remember to set the endDate to the created event, it is mandatory.
Otherwise it will fail (almost silently) with this error:
"Error Domain=EKErrorDomain Code=3 "No end date has been set." UserInfo={NSLocalizedDescription=No end date has been set.}"
The complete working code for me is:
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *calendarEvent = [EKEvent eventWithEventStore:store];
calendarEvent.title = [NSString stringWithFormat:@"CEmprendedor: %@", _event.name];
calendarEvent.startDate = _event.date;
// 5 hours of duration, we must add the duration of the event to the API
NSDate *endDate = [_event.date dateByAddingTimeInterval:60*60*5];
calendarEvent.endDate = endDate;
calendarEvent.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:calendarEvent span:EKSpanThisEvent commit:YES error:&err];
self.savedEventId = calendarEvent.eventIdentifier; //saving the calendar event id to possibly deleted them
}];
Based off your code, i created this Fiddle
You need to use
var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];
if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.
git rev-list --all | (
while read revision; do
git grep -F 'password' $revision
done
)
Use a table variable or a temporary table.
As has been mentioned before, a cursor is a last resort. Mostly because it uses lots of resources, issues locks and might be a sign you're just not understanding how to use SQL properly.
Side note: I once came across a solution that used cursors to update rows in a table. After some scrutiny, it turned out the whole thing could be replaced with a single UPDATE command. However, in this case, where a stored procedure should be executed, a single SQL-command won't work.
Create a table variable like this (if you're working with lots of data or are short on memory, use a temporary table instead):
DECLARE @menus AS TABLE (
id INT IDENTITY(1,1),
parent NVARCHAR(128),
child NVARCHAR(128));
The id
is important.
Replace parent
and child
with some good data, e.g. relevant identifiers or the whole set of data to be operated on.
Insert data in the table, e.g.:
INSERT INTO @menus (parent, child)
VALUES ('Some name', 'Child name');
...
INSERT INTO @menus (parent,child)
VALUES ('Some other name', 'Some other child name');
Declare some variables:
DECLARE @id INT = 1;
DECLARE @parentName NVARCHAR(128);
DECLARE @childName NVARCHAR(128);
And finally, create a while loop over the data in the table:
WHILE @id IS NOT NULL
BEGIN
SELECT @parentName = parent,
@childName = child
FROM @menus WHERE id = @id;
EXEC myProcedure @parent=@parentName, @child=@childName;
SELECT @id = MIN(id) FROM @menus WHERE id > @id;
END
The first select fetches data from the temporary table. The second select updates the @id. MIN
returns null if no rows were selected.
An alternative approach is to loop while the table has rows, SELECT TOP 1
and remove the selected row from the temp table:
WHILE EXISTS(SELECT 1 FROM @menuIDs)
BEGIN
SELECT TOP 1 @menuID = menuID FROM @menuIDs;
EXEC myProcedure @menuID=@menuID;
DELETE FROM @menuIDs WHERE menuID = @menuID;
END;
no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)
Something else you can use is isnull
:
isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp()
.
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
The difference appears when the special parameters are quoted. Let me illustrate the differences:
$ set -- "arg 1" "arg 2" "arg 3"
$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3
$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3
$ for word in "$*"; do echo "$word"; done
arg 1 arg 2 arg 3
$ for word in "$@"; do echo "$word"; done
arg 1
arg 2
arg 3
one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:
$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3
and in bash, "$@"
is the "default" list to iterate over:
$ for word; do echo "$word"; done
arg 1
arg 2
arg 3
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();
i think the easiest way is to use the Adobe PDF reader COM Component
i hope this helps
After adding the cordova-plugin-whitelist, you must tell your application to allow access all the web-page links or specific links, if you want to keep it specific.
You can simply add this to your config.xml, which can be found in your application's root directory:
Recommended in the documentation:
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
From the plugin's documentation:
Navigation Whitelist
Controls which URLs the WebView itself can be navigated to. Applies to top-level navigations only.
Quirks: on Android it also applies to iframes for non-http(s) schemes.
By default, navigations only to file:// URLs, are allowed. To allow other other URLs, you must add tags to your config.xml:
<!-- Allow links to example.com --> <allow-navigation href="http://example.com/*" /> <!-- Wildcards are allowed for the protocol, as a prefix to the host, or as a suffix to the path --> <allow-navigation href="*://*.example.com/*" /> <!-- A wildcard can be used to whitelist the entire network, over HTTP and HTTPS. *NOT RECOMMENDED* --> <allow-navigation href="*" /> <!-- The above is equivalent to these three declarations --> <allow-navigation href="http://*/*" /> <allow-navigation href="https://*/*" /> <allow-navigation href="data:*" />
I have made a cheat-sheet I think can be useful to others. In all examples, you can remove the format_sql
property if you want to keep the logged queries on a single line (no pretty printing).
Pretty print SQL queries to standard out without parameters of prepared statements and without optimizations of a logging framework:
application.properties
file:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
application.yml
file:
spring:
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
Pretty print SQL queries with parameters of prepared statements using a logging framework:
application.properties
file:
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
application.yml
file:
spring:
jpa:
properties:
hibernate:
format_sql: true
logging:
level:
org:
hibernate:
SQL: DEBUG
type:
descriptor:
sql:
BasicBinder: TRACE
Pretty print SQL queries without parameters of prepared statements using a logging framework:
application.properties
file:
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
application.yml
file:
spring:
jpa:
properties:
hibernate:
format_sql: true
logging:
level:
org:
hibernate:
SQL: DEBUG
Source (and more details): https://www.baeldung.com/sql-logging-spring-boot
The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality.
http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html
I thought TemplateBinding does not support Freezable types (which includes brush objects). To get around the problem. One can make use of TemplatedParent
The infix operator %>%
is not part of base R, but is in fact defined by the package magrittr
(CRAN) and is heavily used by dplyr
(CRAN).
It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.
What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris
gets passed to head()
:
library(magrittr)
iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Thus, iris %>% head()
is equivalent to head(iris)
.
Often, %>%
is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris
is passed to head()
, then the result of that is passed to summary()
.
iris %>% head() %>% summary()
Thus iris %>% head() %>% summary()
is equivalent to summary(head(iris))
. Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.
import os
import pickle
PICKLE_FILE = 'pickle.dat'
def main():
# append data to the pickle file
add_to_pickle(PICKLE_FILE, 123)
add_to_pickle(PICKLE_FILE, 'Hello')
add_to_pickle(PICKLE_FILE, None)
add_to_pickle(PICKLE_FILE, b'World')
add_to_pickle(PICKLE_FILE, 456.789)
# load & show all stored objects
for item in read_from_pickle(PICKLE_FILE):
print(repr(item))
os.remove(PICKLE_FILE)
def add_to_pickle(path, item):
with open(path, 'ab') as file:
pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)
def read_from_pickle(path):
with open(path, 'rb') as file:
try:
while True:
yield pickle.load(file)
except EOFError:
pass
if __name__ == '__main__':
main()
You can use this:
$(document).ready(function() {
$("#tabs").tabs();
$('#action').click(function() {
var selected = $("#tabs").tabs("option", "selected");
$("#tabs").tabs("option", "selected", selected + 1);
});
});
Also consider changing the input type as button
instead of submit
unless you want to submit the page.
I used to meet the similar problem because 'localhost' was not available on server when it restarted network service, e.g. 'ifdown -a' but followed by only 'ifup -eo1'. Besides server is not listening to the port, you can also check 'localhost' is available or not.
ps: Post it just hope someone who has the similar problem may benefit.
Remove conn.commit from Register.java
In your jsp change action to :<form name="registrationform" action="Register" method="post">
Approach i used some years ago -
We need a jsp file , a servlet java file and a filter java file.
Give access of jsp file to user. User type url of jsp file .
Case 1 -
Using Printwriter , it will render the response to user .
Meanwhile, Servlet will create a key file .
When servlet try to execute the xxxx.js file within it , Filter
will activate and will detect key file exist and hence delete key
file .
Thus one cycle is over.
In short ,key file will created by server and will be immediatly deleted by filter .
This will happen upon every hit .
Case 2 -
Instead of File creation , one may use setting value in session variable .
@Adrian Cornish's answer is correct. However, there is another caveat to dropping an existing primary key. If that primary key is being used as a foreign key by another table you will get an error when trying to drop it. In some versions of mysql the error message there was malformed (as of 5.5.17, this error message is still
alter table parent drop column id;
ERROR 1025 (HY000): Error on rename of
'./test/#sql-a04_b' to './test/parent' (errno: 150).
If you want to drop a primary key that's being referenced by another table, you will have to drop the foreign key in that other table first. You can recreate that foreign key if you still want it after you recreate the primary key.
Also, when using composite keys, order is important. These
1) ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
and
2) ALTER TABLE provider ADD PRIMARY KEY(person,thing,place);
are not the the same thing. They both enforce uniqueness on that set of three fields, however from an indexing standpoint there is a difference. The fields are indexed from left to right. For example, consider the following queries:
A) SELECT person, place, thing FROM provider WHERE person = 'foo' AND thing = 'bar';
B) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz';
C) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz' AND thing = 'bar';
D) SELECT person, place, thing FROM provider WHERE place = 'baz' AND thing = 'bar';
B can use the primary key index in ALTER statement 1
A can use the primary key index in ALTER statement 2
C can use either index
D can't use either index
A uses the first two fields in index 2 as a partial index. A can't use index 1 because it doesn't know the intermediate place portion of the index. It might still be able to use a partial index on just person though.
D can't use either index because it doesn't know person.
See the mysql docs here for more information.
This one worked for me
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
Button1_Click
End If
End Sub
Install the 2007 version, it seems that if you install the version opposite to the version of Office you are using you can make it work.
http://www.microsoft.com/en-us/download/details.aspx?id=23734
All these answers seem a bit heavy to me.
If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?
for (int i = 0; i < str.length();i++) {
if (str[i] == '\n') {
str[i] = ' ';
}
}
There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.
The fastest way I found is that:
import java.lang.reflect.Method;
public class TraceHelper {
// save it static to have it available on every call
private static Method m;
static {
try {
m = Throwable.class.getDeclaredMethod("getStackTraceElement",
int.class);
m.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMethodName(final int depth) {
try {
StackTraceElement element = (StackTraceElement) m.invoke(
new Throwable(), depth + 1);
return element.getMethodName();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
It accesses the native method getStackTraceElement(int depth) directly. And stores the accessible Method in a static variable.
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)
You can use purrr
as well, which is similar to apply
family functions:
as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)
As per machineAddict's comment, as of version 2 and later, year, month and day
have been replaced by defaultDate
, which is a Moment, supporting constructors such as an ISO 8601
date string or a Unix Epoch.
So e.g. to initialize the calendar with a given date:
$('#calendar').fullCalendar({
defaultDate: moment('2014-09-01'),
...
});
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
The following solution worked for me the best. Since I'm relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/
Here's the code:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden; /* Disable scrollbars */
display: block; /* No floating content on sides */
}
</style>
</head>
<body>
<canvas id='c' style='position:absolute; left:0px; top:0px;'>
</canvas>
<script>
(function() {
var
// Obtain a reference to the canvas element using its id.
htmlCanvas = document.getElementById('c'),
// Obtain a graphics context on the canvas element for drawing.
context = htmlCanvas.getContext('2d');
// Start listening to resize events and draw canvas.
initialize();
function initialize() {
// Register an event listener to call the resizeCanvas() function
// each time the window is resized.
window.addEventListener('resize', resizeCanvas, false);
// Draw canvas border for the first time.
resizeCanvas();
}
// Display custom canvas. In this case it's a blue, 5 pixel
// border that resizes along with the browser window.
function redraw() {
context.strokeStyle = 'blue';
context.lineWidth = '5';
context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
}
// Runs each time the DOM window resize event fires.
// Resets the canvas dimensions to match window,
// then draws the new borders accordingly.
function resizeCanvas() {
htmlCanvas.width = window.innerWidth;
htmlCanvas.height = window.innerHeight;
redraw();
}
})();
</script>
</body>
</html>
The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.
You need to implement a Comparator<Double[]>
like so:
public static void main(String[] args) throws IOException {
final Double[][] doubles = new Double[][]{{5.0, 4.0}, {1.0, 1.0}, {4.0, 6.0}};
final Comparator<Double[]> arrayComparator = new Comparator<Double[]>() {
@Override
public int compare(Double[] o1, Double[] o2) {
return o1[0].compareTo(o2[0]);
}
};
Arrays.sort(doubles, arrayComparator);
for (final Double[] arr : doubles) {
System.out.println(Arrays.toString(arr));
}
}
Output:
[1.0, 1.0]
[4.0, 6.0]
[5.0, 4.0]
$(this).css('marginBottom').replace('px','')
Use
app:breakStrategy="simple"
inAppCompatTextView
, it will control over paragraph layout.
It has three constant values
Designing in your TextView xml
<android.support.v7.widget.AppCompatTextView
android:id="@+id/textquestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:scrollHorizontally="false"
android:text="Your Question Display Hear....Your Question Display Hear....Your Question Display Hear....Your Question Display Hear...."
android:textColor="@android:color/black"
android:textSize="20sp"
android:textStyle="bold"
app:breakStrategy="simple" />
If your current minimum api level is 23 or more then in Coding
yourtextview.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE);
For more refrence refer this BreakStrategy
You can use easily to dump selected tables using MYSQLWorkbench tool
,individually or group of tables at one dump then import it as follow: also u can add host information if u are running it in your local by adding -h IP.ADDRESS.NUMBER after-u username
mysql -u root -p databasename < dumpfileFOurTableInOneDump.sql
Initializing a vector having struct, class or Union can be done this way
std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);
DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.
Set a flag on hover:
var over = false;
$('#elem').hover(function() {
over = true;
},
function () {
over = false;
});
Then just check your flag.
This little function has served me well:
//goto view:
//useage - $scope.gotoView("your/path/here", boolean_open_in_new_window)
$scope.gotoView = function (st_view, is_newWindow)
{
console.log('going to view: ' + '#/' + st_view, $window.location);
if (is_newWindow)
{
$window.open($window.location.origin + $window.location.pathname + '' + '#/' + st_view, '_blank');
}
else
{
$window.location.hash = '#/' + st_view;
}
};
You dont need the full path, just the view you are switching to
If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.
This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.
File name without file extension when you don't know that extension:
$basename = substr($filename, 0, strrpos($filename, "."));
You can iterate using the index access,
To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase
method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
To set up system wide scope you need to use the
/etc/environment file sudo gedit /etc/environment
is the location where you can define any environment variable. It can be visible in the whole system scope. After variable is defined system need to be restarted.
EXAMPLE :
sudo gedit /etc/environment
Add like following :
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
JAVA_HOME="/opt/jdk1.6.0_45/"
Here is the site you can find more : http://peesquare.com/blogs/environment-variable-setup-on-ubuntu/
Take a closer look at the second parameter of json_decode($json, $assoc, $depth)
at https://secure.php.net/json_decode
I had the same problem on my eclipse, and calling eclipse -clean did not solve the problem.
In the end I figured out that within the installation folder of eclipse there is a script called eclipse. This script does some setting of environment variables and then calls eclipse.bin. The call for eclipse.bin contained the command line switch
-data ~/.eclipse
When I removed that switch from start-up script, I got the workspace selection as expected. Maybe that helps others to solve their problems.
The way to get the selection of the spinner is:
spinner1.getSelectedItemPosition();
Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
However, in your code, the one place you are referencing it is within your setOnItemSelectedListener()
. It is not necessary to poll the spinner, because the onItemSelected
method gets passed the position as the "position" variable.
So you could change that line to:
TestProjectActivity.this.number = position + 1;
If that does not fix the problem, please post the error message generated when your app crashes.
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Declaration-wise:
New-style classes inherit from object, or from another new-style class.
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don't.
class OldStyleClass():
pass
Python 3 Note:
Python 3 doesn't support old style classes, so either form noted above results in a new-style class.
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
postgresql.conf
is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA
entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat
, for example
@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL
@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale
Alternatively you can query your database with SHOW config_file;
if you are a superuser.
Here's a "one-liner", spread over multiple lines, in functional programming style:
def variance(data, opt=0):
return (lambda (m2, i, _): m2 / (opt + i - 1))(
reduce(
lambda (m2, i, avg), x:
(
m2 + (x - avg) ** 2 * i / (i + 1),
i + 1,
avg + (x - avg) / (i + 1)
),
data,
(0, 0, 0)))
use this method:-
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
stackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
Caller of method example Code is here:-
public class TestString {
public static void main(String[] args) {
TestString testString = new TestString();
testString.doit1();
testString.doit2();
testString.doit3();
testString.doit4();
}
public void doit() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
}
public void doit1() {
doit();
}
public void doit2() {
doit();
}
public void doit3() {
doit();
}
public void doit4() {
doit();
}
}
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
Even though it can be done via immutability-helper or similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign
. Code:
this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})
Can be used on HTML Event Attributes as well, example:
onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}
In your case the "Vendor code 17002" is the equivalent of the ORA-12541 error: It's most likely that your listener is down, or has an improper port or service name. From the docs:
ORA-12541: TNS no listener
Cause: Listener for the source repository has not been started.
Action: Start the Listener on the machine where the source repository resides.
If you have a self-signed certificate generated by makecert.exe
on a Windows machine, you will get two files: cert.pvk
and cert.cer
. These can be converted to a pfx using pvk2pfx
pvk2pfx
is found in the same location as makecert
(e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86
or similar)
pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx
from this link:
you can use rstrip() method. Example
mystring = "hello\n"
print(mystring.rstrip('\n'))
There are two easy ways, depending on if you want to deal with exceptions or get a default value.
You can use the First<T>()
or the FirstOrDefault<T>()
extension method to get the first result or default(T)
.
var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0
Although this doesnt answer the question directly about command line, but from Windows OS, use the Windows Explorer ftp://username@server
this will use Passive Mode by default
For command line, active mode is the default
My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:
CREATE EVENT applog_clean_event
ON SCHEDULE
EVERY 1 DAY
STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO
MYSQL TRIGGER BEFORE UPDATE IF OLD.a<>NEW.b
USE `pdvsa_ent_aycg`;
DELIMITER $$
CREATE TRIGGER `cisterna_BUPD` BEFORE UPDATE ON `cisterna` FOR EACH ROW
BEGIN
IF OLD.id_cisterna_estado<>NEW.id_cisterna_estado OR OLD.observacion_cisterna_estado<>NEW.observacion_cisterna_estado OR OLD.fecha_cisterna_estado<>NEW.fecha_cisterna_estado
THEN
INSERT INTO cisterna_estado_modificaciones(nro_cisterna_estado, id_cisterna_estado, observacion_cisterna_estado, fecha_cisterna_estado) values (NULL, OLD.id_cisterna_estado, OLD.observacion_cisterna_estado, OLD.fecha_cisterna_estado);
END IF;
END
I think that the best solution is the "Simplest Solution" by Josh Pinter.
This worked for me:
//Code of the activity
//get linearLayout
LinearLayout linearLayout = (LinearLayout ) view.findViewById(R.id.linearLayoutFragment);
LinearLayout linearLayout = new LinearLayout(getActivity());
//display css
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//create the spinner in a fragment activiy
Spinner spn = new Spinner(getActivity());
// create the adapter.
ArrayAdapter<ValorLista> spinner_adapter = new ArrayAdapter<ValorLista>(getActivity(), android.R.layout.simple_spinner_item, meta.getValorlistaList());
spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinner_adapter);
//set the default according to value
//spn.setSelection(spinnerPosition);
linearLayout.addView(spn, params2);
//Code of the class ValorLista
import java.io.Serializable;
import java.util.List;
public class ValorLista implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4930195743192929192L;
private int id;
private String valor;
private List<Metadato> metadatoList;
public ValorLista() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public List<Metadato> getMetadatoList() {
return metadatoList;
}
public void setMetadatoList(List<Metadato> metadatoList) {
this.metadatoList = metadatoList;
}
@Override
public String toString() {
return getValor();
}
}
Dereferencing just means reading the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.
In C, the unary *
operator is the dereferencing operator. If x
is a pointer, then *x
is what x
points to. The unary &
operator is the address-of operator. If x
is anything, then &x
is the address at which x
is stored in memory. The *
and &
operators are inverses of each other: if x
is any data, and y
is any pointer, then these equations are always true:
*(&x) == x
&(*y) == y
A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).
In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:
int *x = NULL; // x is a null pointer
int y = *x; // CRASH: dereference x, trying to read it
*x = 0; // CRASH: dereference x, trying to write it
And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException
in C# (or a NullPointerException
in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException
. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).
Using the excellent request
module:
var request = require('request');
request("http://stackoverflow.com", {method: 'HEAD'}, function (err, res, body){
console.log(res.headers);
});
You can change the method to GET
if you wish, but using HEAD
will save you from getting the entire response body if you only wish to look at the headers.
When you create the colorbar
try using the fraction and/or shrink parameters.
From the documents:
fraction 0.15; fraction of original axes to use for colorbar
shrink 1.0; fraction by which to shrink the colorbar
The difference is in the scope of the variable. The @version is available to all methods of the class instance.
The short answer, if you're in the controller and you need to make the variable available to the view then use @variable
.
For a much longer answer try this: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html
Please see my answer below, inspired by answers above but a bit more detailed...
// Get The Json Response (With Try Catch)
try {
String s = null;
if (response.body() != null) {
s = response.body().string();
// Convert Response Into Json Object (With Try Catch)
JSONObject json = null;
try {
json = new JSONObject(s);
// Extract The User Id From Json Object (With Try Catch)
String stringToExtract = null;
try {
stringToExtract = json.getString("NeededString");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Response status comes as second parameter in callback, (from docs):
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The flowchart below can be of help when choosing one of the various semantic HTML5 elements:
If you are looking for other type of constraint, e.g. defaults, you should use different query (From How do I find a default constraint using INFORMATION_SCHEMA? answered by devio). Use:
SELECT * FROM sys.objects WHERE type = 'D' AND name = @name
to find a default constraint by name.
I've put together different 'IF not Exists" checks in my post "DDL 'IF not Exists" conditions to make SQL scripts re-runnable"
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
In theory: Child => an immediate descendant of an ancestor (e.g. Joe and his father)
Descendant => any element that is descended from a particular ancestor (e.g. Joe and his great-great-grand-father)
In practice: try this HTML:
<div class="one">
<span>Span 1.
<span>Span 2.</span>
</span>
</div>
<div class="two">
<span>Span 1.
<span>Span 2.</span>
</span>
</div>
with this CSS:
span { color: red; }
div.one span { color: blue; }
div.two > span { color: green; }
If you have your navbar inside a component and you declared your style active in that stylesheet, it won't work. In my case this was the problem.
my item of my navbar using angular material was:
<div class="nav-item">
<a routerLink="/test" routerLinkActive="active">
<mat-icon>monetization_on</mat-icon>My link
</a>
<mat-divider class="nav-divider" [vertical]="true"></mat-divider>
so I put the style active in my style.scss in the root
a.active {
color: white !important;
mat-icon {
color: white !important;
}
}
I hope it helps you if the other solutions didn't.
In my case I needed to get the data type for Dynamic SQL (Shudder!) anyway here is a function that I created that returns the full data type. For example instead of returning 'decimal' it would return DECIMAL(18,4): dbo.GetLiteralDataType
In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.
[Edit:] It looks like std::remquo doesn't really return the quotient after all.
React.version
is what you are looking for.
It is undocumented though (as far as I know) so it may not be a stable feature (i.e. though unlikely, it may disappear or change in future releases).
Example with React
imported as a script
const REACT_VERSION = React.version;
ReactDOM.render(
<div>React version: {REACT_VERSION}</div>,
document.getElementById('root')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
_x000D_
Example with React
imported as a module
import React from 'react';
console.log(React.version);
Obviously, if you import React
as a module, it won't be in the global scope. The above code is intended to be bundled with the rest of your app, e.g. using webpack. It will virtually never work if used in a browser's console (it is using bare imports).
This second approach is the recommended one. Most websites will use it. create-react-app does this (it's using webpack behind the scene). In this case, React
is encapsulated and is generally not accessible at all outside the bundle (e.g. in a browser's console).
You can add it by appending a Series to the dataframe as follows. I am assuming by blank you mean you want to add a row containing only "Nan". You can first create a Series object with Nan. Make sure you specify the columns while defining 'Series' object in the -Index parameter. The you can append it to the DF. Hope it helps!
from numpy import nan as Nan
import pandas as pd
>>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
... 'B': ['B0', 'B1', 'B2', 'B3'],
... 'C': ['C0', 'C1', 'C2', 'C3'],
... 'D': ['D0', 'D1', 'D2', 'D3']},
... index=[0, 1, 2, 3])
>>> s2 = pd.Series([Nan,Nan,Nan,Nan], index=['A', 'B', 'C', 'D'])
>>> result = df1.append(s2)
>>> result
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
4 NaN NaN NaN NaN
You could also do this to make it more dynamic.
<input name="filterByPolarity" data-ng-model="text.polarity"/>
Then you ng-repeat will look like this
<div class="tweet" data-ng-repeat="tweet in tweets | filter:text"></div>
This filter will of course only be used to filter by polarity
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
You can get around this by using a traits class:
It requires you set up a specialsed traits class for each actuall class you use.
template<typename SubClass>
class SubClass_traits
{};
template<typename Subclass>
class A {
public:
void action(typename SubClass_traits<Subclass>::mytype var)
{
(static_cast<Subclass*>(this))->do_action(var);
}
};
// Definitions for B
class B; // Forward declare
template<> // Define traits for B. So other classes can use it.
class SubClass_traits<B>
{
public:
typedef int mytype;
};
// Define B
class B : public A<B>
{
// Define mytype in terms of the traits type.
typedef SubClass_traits<B>::mytype mytype;
public:
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv)
{
B myInstance;
return 0;
}
This is fairly straightforward. In your JS, all you would do is this or something similar:
var array = ["thing1", "thing2", "thing3"];
var parameters = {
"array1[]": array,
...
};
$.post(
'your/page.php',
parameters
)
.done(function(data, statusText) {
// This block is optional, fires when the ajax call is complete
});
In your php page, the values in array form will be available via $_POST['array1']
.
references
I had the same problems. I solved it: I went to https://www.google.com/recaptcha/admin, clicked on the domain and then went to key settings at the bottom.
There I disabled the option below Domain Name Validation Verify the origin of reCAPTCHA solution.
Clicked on save and captcha started working.
I recently submitted an app to Apple's App Store. My app was built using iOS 12, Xcode 10, and Swift 4.2. My app uses Google AdMob
for the sole purpose of showing Interstitial Ads. When prompted these question, this is what I did:
1) Does this app use the Advertising Identifier (IDFA)? ANSWER: YES
a) Serve advertisements within the app - CHECKED
b) Attribute this app ... - NOT CHECKED
c) Attribute an action ... - NOT CHECKED
I, (my name), confirm that this app ... - CHECKED
My app was accepted and "Ready for Sale" in less than 24 hrs.
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
If you have pods installed, make sure to open the workspace folder (white Xcode icon) not the project folder. This resolved the library not found for ...
error. Very simple issue but I was stuck on this for a long time.
interface MyProps {
...
}
interface MyState {
value: string
}
class App extends React.Component<MyProps, MyState> {
...
}
// Or with hooks, something like
const App = ({}: MyProps) => {
const [value, setValue] = useState<string>('');
...
};
type
's are fine too like in @nitzan-tomer's answer, as long as you're consistent.
excel file
here and you can get the data in JSON
format in console
:<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
var ExcelToJSON = function() {_x000D_
_x000D_
this.parseExcel = function(file) {_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function(e) {_x000D_
var data = e.target.result;_x000D_
var workbook = XLSX.read(data, {_x000D_
type: 'binary'_x000D_
});_x000D_
workbook.SheetNames.forEach(function(sheetName) {_x000D_
// Here is your object_x000D_
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
var json_object = JSON.stringify(XL_row_object);_x000D_
console.log(JSON.parse(json_object));_x000D_
jQuery( '#xlx_json' ).val( json_object );_x000D_
})_x000D_
};_x000D_
_x000D_
reader.onerror = function(ex) {_x000D_
console.log(ex);_x000D_
};_x000D_
_x000D_
reader.readAsBinaryString(file);_x000D_
};_x000D_
};_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
_x000D_
var files = evt.target.files; // FileList object_x000D_
var xl2json = new ExcelToJSON();_x000D_
xl2json.parseExcel(files[0]);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
<input id="upload" type=file name="files[]">_x000D_
</form>_x000D_
_x000D_
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
<script>_x000D_
document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
</script>
_x000D_
This is a combination of the following Stackoverflow
posts:
Good Luck...
here's a short paragraph from this article How to Make Frames (Main Windows) - The Java Tutorials - Oracle that explains what setBounds method does in addition to some other similar methods:
The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
the parameters of setBounds are (int x, int y, int width, int height) x and y are define the position/location and width and height define the size/dimension of the frame.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.
<html>
<head>
<script language="javascript">
var ret;
function returnfunction()
{
alert(ret);
}
</script>
</head>
<body>
<form>
<label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
<input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
<input type="button" value="No" onClick="ret=false;returnfunction()" />
</form>
</body>
</html>
If you meant disable all the inputs in an Angular form at once:
1- Reactive Forms:
myFormGroup.disable() // where myFormGroup is a FormGroup
2- Template driven forms (NgForm):
You should get hold of the NgForm in a NgForm variable (for ex. named myNgForm) then
myNgForm.form.disable() // where form here is an attribute of NgForm
// & of type FormGroup so it accepts the disable() function
In case of NgForm , take care to call the disable method in the right time
To determine when to call it, You can find more details in this Stackoverflow answer
As lots of others have said, you will need to use multiple ALTER COLUMN
statements, one for each column you want to modify.
If you want to modify all or several of the columns in your table to the same datatype (such as expanding a VARCHAR field from 50 to 100 chars), you can generate all the statements automatically using the query below. This technique is also useful if you want to replace the same character in multiple fields (such as removing \t from all columns).
SELECT
TABLE_CATALOG
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] VARCHAR(300)' as 'code'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'your_table' AND TABLE_SCHEMA = 'your_schema'
This generates an ALTER TABLE
statement for each column for you.
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.
<!--[if gte mso 9]>
<style>
#tableForOutlook {
width:800px;
}
</style>
<![endif]-->
<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
<table id="tableForOutlook"><tr><td>
<![endif]-->
<tr><td>
[Your Content Goes Here]
</td></tr>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
<table>
The idea of removing duplicate involves
Step-by-step
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
capture this
:
auto lambda = [this](){};
use a local reference to the member:
auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref
C++14:
auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref
example: https://godbolt.org/g/dEKVGD
Try this
$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
// your code;
});
Do not use this. This may crash the page.
$('mydiv').bind("DOMSubtreeModified",function(){
alert('changed');
});
I think it's r+
, not rw
. I'm just a starter, and that's what I've seen in the documentation.
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
I know it is not a good habit to answer an old question but I'm putting this answer for people who would see the question afterwards.
The best way to change the state in JQuery now is through
$("#input").prop('disabled', true);
$("#input").prop('disabled', false);
Please check this link for full illustration. Disable/enable an input with jQuery?
While pass by reference is nothing that fits well into python and should be rarely used there are some workarounds that actually can work to get the object currently assigned to a local variable or even reassign a local variable from inside of a called function.
The basic idea is to have a function that can do that access and can be passed as object into other functions or stored in a class.
One way is to use global
(for global variables) or nonlocal
(for local variables in a function) in a wrapper function.
def change(wrapper):
wrapper(7)
x = 5
def setter(val):
global x
x = val
print(x)
The same idea works for reading and del
eting a variable.
For just reading there is even a shorter way of just using lambda: x
which returns a callable that when called returns the current value of x. This is somewhat like "call by name" used in languages in the distant past.
Passing 3 wrappers to access a variable is a bit unwieldy so those can be wrapped into a class that has a proxy attribute:
class ByRef:
def __init__(self, r, w, d):
self._read = r
self._write = w
self._delete = d
def set(self, val):
self._write(val)
def get(self):
return self._read()
def remove(self):
self._delete()
wrapped = property(get, set, remove)
# left as an exercise for the reader: define set, get, remove as local functions using global / nonlocal
r = ByRef(get, set, remove)
r.wrapped = 15
Pythons "reflection" support makes it possible to get a object that is capable of reassigning a name/variable in a given scope without defining functions explicitly in that scope:
class ByRef:
def __init__(self, locs, name):
self._locs = locs
self._name = name
def set(self, val):
self._locs[self._name] = val
def get(self):
return self._locs[self._name]
def remove(self):
del self._locs[self._name]
wrapped = property(get, set, remove)
def change(x):
x.wrapped = 7
def test_me():
x = 6
print(x)
change(ByRef(locals(), "x"))
print(x)
Here the ByRef
class wraps a dictionary access. So attribute access to wrapped
is translated to a item access in the passed dictionary. By passing the result of the builtin locals
and the name of a local variable this ends up accessing a local variable. The python documentation as of 3.5 advises that changing the dictionary might not work but it seems to work for me.
You can use substring to get portio of String which is equal to 1 mb:
public static void main(String[] args) {
// Get length of String in bytes
String string = "long string";
long sizeInBytes = string.getBytes().length;
int oneMb=1024*1024;
if (sizeInBytes>oneMb) {
String string1Mb=string.substring(0, oneMb);
}
}
It is worth mentioning that the command works similarly on Linux:
git clone path/to/source/folder path/to/destination/folder
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
Open Notepad.
Type the following lines into it (obviously replace the folders with your ones)
@echo off
rem you could also remove the line above, because it might help you to see what happens
rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e
Save the file as backup.bat (not .txt)
Double click on the file to run it. It will backup the folder and all its contents files/subfolders.
Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.
To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.
Just use the ==
with the negation symbol (!
). If dtfm is the name of your data.frame:
dtfm[!dtfm$C == "Foo", ]
Or, to move the negation in the comparison:
dtfm[dtfm$C != "Foo", ]
Or, even shorter using subset()
:
subset(dtfm, C!="Foo")
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
Below link saved the day
https://msdn.microsoft.com/en-us/library/ms229076(VS.80).aspx
use the relevant RegSvcs as specified in the above link
c:\Windows\Microsoft. NET\Framework\v4.0.30319\RegSvcs.exe ....\Shared\Your.dll /tlb:Your.tlb
I know many answers have already been posted for this, but neither one answer independently worked for my site. So here is what worked for me:
Step 1: Uninstall the following updates - KB2920789, KB2920790, KB2920792, KB2920793, KB2984942, KB2596927
Step 2: Hide these updates so they do not get installed on subsequent reboots
Step 3: Delete folder Excel8.0 from C:\Users\<>\AppData\Local\Temp
Step 4: Restart workstatiion (I would also make sure the above mentioned KBs did not inadvertently get applied)
You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:
<input type="text" onChange={e => this.setState({ text: e.target.value })}/>
If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.
clickHandler = function(event){
if (click++ == 49)
canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);
No one mentioned liriliri/eruda which adds its own debugging tools meant for mobile websites/apps
Adding this to your page:
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>
Will add a floating icon to your page which opens the console.
Sample, in MyRecyclerViewAdapter, add method:
public interface ItemClickListener {
void onItemClick(View view, int position);
}
In MainActivity.java
@Override
public void onItemClick(View view, int position) {
Context context=view.getContext();
Intent intent=new Intent();
switch (position){
case 0:
intent = new Intent(context, ChildActivity.class);
context.startActivity(intent);
break;
}
}
It may help someone as I need to only show selected value, don't need to declare something in component and etc.
If your status is coming from the database then you can show selected value this way.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
Just in keeping the parent value in child attribute
var Foo = function(){
this.val= 4;
this.test={};
this.test.val=6;
this.test.par=this;
}
var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);
In my case, what did it was this command:
git config core.whitespace cr-at-eol
I prefer error handling in C using the following technique:
struct lnode *insert(char *data, int len, struct lnode *list) { struct lnode *p, *q; uint8_t good; struct { uint8_t alloc_node : 1; uint8_t alloc_str : 1; } cleanup = { 0, 0 }; // allocate node. p = (struct lnode *)malloc(sizeof(struct lnode)); good = cleanup.alloc_node = (p != NULL); // good? then allocate str if (good) { p->str = (char *)malloc(sizeof(char)*len); good = cleanup.alloc_str = (p->str != NULL); } // good? copy data if(good) { memcpy ( p->str, data, len ); } // still good? insert in list if(good) { if(NULL == list) { p->next = NULL; list = p; } else { q = list; while(q->next != NULL && good) { // duplicate found--not good good = (strcmp(q->str,p->str) != 0); q = q->next; } if (good) { p->next = q->next; q->next = p; } } } // not-good? cleanup. if(!good) { if(cleanup.alloc_str) free(p->str); if(cleanup.alloc_node) free(p); } // good? return list or else return NULL return (good ? list : NULL); }
Source: http://blog.staila.com/?p=114
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
I used the below to solve this problem.
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.
Camel Case is usually without spaces between words.
As far as I know you can only join this way:
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = obj_i.SomeField1,
JoinProperty2 = obj_i.SomeField2,
JoinProperty3 = obj_i.SomeField3,
JoinProperty4 = obj_i.SomeField4
}
equals
new {
JoinProperty1 = obj_j.SomeOtherField1,
JoinProperty2 = obj_j.SomeOtherField2,
JoinProperty3 = obj_j.SomeOtherField3,
JoinProperty4 = obj_j.SomeOtherField4
}
The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.
You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.
More advanced stuff in this LinqPad example:
class c1
{
public int someIntField;
public string someStringField;
}
class c2
{
public Int64 someInt64Property {get;set;}
private object someField;
public string someStringFunction(){return someField.ToString();}
}
void Main()
{
var set1 = new List<c1>();
var set2 = new List<c2>();
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = (Int64) obj_i.someIntField,
JoinProperty2 = obj_i.someStringField
}
equals
new {
JoinProperty1 = obj_j.someInt64Property,
JoinProperty2 = obj_j.someStringFunction()
}
select new {obj1 = obj_i, obj2 = obj_j};
}
Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.
If order matters, you should keep a property on the "T" objects in your list that denotes sequence. In order to swap them, just swap the value of that property, and then use that in the .Sort(comparison with sequence property)
declare @p varbinary(max)
set @p = 0x
declare @local table (col text)
SELECT @p = @p + 0x3B + CONVERT(varbinary(100), Email)
FROM tbCarsList
where email <> ''
group by email
order by email
set @p = substring(@p, 2, 100000)
insert @local values(cast(@p as varchar(max)))
select DATALENGTH(col) as collen, col from @local
result collen > 8000, length col value is more than 8000 chars
When you create your image_array, it's empty, therefore your image_array.length is 0
As stated in the comment below, i edit my answer based on this question's answer) :
var image_array = []
inside the else brackets doesn't change anything to the image_array defined before in the code
p
is not how you put text in a
. That is the problem. The only solution is to put the text between <a>
and </a>
. For example:
<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>
Short answer is, it make sense. Recently this was discussed in ng-conf 2014. Here is the talk on this topic:
Check
Control Panel --> Administrative Tools --> Services --> IIS Admin
For reinstalling
If you're not looking to download dex2jar, then just use the apk_grabber
python script to decompile any apk into jar files. Then you read them with jd-gui.
SELECT *, 1 AS sort_order
FROM table1
EXCEPT
SELECT *, 1 AS sort_order
FROM table2
UNION
SELECT *, 1 AS sort_order
FROM table1
INTERSECT
SELECT *, 1 AS sort_order
FROM table2
UNION
SELECT *, 2 AS sort_order
FROM table2
EXCEPT
SELECT *, 2 AS sort_order
FROM table1
ORDER BY sort_order;
But the real answer is: other than the ORDER BY
clause, the sort order will by arbitrary and not guaranteed.
This worked for me:
body {
background-image:url(../IMAGES/background.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
Yes. The casts are redundant. In your expression:
true == 1
Integral promotion applies and the bool value will be promoted to an int
and this promotion must yield 1.
Reference: 4.7 [conv.integral] / 4: If the source type is bool
... true
is converted to one.
set environment variable
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_24
classpath=C:\Program Files\Java\jdk1.6.0_24\lib\tools.jar
path=C:\Program Files\Java\jdk1.6.0_24\bin
Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0
each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)
Private Function FileExists(fullFileName As String) As Boolean
FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
Swift 4
let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.setTitleTextAttributes([NSFontAttributeName: font], for: .normal)
You can think of the HEAD as the "current branch". When you switch branches with git checkout
, the HEAD revision changes to point to the tip of the new branch.
You can see what HEAD points to by doing:
cat .git/HEAD
In my case, the output is:
$ cat .git/HEAD
ref: refs/heads/master
It is possible for HEAD to refer to a specific revision that is not associated with a branch name. This situation is called a detached HEAD.
var query = list.Where(r => listofIds.Any(id => id == r.Id));
Another approach, useful if the listOfIds array is large:
HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));
First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.
We need to Update the GoogleMapHelper to fix the issue
Need to add the below script in setCenterMap function
google.maps.event.trigger({$id}, \"resize\");
And need the include below code in JavaScript
google.maps.event.addListenerOnce({$id}, 'idle', function(){
setCenterMap(new google.maps.LatLng({$this->defaultLatitude},
{$this->defaultLongitude}));
});
No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.
jQuery's implementation of it is as simple as you might expect:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
If you are dealing with a sane amount of array elements the above will do the trick nicely.
EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array
:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
// Output:
// 'ph' was found
// 'o' was found
The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect
. This does what you want:
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
And this my test of the above on it:
var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
alert('ph was found');
}
if(inArray(['f','i'], a)) {
alert('fi was found');
}
if(inArray('o', a)) {
alert('o was found');
}
// Results:
// alerts 'ph' was found
// alerts 'o' was found
Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.
import java.util.Date;
public class IsDateBetween {
public static void main (String[] args) {
IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
}
public IsDateBetween(String dd) {
long from=Date.parse("01/01/2000"); // From some date
long to=Date.parse("12/12/2010"); // To Some Date
long check=Date.parse(dd);
int x=0;
if((check-from)>0 && (to-check)>0)
{
x=1;
}
System.out.println ("From Date is greater Than ToDate : "+x);
}
}
This is my version referring @Virako 's code snippet
def adjust_column_width_from_col(ws, min_row, min_col, max_col):
column_widths = []
for i, col in \
enumerate(
ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
):
for cell in col:
value = cell.value
if value is not None:
if isinstance(value, str) is False:
value = str(value)
try:
column_widths[i] = max(column_widths[i], len(value))
except IndexError:
column_widths.append(len(value))
for i, width in enumerate(column_widths):
col_name = get_column_letter(min_col + i)
value = column_widths[i] + 2
ws.column_dimensions[col_name].width = value
And how to use is as follows,
adjust_column_width_from_col(ws, 1,1, ws.max_column)
Style property can be used For HTML5 if you want to remove the boder of your frame or anything you can use the style property. as given below
Code goes here
<iframe src="demo.htm" style="border:none;"></iframe>
Here 'AffiliateDueDate' and 'Title' are columns, both are sorted in ascending order.
array.sort(function(a, b) {
if (a.AffiliateDueDate > b.AffiliateDueDate ) return 1;
else if (a.AffiliateDueDate < b.AffiliateDueDate ) return -1;
else if (a.Title > b.Title ) return 1;
else if (a.Title < b.Title ) return -1;
else return 0;
})
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Take a look at Job Control on UNIX systems
If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs
and kill -9 %<job #>
to kill it. The '-9' is a type of signal. You can man kill
to see a list of signals.
Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.
From the data you gathered, I would tend to say that encoded "/" in an uri are meant to be seen as "/" again at application/cgi level.
That's to say, that if you're using apache with mod_rewrite
for instance, it will not match pattern expecting slashes against URI with encoded slashes in it.
However, once the appropriate module/cgi/... is called to handle the request, it's up to it to do the decoding and, for instance, retrieve a parameter including slashes as the first component of the URI.
If your application is then using this data to retrieve a file (whose filename contains a slash), that's probably a bad thing.
To sum up, I find it perfectly normal to see a difference of behaviour in "/" or "%2F" as their interpretation will be done at different levels.
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
You need remove path.moveTo after first initial.
Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();