Indeed, the simplest way is to use intValue()
. However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:
Integer integer = Integer.valueOf((int) Math.round(myDouble)));
And don't forget the null case:
Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));
Math.round()
handles odd duck cases, like infinity and NaN, with relative grace.
Microsoft Common Object Runtime Library.
See http://www.danielmoth.com/Blog/mscorlibdll.aspx and What does 'Cor' stand for?
@PropertySource
can be configured by factory
argument. So you can do something like:
@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)
Where YamlPropertyLoaderFactory
is your custom property loader:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
}
}
Inspired by https://stackoverflow.com/a/45882447/4527110
You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running pip3 install --upgrade pip
.
It might be a good idea to take some time and read about virtual environments in Python. It isn't a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/
System wide C++ change on Ubuntu:
sudo apt-get install clang
sudo update-alternatives --config c++
Will print something like this:
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/g++ 20 auto mode
1 /usr/bin/clang++ 10 manual mode
2 /usr/bin/g++ 20 manual mode
Then just select clang++.
I found the answer is git reset --merge
- it clears the conflicted cherry-pick attempt.
What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.
CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult
should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.
I agree with Brad's answer, that you can fix this problem by editing your target/project by hand, deleting any lines like this:
PROVISIONING_PROFILE = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";
However, in Xcode 4.2 and later, there is a much easier way to access this text and select and delete it. In the Project Navigator on the left, select your project (the topmost line of the Project Navigator). Now simply choose View > Version Editor > Show Version Editor. This displays your project as text, and you can search for PROVISIONING and delete the troublesome line, right there in the editor pane of Xcode.
Locking is platform and device specific, but generally, you have a few options:
For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.
If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above).
Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.
It's entirely possible if your code has enough relative logic to work with.
Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.
ol {max-width: 10vw; padding: 0; overflow: hidden;}
Apparently max-width
on colgroup
elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
I think you can use SeriesGroupBy.nunique
:
print (df.groupby('param')['group'].nunique())
param
a 2
b 1
Name: group, dtype: int64
Another solution with unique
, then create new df
by DataFrame.from_records
, reshape to Series
by stack
and last value_counts
:
a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a 2
b 1
dtype: int64
Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.
In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.
You can define a pointer to an array, for example this:
double (*p)[42];
defines p
as a pointer to a 42-element array of double
s. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.
A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator []
to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.
If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.
Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.
But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector>
and <array>
, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.
EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.
TLDR; Neither use the synchronized
modifier nor the synchronized(this){...}
expression but synchronized(myLock){...}
where myLock
is a final instance field holding a private object.
The difference between using the synchronized
modifier on the method declaration and the synchronized(..){ }
expression in the method body are this:
synchronized
modifier specified on the method's signature
synchronized(this) { .... }
, andthis
object as lock when declared on non-static method or the enclosing class when declared on a static method.synchronized(...){...}
expression allows you
However, using the synchronized
modifier or synchronized(...) {...}
with this
as the lock object (as in synchronized(this) {...}
), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).
Therefore best practice is to neither use the synchronized
modifier nor the synchronized(...)
expression in conjunction with this
as lock object but a lock object private to this object. For example:
public class MyService {
private final lock = new Object();
public void doThis() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
public void doThat() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
}
You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.
public class MyService {
private final lock1 = new Object();
private final lock2 = new Object();
public void doThis() {
synchronized(lock1) {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThat() and doMore().
}
}
public void doThat() {
synchronized(lock1) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doMore() may execute concurrently
}
}
public void doMore() {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doThat() may execute concurrently
}
}
}
Since in your situation you only want to notify the user with a short and simple message, a Toast
would make for a better user experience.
Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();
Update: A Snackbar is recommended now instead of a Toast for Material Design apps.
If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment
. (The documentation currently recommends wrapping your AlertDialog
in a fragment rather than calling it directly.)
Make a class that extends DialogFragment
:
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("App Title");
builder.setMessage("This is an alert with no consequence");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// You don't have to do anything here if you just
// want it dismissed when clicked
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Then call it when you need it in your activity:
DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");
Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.
The problem is, that if you have that problem, the database-schema is denormalized.
You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.
So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.
So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.
And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...
Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO
CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
@in_RM_ApertureID uniqueidentifier
,@in_DatumVon AS datetime
,@in_DatumBis AS datetime
,@in_Status AS integer
)
RETURNS bit
AS
BEGIN
DECLARE @bNoCheckForThisCustomer AS bit
DECLARE @bIsInvalidValue AS bit
SET @bNoCheckForThisCustomer = 'false'
SET @bIsInvalidValue = 'false'
IF @in_Status = 99
RETURN 'false'
IF @in_DatumVon > @in_DatumBis
BEGIN
RETURN 'true'
END
IF @bNoCheckForThisCustomer = 'true'
RETURN @bIsInvalidValue
IF NOT EXISTS
(
SELECT
T_Raum.RM_UID
,T_Raum.RM_Status
,T_Raum.RM_DatumVon
,T_Raum.RM_DatumBis
,T_Raum.RM_ApertureID
FROM T_Raum
WHERE (1=1)
AND T_Raum.RM_ApertureID = @in_RM_ApertureID
AND @in_DatumVon >= T_Raum.RM_DatumVon
AND @in_DatumBis <= T_Raum.RM_DatumBis
AND T_Raum.RM_Status <> 99
)
SET @bIsInvalidValue = 'true' -- IF !
RETURN @bIsInvalidValue
END
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
CHECK
(
NOT
(
dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1
)
)
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
... And the answer is:
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")
The Set
makes all the difference. Then it works like a charm.
I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45 There is another way to fix that error.
In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;
Connect to MySQL as root
mysql -u root -p
then enter your MySQL root password;
Select database;
use mysql;
Most probably there is only one record for root in mysql.user
table allowing to connect only from localhost
(that was in my case) but by the default there should be two records for root, one for localhost
and another one for 127.0.0.1
;
Create additional record for root user with Host='127.0.0.1'
if it's not there;
SET @s = CONCAT('INSERT INTO mysql.user SELECT ',
REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
,"Host","'127.0.0.1'"),
' FROM mysql.user WHERE User="root"');
PREPARE stmt FROM @s;
EXECUTE stmt;
Additionally to that you can execute mysql_upgrade -u -p
to see if everything is ok.
That depends on your environment. JSF for example would take the burden of manually checking and converting Strings <-> Numbers from you, Bean Validation is another option.
What you can do immediately in the snippet you provide:
getAsInt(String param)
, in it:String.isEmpty()
(Since Java 6), try / catch
What you should definitely think about if you happen to write a lot of code like this:
public void myBusinessMethod(@ValidNumber String numberInput) {
// ...
}
(This would be interceptor-based).
Last but not least: Save the work and try to switch to a framework which gives you support for these common tasks...
There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit}
and onReset={handleReset}
to your form
elements.
To stop the actual submission just include event
in your function and an event.preventDefault();
to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.
Here's an easier way:
sudo apt-get install maven
More details are here.
You can use ROW_NUMBER()
function to get what you want:
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20
I just accomplished the opposite of this using :after
and ::after
because I needed to make my bottom border exactly 1.3rem
wider:
My element got super deformed when I used :before
and :after
at the same time because the elements are horizontally aligned with display: flex
, flex-direction: row
and align-items: center
.
You could use this for making something wider or narrower, or probably any mathematical dimension mods:
a.nav_link-active {
color: $e1-red;
margin-top: 3.7rem;
}
a.nav_link-active:visited {
color: $e1-red;
}
a.nav_link-active:after {
content: '';
margin-top: 3.3rem; // margin and height should
height: 0.4rem; // add up to active link margin
background: $e1-red;
margin-left: -$nav-spacer-margin;
display: block;
}
a.nav_link-active::after {
content: '';
margin-top: 3.3rem; // margin and height should
height: 0.4rem; // add up to active link margin
background: $e1-red;
margin-right: -$nav-spacer-margin;
display: block;
}
Sorry, this is SCSS
, just multiply the numbers by 10 and change the variables with some normal values.
Install Oracle's MySql.Data
NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
I'd recommend event.key
currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
event.KeyCode
and event.which
both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
For alphanumeric keys, event.key
appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key
has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).
For alphanumeric keys a check would look something like:
event.key === 'a'
For control characters you'd need to do something like:
event.key === 'Esc' || event.key === 'Escape'
I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code
event.code
is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.
$('#a_tbnotesverbergen').text('My New Link Text');
OR
$('#a_tbnotesverbergen').html('My New Link Text or HTML');
Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.
Refer: google recaptcha docs
apply this.
<RatingBar android:id="@+id/indicator_ratingbar"
style="?android:attr/ratingBarStyleIndicator"
android:layout_marginLeft="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
conda create --name new_name --copy --clone old_name
is better
I use conda create --name new_name --clone old_name
which is without --copy
but encountered pip breaks...
the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from
I just had this error. I tried restarting the simulator and Xcode but my project would only work again after a clean and build. No idea what caused it.
The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.
bool alreadyAdded = false;
This variable can be global.
if(!alreadyAdded)
{
myClass.MyEvent += MyHandler;
alreadyAdded = true;
}
Here's my take: http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/
Sometimes while moving mouse from popover trigger to actual popover content diagonally, you hover over elements below. I wanted to handle such situations – as long as you reach popover content before the timeout fires, you're safe (the popover won't disappear). It requires delay
option.
This hack basically overrides Popover leave
function, but calls the original (which starts timer to hide the popover). Then it attaches a one-off listener to mouseenter
popover content element's.
If mouse enters the popover, the timer is cleared. Then it turns it listens to mouseleave
on popover and if it's triggered, it calls the original leave function so that it could start hide timer.
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
var container, timeout;
originalLeave.call(this, obj);
if(obj.currentTarget) {
container = $(obj.currentTarget).siblings('.popover')
timeout = self.timeout;
container.one('mouseenter', function(){
//We entered the actual popover – call off the dogs
clearTimeout(timeout);
//Let's monitor popover content instead
container.one('mouseleave', function(){
$.fn.popover.Constructor.prototype.leave.call(self, self);
});
})
}
};
np.r_[ ... ]
and np.c_[ ... ]
are useful alternatives to vstack
and hstack
,
with square brackets [] instead of round ().
A couple of examples:
: import numpy as np
: N = 3
: A = np.eye(N)
: np.c_[ A, np.ones(N) ] # add a column
array([[ 1., 0., 0., 1.],
[ 0., 1., 0., 1.],
[ 0., 0., 1., 1.]])
: np.c_[ np.ones(N), A, np.ones(N) ] # or two
array([[ 1., 1., 0., 0., 1.],
[ 1., 0., 1., 0., 1.],
[ 1., 0., 0., 1., 1.]])
: np.r_[ A, [A[1]] ] # add a row
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.]])
: # not np.r_[ A, A[1] ]
: np.r_[ A[0], 1, 2, 3, A[1] ] # mix vecs and scalars
array([ 1., 0., 0., 1., 2., 3., 0., 1., 0.])
: np.r_[ A[0], [1, 2, 3], A[1] ] # lists
array([ 1., 0., 0., 1., 2., 3., 0., 1., 0.])
: np.r_[ A[0], (1, 2, 3), A[1] ] # tuples
array([ 1., 0., 0., 1., 2., 3., 0., 1., 0.])
: np.r_[ A[0], 1:4, A[1] ] # same, 1:4 == arange(1,4) == 1,2,3
array([ 1., 0., 0., 1., 2., 3., 0., 1., 0.])
(The reason for square brackets [] instead of round () is that Python expands e.g. 1:4 in square -- the wonders of overloading.)
Another one-liner:
Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })
Add the following parameter debug-enabled="true" to this line in the glassfish configuration. Example:
<java-config debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009" debug-enabled="true"
system-classpath="" native-library-path-prefix="D:\Project\lib\windows\64bit" classpath-suffix="">
Start and stop the glassfish domain or service which was using this configuration.
I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.
This worked for me in Oracle 11g:
REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*');
This is another version which work in case you have some tasks to cleanup. Code will leave clean up process in their method.
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
_,done1:=doSomething1()
_,done2:=doSomething2()
//do main thread
println("wait for finish")
<-done1
<-done2
fmt.Print("clean up done, can exit safely")
}
func doSomething1() (error, chan bool) {
//do something
done:=make(chan bool)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
//cleanup of something1
done<-true
}()
return nil,done
}
func doSomething2() (error, chan bool) {
//do something
done:=make(chan bool)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
//cleanup of something2
done<-true
}()
return nil,done
}
in case you need to clean main function you need to capture signal in main thread using go func() as well.
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Just a few lines of example code to show the difference between numpy.array and numpy.ndarray
Warm up step: Construct a list
a = [1,2,3]
Check the type
print(type(a))
You will get
<class 'list'>
Construct an array (from a list) using np.array
a = np.array(a)
Or, you can skip the warm up step, directly have
a = np.array([1,2,3])
Check the type
print(type(a))
You will get
<class 'numpy.ndarray'>
which tells you the type of the numpy array is numpy.ndarray
You can also check the type by
isinstance(a, (np.ndarray))
and you will get
True
Either of the following two lines will give you an error message
np.ndarray(a) # should be np.array(a)
isinstance(a, (np.array)) # should be isinstance(a, (np.ndarray))
This one answer I have got from the earlier python2 answers that is
Install termcolor module.
pip3 install termcolor
Import the colored library from termcolor.
from termcolor import colored
Use the provided methods, below is an example.
print(colored('hello', 'red'), colored('world', 'green'))
For REST controllers, I would recommend to use Zalando Problem Spring Web
.
https://github.com/zalando/problem-spring-web
If Spring Boot aims to embed some auto-configuration, this library does more for exception handling. You just need to add the dependency:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
<version>LATEST</version>
</dependency>
And then define one or more advice traits for your exceptions (or use those provided by default)
public interface NotAcceptableAdviceTrait extends AdviceTrait {
@ExceptionHandler
default ResponseEntity<Problem> handleMediaTypeNotAcceptable(
final HttpMediaTypeNotAcceptableException exception,
final NativeWebRequest request) {
return Responses.create(Status.NOT_ACCEPTABLE, exception, request);
}
}
Then you can defined the controller advice for exception handling as:
@ControllerAdvice
class ExceptionHandling implements MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait {
}
Based on the comments above, here is a simple test:
isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset() { [ -z "$(isunset "$1")" ] && echo 1; }
Example:
$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo= ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
cat /dev/urandom > /dev/null
Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.
Use the Menu "Find Handle" and then you can type a path like this
\Device\LanmanRedirector\server\share\
You may use Arrays.sort() function.
sort() method is a java.util.Arrays class method.
Declaration : Arrays.sort(arrName)
just use SQL :
disconnect;
conn tiger/scott as sysdba;
One more important thing needs to be highlighted. It's better to use params
because it is better for performance. When you call a method with params
argument and passed to it nothing:
public void ExampleMethod(params string[] args)
{
// do some stuff
}
call:
ExampleMethod();
Then a new versions of the .Net Framework do this (from .Net Framework 4.6):
ExampleMethod(Array.Empty<string>());
This Array.Empty
object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:
ExampleMethod(new string[] {});
The following javascript and python scripts give identical outputs. I think it's what you are looking for.
JavaScript
new Date().toISOString()
Python
from datetime import datetime
datetime.utcnow().isoformat()[:-3]+'Z'
The output they give is the utc (zelda) time formatted as an ISO string with a 3 millisecond significant digit and appended with a Z.
2019-01-19T23:20:25.459Z
In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL
into MySQL
is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak
file which is from MsSQL
and convert it into .sql
format which is readable to MySQL
.
Additional note: This can not only convert your .bak
files but also this site is for all types of Database migrations that you want.
An old post but thought i would share an answer for anyone looking.
And because when you use absolute
things can go wrong.
What I would do is
HTML
<div id="parentDiv"></div>
<div class="childDiv"></div>
The Css
parentDiv{
}
childDiv{
height:40px;
margin-top:-20px;
}
And that would just sit that bottom div back up into the parent div. safe for most browsers too
because a lambda function is supposed to be one-lined, as its the simplest form of a function, an entrance, then return
Many have voiced out their answer in words. This is an extended explanation in codes:
public class A {
public static void test() {
System.out.println("A");
}
public static void test2() {
System.out.println("Test");
}
}
public class B extends A {
public static void test() {
System.out.println("B");
}
}
// Called statically
A.test();
B.test();
System.out.println();
// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();
// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();
// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();
// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();
// Testing whether null instance works
A nullObj = null;
nullObj.hi();
Results:
A
B
Test
Test
A
B
Test
Test
A
A
Therefore, this is the conclusion:
null
instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
You can do it like this:
public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
foreach (T item in list)
{
}
}
... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name
and Id
directly.
Here is my solution which does not allocate any heap memory, therefore it should be significantly faster than most of the other implementations mentioned here.
public static int indexOfIgnoreCase(final String haystack,
final String needle) {
if (needle.isEmpty() || haystack.isEmpty()) {
// Fallback to legacy behavior.
return haystack.indexOf(needle);
}
for (int i = 0; i < haystack.length(); ++i) {
// Early out, if possible.
if (i + needle.length() > haystack.length()) {
return -1;
}
// Attempt to match substring starting at position i of haystack.
int j = 0;
int ii = i;
while (ii < haystack.length() && j < needle.length()) {
char c = Character.toLowerCase(haystack.charAt(ii));
char c2 = Character.toLowerCase(needle.charAt(j));
if (c != c2) {
break;
}
j++;
ii++;
}
// Walked all the way to the end of the needle, return the start
// position that this was found.
if (j == needle.length()) {
return i;
}
}
return -1;
}
And here are the unit tests that verify correct behavior.
@Test
public void testIndexOfIgnoreCase() {
assertThat(StringUtils.indexOfIgnoreCase("A", "A"), is(0));
assertThat(StringUtils.indexOfIgnoreCase("a", "A"), is(0));
assertThat(StringUtils.indexOfIgnoreCase("A", "a"), is(0));
assertThat(StringUtils.indexOfIgnoreCase("a", "a"), is(0));
assertThat(StringUtils.indexOfIgnoreCase("a", "ba"), is(-1));
assertThat(StringUtils.indexOfIgnoreCase("ba", "a"), is(1));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", " Royal Blue"), is(-1));
assertThat(StringUtils.indexOfIgnoreCase(" Royal Blue", "Royal Blue"), is(1));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "royal"), is(0));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "oyal"), is(1));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "al"), is(3));
assertThat(StringUtils.indexOfIgnoreCase("", "royal"), is(-1));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", ""), is(0));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BLUE"), is(6));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BIGLONGSTRING"), is(-1));
assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "Royal Blue LONGSTRING"), is(-1));
}
Another way to collect uniq columns with sql:
Model.group(:rating).pluck(:rating)
string[] result = new string[table.Columns.Count];
DataRow dr = table.Rows[0];
for (int i = 0; i < dr.ItemArray.Length; i++)
{
result[i] = dr[i].ToString();
}
foreach (string str in result)
Console.WriteLine(str);
Use ng-value
for set value of input box after clicking on a button
:
"input type="email" class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"
and
Set Value as:
$scope.myForm.email2 = $scope.names[0].success;
As Chris said before me, just an a
should override. For example:
a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }
In this instance the .nav a
would ALWAYS be green, the :hover wouldn't apply to it.
If there's some other rule affecting it, you COULD use !important
, but you shouldn't. It's a bad habit to fall into.
.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */
Then it'll always be green, irrelevant of any other rule.
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy
and paste it system-wide.
from http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
package
: take the compiled code and package it in its distributable format, such as a JAR.
install
: install the package into the local repository, for use as a dependency in other projects locally
So the answer to your question is, it depends on whether you want it in installed into your local repo. Install will also run package because it's higher up in the goal phase stack.
The old code for asking location won't work in iOS 8. You can try this method for location authorization:
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}
}
What about /usr/share/dict/words
on any Unix system? How many words are we talking about? Like OED-Unabridged?
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:
I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.
I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.
This command shows the configured heap sizes in bytes.
java -XX:+PrintFlagsFinal -version | grep HeapSize
It works on Amazon AMI on EC2 as well.
Install pip
Download get-pip. Remember to save it as "get-pip.py"
Now go to the download folder. Right click on get-pip.py then open with python.exe.
You can add system variable by
(by doing this you can use pip and easy_install without specifying path)
1 Clicking on Properties of My Computer
2 Then chose Advanced System Settings
3 Click on Advanced Tab
4 Click on Environment Variables
5 From System Variables >>> select variable path.
6 Click edit then add the following lines at the end of it
;c:\Python27;c:\Python27\Scripts
(please dont copy this, just go to your python directory and copy the paths similar to this)
NB:- you have to do this once only.
Install beautifulsoup4
Open cmd and type
pip install beautifulsoup4
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(7);
vec.push_back(4);
vec.push_back(9);
vec.push_back(7);
std::ostringstream oss;
if (!vec.empty())
{
// Convert all but the last element to avoid a trailing ","
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator<int>(oss, ","));
// Now add the last element with no delimiter
oss << vec.back();
}
std::cout << oss.str() << std::endl;
}
Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.
Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.
If you want to display single value access from database into textbox, please refer to the code below:
SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();
or
SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
>>> def delete_key(dict, key):
... del dict[key]
... return dict
...
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>
this doesn't do any error handling, it assumes the key is in the dict, you might want to check that first and raise
if its not
C++11 standard on ==
for std::vector
Others have mentioned that operator==
does compare vector contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.
We first look at Chapter 23.2.1 "General container requirements", which documents things that must be valid for all containers, including therefore std::vector
.
That section Table 96 "Container requirements" which contains an entry:
Expression Operational semantics =========== ====================== a == b distance(a.begin(), a.end()) == distance(b.begin(), b.end()) && equal(a.begin(), a.end(), b.begin())
The distance
part of the semantics means that the size of both containers are the same, but stated in a generalized iterator friendly way for non random access addressable containers. distance()
is defined at 24.4.4 "Iterator operations".
Then the key question is what does equal()
mean. At the end of the table we see:
Notes: the algorithm equal() is defined in Clause 25.
and in section 25.2.11 "Equal" we find its definition:
template<class InputIterator1, class InputIterator2> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template<class InputIterator1, class InputIterator2, class BinaryPredicate> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred);
1 Returns: true if for every iterator i in the range
[first1,last1)
the following corresponding conditions hold:*i == *(first2 + (i - first1))
,pred(*i, *(first2 + (i - first1))) != false
. Otherwise, returns false.
In our case, we care about the overloaded version without BinaryPredicate
version, which corresponds to the first pseudo code definition *i == *(first2 + (i - first1))
, which we see is just an iterator-friendly definition of "all iterated items are the same".
Similar questions for other containers:
I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.
See this blog post. It uses jQuery, but it should help you even if you are not using it.
Basically you add this to your document.ready()
$('iframe').load(function() {
RunAfterIFrameLoaded();
});
Sometimes if you are making a target via make files double check that all c files are named correctly with correct file structure.
Try this :
SELECT
(
SELECT
`NAME`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) as `NAME`
FROM
school_locations
WHERE
(
SELECT
`TYPE`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) = 'coun';
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
To run batch files using java if that's you're talking about...
String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`
This should do it.
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
I had this problem when trying to run Rails in a subdirectory, and not in /
. For example, I had Angular/Node/Gulp app running in /client
and a Rails app running in /server
, but both of them were in the same git repo, so I could track changes across the front end and back end. I got this error when trying to deploy them to Heroku. For anyone else having this issue, here is a custom buildpack that will allow running Rails in a subdirectory.
When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.
If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.
If they are not present, make blindly builds everything under the rule.
Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!
I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href
attribute of each links. It will match whether double or single quotes are used.
<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1
You can view a full explanation of this regex at here.
Snippet playground:
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
Text to match:_x000D_
<input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
_x000D_
<button>Match</button>_x000D_
</label>
_x000D_
my problem was I got stuck after xcode created the bridge file but still I got error in header file name MYPROJECTNAME-swift.h
1.I check in terminal and search for all auto created swift bridge files:
find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -
you see what xcode created.
Try using float: left
(or right
) instead of display: inline
. Inline display replaces list-item display, which is what adds the bullet points.
Java Language Specification says that
Program Exit
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.
I would implement a null safe comparator. There may be an implementation out there, but this is so straightforward to implement that I've always rolled my own.
Note: Your comparator above, if both names are null, won't even compare the value fields. I don't think this is what you want.
I would implement this with something like the following:
// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(final Metadata other) {
if (other == null) {
throw new NullPointerException();
}
int result = nullSafeStringComparator(this.name, other.name);
if (result != 0) {
return result;
}
return nullSafeStringComparator(this.value, other.value);
}
public static int nullSafeStringComparator(final String one, final String two) {
if (one == null ^ two == null) {
return (one == null) ? -1 : 1;
}
if (one == null && two == null) {
return 0;
}
return one.compareToIgnoreCase(two);
}
EDIT: Fixed typos in code sample. That's what I get for not testing it first!
EDIT: Promoted nullSafeStringComparator to static.
I had to control this in a script that ran on a machine with French locale, but a specific Java program had to run with en_US. As already pointed out, the following works:
java -Duser.language=en -Duser.country=US ...
Alternatively,
LC_ALL=en_US.UTF-8 java ...
I prefer the latter.
Running this:
sqllocaldb create "v12.0"
From cmd prompt solved this for me...
You can try the Boost Tokenizer library, in particular the Escaped List Separator
Use EditorFor rather than TextBoxFor
Here is another way to display PDF inside Div by using Iframe like below.
<div>_x000D_
<iframe src="/pdf/test.pdf" style="width:100%;height:700px;"></iframe>_x000D_
</div>_x000D_
<div>_x000D_
<!-- I agree button -->_x000D_
</div>
_x000D_
If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename)
several times until all cases are gone then attach(newfilename)
should have no output message.
If you are producing the entire output yourself, you can use sprintf()
, e.g.
> sprintf("%.10f",0.25)
[1] "0.2500000000"
specifies that you want to format a floating point number with ten decimal points (in %.10f
the f
is for float and the .10
specifies ten decimal points).
I don't know of any way of forcing R's higher level functions to print an exact number of digits.
Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.
I would recommend using rgba(255,255,255,0)
because broken (newest) safari thinks that if you are using transparent
or rgba(0,0,0,0)
in linear-gradent you really mean gray
, For more info please head to - What happens in Safari with the transparent color?
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
Another possible option, depending on what you need the array for:
$array = array('lastname', 'email', 'phone');
echo json_encode($array);
This will put '[' and ']' around the string, which you may or may not want.
I found this solution by Sebastian Ekström. It's quick, dirty, and works really well. Even if you don't know the parent's height:
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Read the full article here.
I ran into an issue where I have multiple node servers running, and I want to just kill one of them and redeploy it from a script.
Note: This example is in a bash shell on Mac.
To do so I make sure to make my node
call as specific as possible. For example rather than calling node server.js
from the apps directory, I call node app_name_1/app/server.js
Then I can kill it using:
kill -9 $(ps aux | grep 'node\ app_name_1/app/server.js' | awk '{print $2}')
This will only kill the node process running app_name_1/app/server.js.
If you ran node app_name_2/app/server.js
this node process will continue to run.
If you decide you want to kill them all you can use killall node
as others have mentioned.
In my case, the servlet-api.jar file in jre/lib/ext in the jdk directory conflicts with the servlet-api.jar file in tomcat, removing the servlet-api.jar in jre/lib/ext in the jdk directory can solve the problem.
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
Enter the following in the terminal:
$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path/to/your/file/projectname.app/projectname
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/
wget https://www.kernel.org/pub/software/scm/git/{version.gz}
tar -xzvf git-version.gz
cd git-version
./configure
make
make install
When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:
MyClass()
{
this(default1, default2);
}
MyClass(arg1, arg2)
{
validate arguments, etc...
note that your validation logic is only written once now
}
As for the super()
constructor, again unlike super.method()
access it must be the first line of your constructor. After that it is very much like the this()
constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:
YourClass extends MyClass
{
YourClass(arg1, arg2, arg3)
{
super(arg1, arg2) // calls MyClass(arg1, arg2)
validate and process arg3...
}
}
Additional information:
Even though you don't see it, the default no argument constructor always calls super()
first. Example:
MyClass()
{
}
is equivalent to
MyClass()
{
super();
}
I see that many have mentioned using the this
and super
keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.
You can look at the target of the mouseover
event on some suitable ancestor:
var currentElement = null;
document.addEventListener('mouseover', function (e) {
currentElement = e.target;
});
If you using roles you could check for ROLE_USER
that is the solution i use:
if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
// user is logged in
}
Two-way binding means that any data-related changes affecting the model are immediately propagated to the matching view(s), and that any changes made in the view(s) (say, by the user) are immediately reflected in the underlying model. When app data changes, so does the UI, and conversely.
This is a very solid concept to build a web application on top of, because it makes the "Model" abstraction a safe, atomic data source to use everywhere within the application. Say, if a model, bound to a view, changes, then its matching piece of UI (the view) will reflect that, no matter what. And the matching piece of UI (the view) can safely be used as a mean of collecting user inputs/data, so as to maintain the application data up-to-date.
A good two-way binding implementation should obviously make this connection between a model and some view(s) as simple as possible, from a developper point of view.
It is then quite untrue to say that Backbone does not support two-way binding: while not a core feature of the framework, it can be performed quite simply using Backbone's Events though. It costs a few explicit lines of code for the simple cases; and can become quite hazardous for more complex bindings. Here is a simple case (untested code, written on the fly just for the sake of illustration):
Model = Backbone.Model.extend
defaults:
data: ''
View = Backbone.View.extend
template: _.template("Edit the data: <input type='text' value='<%= data %>' />")
events:
# Listen for user inputs, and edit the model.
'change input': @setData
initialize: (options) ->
# Listen for model's edition, and trigger UI update
@listenTo @model, 'change:data', @render
render: ->
@$el.html @template(@model.attributes)
@
setData: (e) =>
e.preventDefault()
@model.set 'data', $(e.currentTarget).value()
model: new Model()
view = new View {el: $('.someEl'), model: model}
This is a pretty typical pattern in a raw Backbone application. As one can see, it requires a decent amount of (pretty standard) code.
AngularJS and some other alternatives (Ember, Knockout…) provide two-way binding as a first-citizen feature. They abstract many edge-cases under some DSL, and do their best at integrating two-way binding within their ecosystem. Our example would look something like this with AngularJS (untested code, see above):
<div ng-app="app" ng-controller="MainCtrl">
Edit the data:
<input name="mymodel.data" ng-model="mymodel.data">
</div>
angular.module('app', [])
.controller 'MainCtrl', ($scope) ->
$scope.mymodel = {data: ''}
Rather short!
But, be aware that some fully-fledged two-way binding extensions do exist for Backbone as well (in raw, subjective order of decreasing complexity): Epoxy, Stickit, ModelBinder…
One cool thing with Epoxy, for instance, is that it allows you to declare your bindings (model attributes <-> view's DOM element) either within the template (DOM), or within the view implementation (JavaScript). Some people strongly dislike adding "directives" to the DOM/template (such as the ng-* attributes required by AngularJS, or the data-bind attributes of Ember).
Taking Epoxy as an example, one can rework the raw Backbone application into something like this (…):
Model = Backbone.Model.extend
defaults:
data: ''
View = Backbone.Epoxy.View.extend
template: _.template("Edit the data: <input type='text' />")
# or, using the inline form: <input type='text' data-bind='value:data' />
bindings:
'input': 'value:data'
render: ->
@$el.html @template(@model.attributes)
@
model: new Model()
view = new View {el: $('.someEl'), model: model}
All in all, pretty much all "mainstream" JS frameworks support two-way binding. Some of them, such as Backbone, do require some extra work to make it work smoothly, but those are the same which do not enforce a specific way to do it, to begin with. So it is really about your state of mind.
Also, you may be interested in Flux, a different architecture for web applications promoting one-way binding through a circular pattern. It is based on the concept of fast, holistic re-rendering of UI components upon any data change to ensure cohesiveness and make it easier to reason about the code/dataflow. In the same trend, you might want to check the concept of MVI (Model-View-Intent), for instance Cycle.
Be sure to include the $route service into your scope and do this:
$route.reload();
See this:
Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
...and you might also want to do this too:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline 1 */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000, _x000D_
/* Outline 2 */_x000D_
-2px -2px 0 #ff0000,_x000D_
2px -2px 0 #ff0000,_x000D_
-2px 2px 0 #ff0000,_x000D_
2px 2px 0 #ff0000, _x000D_
-3px 0 0 #ff0000,_x000D_
3px 0 0 #ff0000,_x000D_
0 3px 0 #ff0000,_x000D_
0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.
Have fun!
Java 8 Comparator
interface has a reversed
method : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reversed--
This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.
To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell
2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.
Import-Module MSOnline
After it complete, we can use this command to check it.
PS C:\Users> Get-Module -ListAvailable -Name MSOnline*
Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.1.166.0 MSOnline {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest 1.1.166.0 MSOnlineExtended {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
More information about this issue, please refer to it.
Update:
We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.
Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.
In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )
tesseract --tessdata-dir <tessdata-folder> <image-path> stdout --oem 2 -l <lng>
In my case, the mistakes that I've made or attempts that wasn't a success.
TESSDATA_PREFIX
with above pathsFirst 2 attempts did not worked because, the files from git clone
did not worked for the reasons that I do not know. I am not sure why #3 attempt worked for me.
Finally,
wget
--tessdata-dir
with directory nameTake away for me is to learn the tool well & make use of it, rather than relying on package manager installation & directories
Java 8 provides different utility api methods to help us sort the streams better.
If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.
List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);
Creating comparator on fly:
integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);
With default comparator provided by java 8 when no argument passed to sorted():
integerList.stream().sorted().forEach(System.out::println); //Natural order
If you want to sort the same list in reverse order:
integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order
If your list is a list of user defined objects, then:
List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
new Person(2000, "Second", 30, 45000),
new Person(3000, "Third", 35, 25000));
Creating comparator on fly:
personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
.forEach(person -> System.out.println(person.getName()));
Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):
personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
Using Comparator.comparing() method(Generic method which compares based on the getter method provided):
personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
We can do chaining too using thenComparing() method:
personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.
Person class
public class Person {
private long personId;
private String name;
private int age;
private double salary;
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public Person(long personId, String name, int age, double salary) {
this.personId = personId;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
I didn't see a simple one line solution without any dependencies. I simple use
List<Users> list;
Iterable<IterableUsers> users = getUsers();
// one line solution
list = StreamSupport.stream(users.spliterator(), true).collect(Collectors.toList());
Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0
in the beginning of your script. This will help you to catch misspelled variable names. Like so,
# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"
PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
+ CategoryInfo : InvalidOperation: (fo:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,
$file = "\\server\share\file.txt"
cat $file
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit: "Address can have a max of 100 characters"
The placeholders I am aware of are:
Much thanks to bloudraak for initially pointing this out.
As other users have mentioned, enumerate
is a generator that adds an incremental index next to each item of an iterable.
So if you have a list say l = ["test_1", "test_2", "test_3"]
, the list(enumerate(l))
will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
.
Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).
for index, value in enumerate(joint_values):
if index == 3:
continue
# Do something with the other `value`
So your code reads better because you could also do a regular for loop with range
but then to access the items you need to index them (i.e., joint_values[i]
).
Although another user mentioned an implementation of enumerate
using zip
, I think a more pure (but slightly more complex) way without using itertools
is the following:
def enumerate(l, start=0):
return zip(range(start, len(l) + start), l)
Example:
l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)
Output:
[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]
As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate
function does.
If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then
I believe Tim is right. You have a Form Control. For that you have to use this
If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then
cd into the repo/directory that you're pushing into on the remote machine and enter
$ git config core.bare true
Here you go:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt
Or:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt
Solution 1 (Elegant approach with great user experience)
HTML
<input id="inputID" class="uppercase" name="inputName" value="" />
CSS
.uppercase{
text-transform: uppercase;
}
JS
$('#inputID').on('blur', function(){
this.value = this.value.toUpperCase();
});
By using CSS text-transform: uppercase;
you'll eliminate the animation of lower to uppercase as the user types into the field.
Use blur
event to handle converting to uppercase. This happens behind the scene as CSS took care of the user's visually appealing masking.
Solution 2 (Great, but less elegant)
If you insist on using keyup
, here it is...
$('#inputID').on('keyup', function(){
var caretPos = this.selectionStart;
this.value = this.value.toUpperCase();
this.setSelectionRange(caretPos, caretPos);
});
User would notice the animation of lowercase to uppercase as they type into the field. It gets the job done.
Solution 3 (Just get the job done)
$('#inputID').on('keyup', function(){
this.value = this.value.toUpperCase();
});
This method is most commonly suggested but I do not recommend.
The downside of this solution is you'll be annoying the user as the cursor's caret position keeps jumping to the end of the text after every key input. Unless you know your users will never encounter typos or they will always clear the text and retype every single time, this method works.
g++ test.cpp LinearNode.cpp LinkedList.cpp -o test
If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.
See this SO question/answer for more details on the SSL options in that file.
Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)
So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:
git log path/to/file
If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch
option:
git log -p path/to/file
Or, if you prefer the graphical view of gitk
gitk path/to/file
You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.
Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:
# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit
(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add
to add it to the index in preparation for committing.)
If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git
can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.
For Play 2.2.x on Windows with a distributable tar file I created a file in the distributable root directory called: {PROJECT_NAME}_config.txt and added:
-Dhttp.port=8080
Where {PROJECT_NAME} should be replaced with the name of your project. Then started the {PROJECT_NAME}.bat script as usual in the bin\ directory.
//A custom toast class where you can show custom or default toast as desired)
public class ToastMessage {
private Context context;
private static ToastMessage instance;
/**
* @param context
*/
private ToastMessage(Context context) {
this.context = context;
}
/**
* @param context
* @return
*/
public synchronized static ToastMessage getInstance(Context context) {
if (instance == null) {
instance = new ToastMessage(context);
}
return instance;
}
/**
* @param message
*/
public void showLongMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* @param message
*/
public void showSmallMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* The Toast displayed via this method will display it for short period of time
*
* @param message
*/
public void showLongCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
/**
* The toast displayed by this class will display it for long period of time
*
* @param message
*/
public void showSmallCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
I was able to call stored procedure in a view (SQL Server 2005).
CREATE FUNCTION [dbo].[dimMeasure]
RETURNS TABLE AS
(
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost; Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')
)
RETURN
GO
Inside stored procedure we need to set:
set nocount on
SET FMTONLY OFF
CREATE VIEW [dbo].[dimMeasure]
AS
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')
GO
In Laravel 6.x
// Retrieve a piece of data from the session...
$value = session('key');
// Specifying a default value...
$value = session('key', 'default');
// Store a piece of data in the session...
session(['key' => 'value']);
Nothing wrong with your method, it's a G-mail security issue.
Login g-mail account settings.
Enable 2-step verification.
Use new-generated password in place of your real g-mail password.
Don't forget to clear cache.
php artisan config:cache.
php artisan config:clear.
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=generatedAppPassword
MAIL_ENCRYPTION=tls
Here you go:
DECLARE
BEGIN
dbms_output.enable(NULL); -- Disables the limit of DBMS
-- Your print here !
END;
I have a cron job that calls a php script and, some times, it get stuck on php script. This solution was perfect to me.
I use:
scripttimeout -t 60 /script.php
There's no need to use a lambda, when you can remove all the null ones, and put one back if the input size changes:
input = [Object(name=""), Object(name="fake_name"), Object(name="")]
output = [x for x in input if x.name]
if(len(input) != len(output)):
output.append(Object(name=""))
You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:
boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))
If it is a String, you could do this:
boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))
Since setEditable(false)
is deprecated, use textView.setKeyListener(null);
to make editText non-clickable.
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
For what it's worth I wrote this to truncate to word boundary without leaving punctuation or whitespace at the end of the string:
function truncateStringToWord(str, length, addEllipsis)_x000D_
{_x000D_
if(str.length <= length)_x000D_
{_x000D_
// provided string already short enough_x000D_
return(str);_x000D_
}_x000D_
_x000D_
// cut string down but keep 1 extra character so we can check if a non-word character exists beyond the boundary_x000D_
str = str.substr(0, length+1);_x000D_
_x000D_
// cut any non-whitespace characters off the end of the string_x000D_
if (/[^\s]+$/.test(str))_x000D_
{_x000D_
str = str.replace(/[^\s]+$/, "");_x000D_
}_x000D_
_x000D_
// cut any remaining non-word characters_x000D_
str = str.replace(/[^\w]+$/, "");_x000D_
_x000D_
var ellipsis = addEllipsis && str.length > 0 ? '…' : '';_x000D_
_x000D_
return(str + ellipsis);_x000D_
}_x000D_
_x000D_
var testString = "hi stack overflow, how are you? Spare";_x000D_
var i = testString.length;_x000D_
_x000D_
document.write('<strong>Without ellipsis:</strong><br>');_x000D_
_x000D_
while(i > 0)_x000D_
{_x000D_
document.write(i+': "'+ truncateStringToWord(testString, i) +'"<br>');_x000D_
i--;_x000D_
}_x000D_
_x000D_
document.write('<strong>With ellipsis:</strong><br>');_x000D_
_x000D_
i = testString.length;_x000D_
while(i > 0)_x000D_
{_x000D_
document.write(i+': "'+ truncateStringToWord(testString, i, true) +'"<br>');_x000D_
i--;_x000D_
}
_x000D_
Best thing to do is
(Date1-Date2)/86 400 000
That number is the number of milliseconds in a day.
One date-other date gives you difference in milliseconds.
Collect the answer in a double variable.
If using the Win32 API you can use the FindFirstFile and FindNextFile functions.
http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx
For recursive traversal of directories you must inspect each WIN32_FIND_DATA.dwFileAttributes to check if the FILE_ATTRIBUTE_DIRECTORY bit is set. If the bit is set then you can recursively call the function with that directory. Alternatively you can use a stack for providing the same effect of a recursive call but avoiding stack overflow for very long path trees.
#include <windows.h>
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
bool ListFiles(wstring path, wstring mask, vector<wstring>& files) {
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
wstring spec;
stack<wstring> directories;
directories.push(path);
files.clear();
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\" + mask;
directories.pop();
hFind = FindFirstFile(spec.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
return false;
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 &&
wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"\\" + ffd.cFileName);
}
else {
files.push_back(path + L"\\" + ffd.cFileName);
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
return false;
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
return true;
}
int main(int argc, char* argv[])
{
vector<wstring> files;
if (ListFiles(L"F:\\cvsrepos", L"*", files)) {
for (vector<wstring>::iterator it = files.begin();
it != files.end();
++it) {
wcout << it->c_str() << endl;
}
}
return 0;
}
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
In case someone lands here after making the same mistake I did:
plugin="mysql_native_password"
temporarily. Performed my tasks.plugin="auth_socket"
which resulted in mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"
mysql_safe
to bypass authentication in order to switch to the appropriate plugin plugin="unix_socket"
Hopefully this saves someone some time if they receive the original poster's error message, but the true cause was flubbing the plugin name, not actually lacking the existence of the "auth_socket" plugin itself, which according to the MariaDB documentation:
In MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default, and it is used by the 'root'@'localhost' user account by default.
From Tomcat Documentation
maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.
maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.
It's worth noting that perldoc perllocal will only report on modules installed via CPAN. If someone installs modules manually, it won't find them. Also, if you have multiple people installing modules and the perllocal.pod is under source control, people might resolve conflicts incorrectly and corrupt the list (this has happened here at work, for example).
Regrettably, the solution appears to be walking through @INC with File::Find or something similar. However, that doesn't just find the modules, it also finds related modules in a distribution. For example, it would report TAP::Harness and TAP::Parser in addition to the actual distribution name of Test::Harness (assuming you have version 3 or above). You could potentially match them up with distribution names and discard those names which don't match, but then you might be discarding locally built and installed modules.
I believe brian d foy's backpan indexing work is supposed to have code to hand it at .pm file and it will attempt to infer the distribution, but even this fails at times because what's in a package is not necessarily installed (see Devel::Cover::Inc for an example).
is all this really necessary, human perception and CRT vs LCD will vary, but the R G B intensity does not, Why not L = (R + G + B)/3
and set the new RGB to L, L, L?
You can use jQuery :contains() Selector
var element = $( "a:contains('SearchingText')" );
Try to make use of linq to Dataset
(from b in table1.AsEnumerable()
select new { id = b.Field<int>("id")}).Except(
from a in table2.AsEnumerable()
select new {id = a.Field<int>("id")})
Check this article : Comparing DataSets using LINQ
OpenProcess Function
From MSDN:
To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.
You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.
In first activity u can send intent using startActivityForResult()
and then get result from second activity after it finished using setResult
.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
// send intent for result
startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
}
// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
SecondActivity.class
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
The documentation is misleading.
I have the following code running in production
DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
SET @sql = 'SELECT UserID FROM UserTable'
*/
INSERT INTO @table
EXEC(@sql)
SELECT * FROM @table
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
println "x value: ${x}"
println x.getClass().name
?.
checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject
.
Assuming you're happy with truncating towards zero, just cast:
double d = 1234.56;
long x = (long) d; // x = 1234
This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.
This should work:
quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE
official Link of DB 2 JDBC Driver from IBM
I just wanted to share my experience
For me,
$('#selectorId').val()
returned null.
I had to use
$('#selectorId option:selected').val()
Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
I have same problem once.I solved this by File->Open->other project,then switch this project by this way.
If you right-click on your "Computer" (or "My Computer") icon and select "Manage" from the pop-up menu, that'll take you to the Computer Management console.
In there, under System Tools\Shared Folders, you'll find "Open Files". This is probably close to what you want, but if the file is on a network share then you'd need to do the same thing on the server on which the file lives.
Encoding.GetString Method (Byte[]) convert bytes to a string.
When overridden in a derived class, decodes all the bytes in the specified byte array into a string.
Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Syntax
public virtual string GetString(byte[] bytes)
Parameters
bytes
Type: System.Byte[]
The byte array containing the sequence of bytes to decode.
Return Value
Type: System.String
A String containing the results of decoding the specified sequence of bytes.
Exceptions
ArgumentException - The byte array contains invalid Unicode code points.
ArgumentNullException - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.
Remarks
If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.
See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.
The literal 0
has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.
As your setval
function can accept either an int
or a char*
, the compiler can not decide which overload you meant.
The easiest solution is to just cast the 0
to the right type.
Another option is to ensure the int
overload is preferred, for example by making the other one a template:
class huge
{
private:
unsigned char data[BYTES];
public:
void setval(unsigned int);
template <class T> void setval(const T *); // not implemented
template <> void setval(const char*);
};
You pass the exception directly to the logger, e.g.
try {
...
} catch (Exception e) {
log.error( "failed!", e );
}
It's up to log4j to render the stack trace.
The function pthread_mutex_lock()
either acquires the mutex for the calling thread or blocks the thread until the mutex can be acquired. The related pthread_mutex_unlock()
releases the mutex.
Think of the mutex as a queue; every thread that attempts to acquire the mutex will be placed on the end of the queue. When a thread releases the mutex, the next thread in the queue comes off and is now running.
A critical section refers to a region of code where non-determinism is possible. Often this because multiple threads are attempting to access a shared variable. The critical section is not safe until some sort of synchronization is in place. A mutex lock is one form of synchronization.
The dataset:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
Now you can convert the data frame into a matrix and use the barplot
function.
barplot(as.matrix(dat))
In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug (this one), that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime (and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours):
function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
// or whatever start and end \DateTimeInterface objects you like
$start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
$end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
// count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
$hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
// find transitions and check, if there is one that leads to a positive offset
// that isn't added by \DatePeriod
// this is the workaround for https://bugs.php.net/bug.php?id=75685
$transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
$hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
}
return $hours;
}
$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!
$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744
P.S. If you check a (longer) timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.
I had the same problem after upgrading to Windows 10.
This worked for me
Set-ExecutionPolicy Unrestricted
If it still doesn't work try editing devenv.exe.config
Visual Studio 2013: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\12.0
Visual Studio 2015: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\14.0
Add the following
<dependentAssembly>
<assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Utility" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.ConsoleHost" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Management" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Security" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.PowerShell.Commands.Diagnostics" publicKeyToken="31bf3856ad364e35" />
<publisherPolicy apply="no" />
</dependentAssembly>
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf
instead of System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
change import cv
to import cv2.cv as cv
See also the post here.
Its mostly caused due to some unicode characters. In my case it was the Rupee currency symbol.
To quickly fix this, I had to spot the character causing this error. I copy pasted the entire text in a text editor like vi and replaced the troubling character with a text one.
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
It's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image
I have found that you have to comment out the namespace wrapping the the class at time when moving between version of Visual Studio:
'Namespace FormsAuth
'End Namespace
and at other times, I have to uncomment the namespace.
This happened to me several times when other developers edited the same solution using a different version of VS and/or I moved (copied) the solution to another location
If you want to pass dynamic constructor parameters to the class, you can use this code:
$reflectionClass = new ReflectionClass($className);
$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);
More information on dynamic classes and parameters
As of PHP 5.6 you can simplify this even more by using Argument Unpacking:
// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);
Thanks to DisgruntledGoat for pointing that out.
Researching this topic myself and having read the answers I recommend using the path.py library since it provides a context manager for changing the current working directory.
You then have something like
import path
if path.Path('../lib').isdir():
with path.Path('..'):
import lib
Although, you might just omit the isdir
statement.
Here I'll add print statements to make it easy to follow what's happening
import path
import pandas
print(path.Path.getcwd())
print(path.Path('../lib').isdir())
if path.Path('../lib').isdir():
with path.Path('..'):
print(path.Path.getcwd())
import lib
print('Success!')
print(path.Path.getcwd())
which outputs in this example (where lib is at /home/jovyan/shared/notebooks/by-team/data-vis/demos/lib
):
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
/home/jovyan/shared/notebooks/by-team/data-vis/demos
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
Since the solution uses a context manager, you are guaranteed to go back to your previous working directory, no matter what state your kernel was in before the cell and no matter what exceptions are thrown by importing your library code.
I have a simple solution which is working perfectly. The code is not mine, I found it on this link. Here are the steps to follow:
1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.
public void saveImage(Context context, Bitmap b, String imageName)
{
FileOutputStream foStream;
try
{
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
foStream.close();
}
catch (Exception e)
{
Log.d("saveImage", "Exception 2, Something went wrong!");
e.printStackTrace();
}
}
2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
@Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, "my_image.png");
}
}
3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.
new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");
The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.
IMO this solves the issue! If you want further steps such as load the image you can follow these extra steps:
4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.
someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));
6. To get the image full path by image name.
File file = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();
7. Check if the image file exists.
File file =
getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");
To delete the image file.
File file = getApplicationContext().getFileStreamPath("my_image.jpeg"); if (file.delete()) Log.d("file", "my_image.jpeg deleted!");
I think it's worth answering the generic question "R - test if string contains string" here.
For that, use the grep function.
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
You might be specifying a wrong version of java. java -version(in your terminal) to check the version of java you are using. Go to maven-compile-plugin for the latest maven compiler version Your plugin may appear like this if you are using java 6 and the latest version of maven compiler plugin is 3.1
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
A little bit of history now. Among other languages, BCPL had a fairly major influence on C's early development. If you declared an array in BCPL with something like:
let V = vec 10
that actually allocated 11 words of memory, not 10. Typically V was the first, and contained the address of the immediately following word. So unlike C, naming V went to that location and picked up the address of the zeroeth element of the array. Therefore array indirection in BCPL, expressed as
let J = V!5
really did have to do J = !(V + 5)
(using BCPL syntax) since it was necessary to fetch V to get the base address of the array. Thus V!5
and 5!V
were synonymous. As an anecdotal observation, WAFL (Warwick Functional Language) was written in BCPL, and to the best of my memory tended to use the latter syntax rather than the former for accessing the nodes used as data storage. Granted this is from somewhere between 35 and 40 years ago, so my memory is a little rusty. :)
The innovation of dispensing with the extra word of storage and having the compiler insert the base address of the array when it was named came later. According to the C history paper this happened at about the time structures were added to C.
Note that !
in BCPL was both a unary prefix operator and a binary infix operator, in both cases doing indirection. just that the binary form included an addition of the two operands before doing the indirection. Given the word oriented nature of BCPL (and B) this actually made a lot of sense. The restriction of "pointer and integer" was made necessary in C when it gained data types, and sizeof
became a thing.
You could also use POSIX regular expressions, like
SELECT id FROM groups where name ~* 'administrator'
SELECT 'asd' ~* 'AsD'
returns t
There's a lot of great answers but they either use command line or some external program for profiling and/or sorting the results.
I really missed some way I could use in my IDE (eclipse-PyDev) without touching the command line or installing anything. So here it is.
def count():
from math import sqrt
for x in range(10**5):
sqrt(x)
if __name__ == '__main__':
import cProfile, pstats
cProfile.run("count()", "{}.profile".format(__file__))
s = pstats.Stats("{}.profile".format(__file__))
s.strip_dirs()
s.sort_stats("time").print_stats(10)
See docs or other answers for more info.
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
I just installed oracle11g
ORA-65096: invalid common user or role name in oracle
No, you have installed Oracle 12c. That error could only be on 12c
, and cannot be on 11g
.
Always check your database version up to 4 decimal places:
SELECT banner FROM v$version WHERE ROWNUM = 1;
Oracle 12c multitenant container database has:
You must have created the database as a container database. While, you are trying to create user in the container, i.e. CDB$ROOT, however, you should create the user in the PLUGGABLE database.
You are not supposed to create application-related objects in the container, the container holds the metadata for the pluggable databases. You should use the pluggable database for you general database operations. Else, do not create it as container, and not use multi-tenancy. However, 12cR2 onward you cannot create a non-container database anyway.
And most probably, the sample schemas might have been already installed, you just need to unlock them in the pluggable database.
For example, if you created pluggable database as pdborcl
:
sqlplus SYS/password@PDBORCL AS SYSDBA
SQL> ALTER USER scott ACCOUNT UNLOCK IDENTIFIED BY tiger;
sqlplus scott/tiger@pdborcl
SQL> show user;
USER is "SCOTT"
To show the PDBs and connect to a pluggable database from root container:
SQL> show con_name
CON_NAME
------------------------------
CDB$ROOT
SQL> show pdbs
CON_ID CON_NAME OPEN MODE RESTRICTED
---------- ------------------------------ ---------- ----------
2 PDB$SEED READ ONLY NO
3 ORCLPDB READ WRITE NO
SQL> alter session set container = ORCLPDB;
Session altered.
SQL> show con_name;
CON_NAME
------------------------------
ORCLPDB
I suggest read, Oracle 12c Post Installation Mandatory Steps
Note: Answers suggesting to use the _ORACLE_SCRIPT
hidden parameter to set to true is dangerous in a production system and might also invalidate your support contract. Beware, without consulting Oracle support DO NOT use hidden parameters.
I know it's an old question, but the tag library http://www.springframework.org/tags
is provided by spring-webmvc
package. With Maven it can be added to the project with the following lines to be added in the pom.xml
<properties>
<spring.version>3.0.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
Without Maven, just add that jar to your classpath. In any case it's not necessary to refer the tld file directly, it will be automatically found.