This is the simplest way to do it. Allows for group authorities, as well as user authorities.
-- Postgres syntax
create table users (
user_id serial primary key,
enabled boolean not null default true,
password text not null,
username citext not null unique
);
create index on users (username);
create table groups (
group_id serial primary key,
name citext not null unique
);
create table authorities (
authority_id serial primary key,
authority citext not null unique
);
create table user_authorities (
user_id int references users,
authority_id int references authorities,
primary key (user_id, authority_id)
);
create table group_users (
group_id int references groups,
user_id int referenecs users,
primary key (group_id, user_id)
);
create table group_authorities (
group_id int references groups,
authority_id int references authorities,
primary key (group_id, authority_id)
);
Then in META-INF/applicationContext-security.xml
<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />
<authentication-manager>
<authentication-provider>
<jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from users where username=?"
authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"
group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"
/>
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
Here is a way to remove a specific commit id knowing only the commit id you would like to remove.
git rebase --onto commit-id^ commit-id
Note that this actually removes the change that was introduced by the commit.
Electron + Angular 2/4 addition:
On top of adding the 'node' type to ts.config various files, what eventually worked for me was adding the next to the
typings.d.ts
file:
declare var window: Window;
interface Window {
process: any;
require: any;
}
Note that my case is developing with Electron + Angular 2/4. I needed the require on the window global.
use only see a tables
=> \dt
if want to see schema tables
=>\dt+
if you want to see specific schema tables
=>\dt schema_name.*
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
if you want to do it only with the LocalDate-class:
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = LocalDate.of(initial.getYear(), initial.getMonthValue(),1);
// Idea: the last day is the same as the first day of next month minus one day.
LocalDate end = LocalDate.of(initial.getYear(), initial.getMonthValue(), 1).plusMonths(1).minusDays(1);
I made a procedure that execute a FOREACH
with CURSOR
for any table.
Example of use:
CREATE TABLE #A (I INT, J INT)
INSERT INTO #A VALUES (1, 2), (2, 3)
EXEC PRC_FOREACH
#A --Table we want to do the FOREACH
, 'SELECT @I, @J' --The execute command, each column becomes a variable in the same type, so DON'T USE SPACES IN NAMES
--The third variable is the database, it's optional because a table in TEMPB or the DB of the proc will be discovered in code
The result is 2 selects for each row.
The syntax of UPDATE
and break the FOREACH
are written in the hints.
This is the proc code:
CREATE PROC [dbo].[PRC_FOREACH] (@TBL VARCHAR(100) = NULL, @EXECUTE NVARCHAR(MAX)=NULL, @DB VARCHAR(100) = NULL) AS BEGIN
--LOOP BETWEEN EACH TABLE LINE
IF @TBL + @EXECUTE IS NULL BEGIN
PRINT '@TBL: A TABLE TO MAKE OUT EACH LINE'
PRINT '@EXECUTE: COMMAND TO BE PERFORMED ON EACH FOREACH TRANSACTION'
PRINT '@DB: BANK WHERE THIS TABLE IS (IF NOT INFORMED IT WILL BE DB_NAME () OR TEMPDB)' + CHAR(13)
PRINT 'ROW COLUMNS WILL VARIABLE WITH THE SAME NAME (COL_A = @COL_A)'
PRINT 'THEREFORE THE COLUMNS CANT CONTAIN SPACES!' + CHAR(13)
PRINT 'SYNTAX UPDATE:
UPDATE TABLE
SET COL = NEW_VALUE
WHERE CURRENT OF MY_CURSOR
CLOSE CURSOR (BEFORE ALL LINES):
IF 1 = 1 GOTO FIM_CURSOR'
RETURN
END
SET @DB = ISNULL(@DB, CASE WHEN LEFT(@TBL, 1) = '#' THEN 'TEMPDB' ELSE DB_NAME() END)
--Identifies the columns for the variables (DECLARE and INTO (Next cursor line))
DECLARE @Q NVARCHAR(MAX)
SET @Q = '
WITH X AS (
SELECT
A = '', @'' + NAME
, B = '' '' + type_name(system_type_id)
, C = CASE
WHEN type_name(system_type_id) IN (''VARCHAR'', ''CHAR'', ''NCHAR'', ''NVARCHAR'') THEN ''('' + REPLACE(CONVERT(VARCHAR(10), max_length), ''-1'', ''MAX'') + '')''
WHEN type_name(system_type_id) IN (''DECIMAL'', ''NUMERIC'') THEN ''('' + CONVERT(VARCHAR(10), precision) + '', '' + CONVERT(VARCHAR(10), scale) + '')''
ELSE ''''
END
FROM [' + @DB + '].SYS.COLUMNS C WITH(NOLOCK)
WHERE OBJECT_ID = OBJECT_ID(''[' + @DB + '].DBO.[' + @TBL + ']'')
)
SELECT
@DECLARE = STUFF((SELECT A + B + C FROM X FOR XML PATH('''')), 1, 1, '''')
, @INTO = ''--Read the next line
FETCH NEXT FROM MY_CURSOR INTO '' + STUFF((SELECT A + '''' FROM X FOR XML PATH('''')), 1, 1, '''')'
DECLARE @DECLARE NVARCHAR(MAX), @INTO NVARCHAR(MAX)
EXEC SP_EXECUTESQL @Q, N'@DECLARE NVARCHAR(MAX) OUTPUT, @INTO NVARCHAR(MAX) OUTPUT', @DECLARE OUTPUT, @INTO OUTPUT
--PREPARE TO QUERY
SELECT
@Q = '
DECLARE ' + @DECLARE + '
-- Cursor to scroll through object names
DECLARE MY_CURSOR CURSOR FOR
SELECT *
FROM [' + @DB + '].DBO.[' + @TBL + ']
-- Opening Cursor for Reading
OPEN MY_CURSOR
' + @INTO + '
-- Traversing Cursor Lines (While There)
WHILE @@FETCH_STATUS = 0
BEGIN
' + @EXECUTE + '
-- Reading the next line
' + @INTO + '
END
FIM_CURSOR:
-- Closing Cursor for Reading
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR'
EXEC SP_EXECUTESQL @Q --MAGIA
END
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
In addition, correct way to count total item number would be:
sum(len(x) for x in input)
Please try this one option:
task RunTest(type: Test) {
systemProperty "spring.profiles.active", System.getProperty("DEV")
include 'com/db/project/Test1.class'
}
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
If you use has_many through, and want to alias:
has_many :alias_name, through: model_name, source: initial_name
M.Ali's answer could be modified as
select Cast(Cast((37.0/38.0)*100 as decimal(18,2)) as varchar(5)) + ' %' as Percentage
Kind of, use the XmlAttribute
instead of XmlElement
, but it won't look like what you want. It will look like the following:
<SomeModel SomeStringElementName="testData">
</SomeModel>
The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.
// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}
[XmlAttribute("value")]
public string Value { get; }
}
[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }
[XmlIgnore]
public int SomeInfo { get; set; }
[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}
In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
To get the values from the Textview
we have to use this method
val str: String = textView.text.toString()
println("the value is $str")
Upgrade your pear/MDB2 from console:
# pear upgrade MDB2-beta
# pear upgrade MDB2_Driver_Mysql-beta
Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.
I had problems with the relative source in Silverlight. After searching and reading I did not find a suitable solution without using some additional Binding library. But, here is another approach for gaining access to the parent DataContext by directly referencing an element of which you know the data context. It uses Binding ElementName
and works quite well, as long as you respect your own naming and don't have heavy reuse of templates
/styles
across components:
<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content={Binding MyLevel2Property}
Command={Binding ElementName=level1Lister,
Path=DataContext.MyLevel1Command}
CommandParameter={Binding MyLevel2Property}>
</Button>
<DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
This also works if you put the button into Style
/Template
:
<Border.Resources>
<Style x:Key="buttonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Button Command={Binding ElementName=level1Lister,
Path=DataContext.MyLevel1Command}
CommandParameter={Binding MyLevel2Property}>
<ContentPresenter/>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Border.Resources>
<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding MyLevel2Property}"
Style="{StaticResource buttonStyle}"/>
<DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
At first I thought that the x:Names
of parent elements are not accessible from within a templated item, but since I found no better solution, I just tried, and it works fine.
To timeout the slowcommand
after 1 second:
timeout 1 slowcommand || echo "I failed, perhaps due to time out"
To determine whether the command timed out or failed for its own reasons, check whether the status code is 124:
# ping for 3 seconds, but timeout after only 1 second
timeout 1 ping 8.8.8.8 -w3
EXIT_STATUS=$?
if [ $EXIT_STATUS -eq 124 ]
then
echo 'Process Timed Out!'
else
echo 'Process did not timeout. Something else went wrong.'
fi
exit $EXIT_STATUS
Note that when the exit status is 124, you don't know whether it timed out due to your timeout
command, or whether the command itself terminated due to some internal timeout logic of its own and then returned 124. You can safely assume in either case, though, that a timeout of some kind happened.
You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to
table.Variable2 LIKE '%' || :VarB || '%'
and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.
You could also change the Sql to
table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'
It is the $sce
service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.
You can disable it completely, but it's not recommended
angular.module('myAppWithSceDisabledmyApp', [])
.config(function($sceProvider) {
$sceProvider.enabled(false);
});
for more info https://docs.angularjs.org/api/ng/service/$sce
For those who seem to be following the answers above but still have the problem (e.g., see the first comment on the poster's question):
You are probably working in a solution with many projects. The project you appear to be working in references other projects, but you are actually modifying a file from one of the other projects. For example:
System.Web.Extensions
But if the file you are modifying to use System.Web.Script.Serialization
is in project B, then you will need to add a reference to System.Web.Extension
in project B as well.
Using 'now()' as default value automatically generates time-stamp.
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
<>
means NOT EQUAL TO, !=
also means NOT EQUAL TO. It's just another syntactic sugar. both <>
and !=
are same.
The below two examples are doing the same thing. Query publisher table to bring results which are NOT EQUAL TO <> !=
USA.
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country <> "USA";
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country != "USA";
Note this
function FollowMouse() {
for(var i=0; i< arguments.length; i++) {
arguments[i].style.top = event.clientY+"px";
arguments[i].style.left = event.clientX+"px";
}
};
//---------------------------
html page
<body onmousemove="FollowMouse(d1,d2,d3)">
<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>
</body>
can call function with any Args
<body onmousemove="FollowMouse(d1,d2)">
or
<body onmousemove="FollowMouse(d1)">
The Bitwise operators are used to perform operations a bit-level or to manipulate bits in different ways. The bitwise operations are found to be much faster and are some times used to improve the efficiency of a program. Basically, Bitwise operators can be applied to the integer types: long, int, short, char and byte.
They are classified into two categories left shift and the right shift.
Output: 6, Here the binary representation of 3 is 0...0011(considering 32-bit system) so when it shifted one time the leading zero is ignored/lost and all the rest 31 bits shifted to left. And zero is added at the end. So it became 0...0110, the decimal representation of this number is 6.
Output: -2, In java negative number, is represented by 2's complement. SO, -1 represent by 2^32-1 which is equivalent to 1....11(Considering 32-bit system). When shifted one time the leading bit is ignored/lost and the rest 31 bits shifted to left and zero is added at the last. So it becomes, 11...10 and its decimal equivalent is -2. So, I think you get enough knowledge about the left shift and how its work.
Output: 8, As a binary representation of 35 in a 32-bit system is 00...00100011, so when we right shift it two times the first 30 leading bits are moved/shifts to the right side and the two low-order bits are lost/ignored and two zeros are added at the leading bits. So, it becomes 00....00001000, the decimal equivalent of this binary representation is 8. Or there is a simple mathematical trick to find out the output of this following code: To generalize this we can say that, x >> y = floor(x/pow(2,y)). Consider the above example, x=35 and y=2 so, 35/2^2 = 8.75 and if we take the floor value then the answer is 8.
Output:
But remember one thing this trick is fine for small values of y if you take the large values of y it gives you incorrect output.
Output: -5, As I explained above the compiler stores the negative value as 2's complement. So, -10 is represented as 2^32-10 and in binary representation considering 32-bit system 11....0110. When we shift/ move one time the first 31 leading bits got shifted in the right side and the low-order bit got lost/ignored. So, it becomes 11...0011 and the decimal representation of this number is -5 (How I know the sign of number? because the leading bit is 1). It is interesting to note that if you shift -1 right, the result always remains -1 since sign extension keeps bringing in more ones in the high-order bits.
Output: 2147483647, Because -2 is represented as 11...10 in a 32-bit system. When we shift the bit by one, the first 31 leading bit is moved/shifts in right and the low-order bit is lost/ignored and the zero is added to the leading bit. So, it becomes 011...1111 (2^31-1) and its decimal equivalent is 2147483647.
A nice kotlin solution, using the latest cross-platform answer mentioned by lakshman sai...
No unnecessary Uri.toString and the Uri.parse though, this answer clean and minimal:
val intentUri = Uri.Builder().apply {
scheme("https")
authority("www.google.com")
appendPath("maps")
appendPath("dir")
appendPath("")
appendQueryParameter("api", "1")
appendQueryParameter("destination", "${yourLocation.latitude},${yourLocation.longitude}")
}.build()
startActivity(Intent(Intent.ACTION_VIEW).apply {
data = intentUri
})
Or maybe even easier
grep -R put **/*bills*
The **
glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.
Do you even need them to be input elements in the first place? You can use Javascript to dynamically create divs or paragraphs or list items or whatever that contain the information you want to present.
But if the interactive element is important and it's a pain in the butt to place those elements outside the <form>
block, it ought to be possible to remove those elements from the form when the page gets submitted.
copy /b file1 + file2 + file3 newfile
Each source file must be added to the copy command with a +
, and the last filename listed will be where the concatenated data is copied to.
You need to allow Allow USB debugging
when the popup shows up when you first connect to the computer!
Try the following (note that there should not be a space between the VAR
, =
, and GREG
).
SET VAR=GREG
ECHO %VAR%
PAUSE
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
In onCreate with activity or onCreateView with fragment
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
}
try {
view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {
e.printStackTrace();
}
Before understanding next
, you need to have a little idea of Request-Response cycle in node though not much in detail.
It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);
let’s have a look at a very simple example.
app.get('/hello', function (req, res, next) {
res.send('USER')
})
Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.
Now let’s take a look at another example.
app.get('/hello', function (req, res, next) {
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.
But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.
app.get('/hello', function (req, res, next) {
if(some condition){
next();
return;
}
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
What’s the next
doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!"
response.
So, next pass the control to the next function in the middleware stack.
What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.
Something like below:-
app.get('/hello', function (req, res, next) {
// Your piece of logic
next();
});
app.get('/hello', function (req, res, next) {
res.send("Hello !!!!");
});
In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();
What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.
With the addition of Python 3, here is an updated code that works:
import numpy as n
import scipy as s
import matplotlib.pylab as p #pylab is part of matplotlib
xa=0.252
xb=1.99
C=n.linspace(xa,xb,100)
print(C)
iter=1000
Y = n.ones(len(C))
for x in range(iter):
Y = Y**2 - C #get rid of early transients
for x in range(iter):
Y = Y**2 - C
p.plot(C,Y, '.', color = 'k', markersize = 2)
p.show()
You have to setState
every second with the seconds remaining (every time the interval is called). Here's an example:
class Example extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { time: {}, seconds: 5 };_x000D_
this.timer = 0;_x000D_
this.startTimer = this.startTimer.bind(this);_x000D_
this.countDown = this.countDown.bind(this);_x000D_
}_x000D_
_x000D_
secondsToTime(secs){_x000D_
let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
let divisor_for_minutes = secs % (60 * 60);_x000D_
let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
let obj = {_x000D_
"h": hours,_x000D_
"m": minutes,_x000D_
"s": seconds_x000D_
};_x000D_
return obj;_x000D_
}_x000D_
_x000D_
componentDidMount() {_x000D_
let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
this.setState({ time: timeLeftVar });_x000D_
}_x000D_
_x000D_
startTimer() {_x000D_
if (this.timer == 0 && this.state.seconds > 0) {_x000D_
this.timer = setInterval(this.countDown, 1000);_x000D_
}_x000D_
}_x000D_
_x000D_
countDown() {_x000D_
// Remove one second, set state so a re-render happens._x000D_
let seconds = this.state.seconds - 1;_x000D_
this.setState({_x000D_
time: this.secondsToTime(seconds),_x000D_
seconds: seconds,_x000D_
});_x000D_
_x000D_
// Check if we're at zero._x000D_
if (seconds == 0) { _x000D_
clearInterval(this.timer);_x000D_
}_x000D_
}_x000D_
_x000D_
render() {_x000D_
return(_x000D_
<div>_x000D_
<button onClick={this.startTimer}>Start</button>_x000D_
m: {this.state.time.m} s: {this.state.time.s}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
Take care to reset target, otherwise all other calls like Response.Redirect
will open in a new tab, which might be not what you want.
<asp:LinkButton OnClientClick="openInNewTab();" .../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
You may do as follows to Populate treeView with parent and child node. And also with display and value member of parent and child nodes:
arrayRoot = taskData.GetRocordForRoot(); // iterate through database table
for (int j = 0; j <arrayRoot.length; j++) {
TreeNode root = new TreeNode(); // Creating new root node
root.Text = "displayString";
root.Tag = "valueString";
treeView1.Nodes.Add(root); //Adding the root node
arrayChild = taskData.GetRocordForChild();// iterate through database table
for (int i = 0; i < arrayChild.length; i++) {
TreeNode child = new TreeNode(); // creating child node
child.Text = "displayString"
child.Tag = "valueString";
root.Nodes.Add(child); // adding child node
}
}
You can do it without having to create a real Hibernate mapping. Try this:
SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team
Dont know whether I should put this as answer or not...
I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..
going through some other question over SO, I had the following solution
I add the following function in Zeeshan's class
public void clearRoute(){
for(Polyline line1 : polylines)
{
line1.remove();
}
polylines.clear();
}
in my map activity, before drawing the path, I called this function.. example usage as per my app is
private Route rt;
rt.clearRoute();
if (src == null) {
Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
}else if (Destination == null) {
Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
}else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
}else{
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
}
you can use rt.clearRoute();
as per your requirements..
Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..
Complete Class Code
see on github
Edit: here is part of code from mainactivity..
case R.id.mkrbtn_set_dest:
Destination = selmarker.getPosition();
destmarker = selmarker;
desShape = createRouteCircle(Destination, false);
if (src == null) {
Toast.makeText(getApplicationContext(),
"Please select your Source first...",
Toast.LENGTH_LONG).show();
} else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(),
"Source and Destinatin can not be the same..",
Toast.LENGTH_LONG).show();
} else {
if (isNetworkAvailable()) {
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
src = null;
Destination = null;
} else {
Toast.makeText(
getApplicationContext(),
"Internet Connection seems to be OFFLINE...!",
Toast.LENGTH_LONG).show();
}
}
break;
Edit 2 as per comments
usage :
//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
For x64 install zlib1g-dev
.
sudo apt-get install zlib1g-dev
I don't need all the x86 libs ;)
Yes IFNULL function will be working to achieve your desired result.
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT IFNULL(SUM(uop.price * uop.qty),0)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT IFNULL(SUM(upr.amount),0)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT IFNULL(SUM(uoli.amount),0)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
I know this is an old post. But many visitors to this page are getting nothing related to the question. Especially for a newbie.
How to upload and store images or file in our website:
For a static website there maybe no problem since the file storage for some share hosting still adequate. The problem comes from a dynamic website when it gets bigger. Bigger in the database can be handled, but bigger in file such as images is becomes a problem. There are two type of images in a website:
Images come from the administrator for dynamic blog. Usually, these images have been optimized before upload.
Images from users in case of users is allowed to upload images such as avatar. Or users can create blog content and put some images from text editor. This kind of images is difficult to predict the size. Users can upload big images just for small content by resize the view size but not resize the image size.
By ignoring item no. 1 above, quick solution for item no. 2 can be temporary solved by the following tips if we don't have image optimizer functionality in our website :
Do not allow users to directly upload from text editor by redirecting them to image gallery. On this page users must upload file in advance before they can embedded in the content. This method is called as a File Manager.
Use a crop image function for users to upload images. This will limit the image size even users upload very big file. The final image is the result of the cropped image. We can define the size in server side and accept only for example 500Kb or lower.
Now, that is only temporary. For final solution, the question is repeated :
What we can do then :
Migrate from share hosting VPS. Not enough? Then more higher by upgrading to Dedicated.
Create your own server for file storage. Googling to do it. This is not as difficult as you think. Some people do it for their website.
The easy way is use the CDN file storage service.
Okay, 1 and 2 is little bit expensive. But no 3 I think is the best solution.
Some CDN services allow you to store as many web files as you want.
Question, "how to upload file to CDN from our website?"
Don't worry, once you register, usually free, you will get guidance how to upload file and get their link from/to your website. You will get an API and more. It's easy.
Some providers give us a free service for 14 days with limited storage and bandwidth. But that will be okay for starting point. The only problem is because 'people never try'.
Hope it will help for newbie.
To acomplish the timezone change in Postgres 9.1 you must:
1.- Search in your "timezones" folder in /usr/share/postgresql/9.1/ for the appropiate file, in my case would be "America.txt", in it, search for the closest location to your zone and copy the first letters in the left column.
For example: if you are in "New York" or "Panama" it would be "EST":
# - EST: Eastern Standard Time (Australia)
EST -18000 # Eastern Standard Time (America)
# (America/New_York)
# (America/Panama)
2.- Uncomment the "timezone" line in your postgresql.conf
file and put your timezone as shown:
#intervalstyle = 'postgres'
#timezone = '(defaults to server environment setting)'
timezone = 'EST'
#timezone_abbreviations = 'EST' # Select the set of available time zone
# abbreviations. Currently, there are
# Default
# Australia
3.- Restart Postgres
declarative program is just a data for its some more-or-less "universal" imperative implementation/vm.
pluses: specifying just a data, in some hardcoded (and checked) format, is simpler and less error-prone than specifying variant of some imperative algorithm directly. some complex specifications just cant be written directly, only in some DSL form. best and freq used in DSLs data structures is sets and tables. because you not have dependencies between elements/rows. and when you havent dependencies you have freedom to modify and ease of support. (compare for example modules with classes - with modules you happy and with classes you have fragile base class problem) all goods of declarativeness and DSL follows immediately from benefits of that data structures (tables and sets). another plus - you can change implementation of declarative language vm, if DSL is more-or-less abstract (well designed). make parallel implementation, for example. or port it to other os etc. all good specifed modular isolating interfaces or protocols gives you such freedom and easyness of support.
minuses: you guess right. generic (and parameterized by DSL) imperative algorithm/vm implementation may be slower and/or memory hungry than specific one. in some cases. if that cases is rare - just forget about it, let it be slow. if it's frequient - you always can extend your DSL/vm for that case. somewhere slowing down all other cases, sure...
P.S. Frameworks is half-way between DSL and imperative. and as all halfway solutions ... they combines deficiences, not benefits. they not so safe AND not so fast :) look at jack-of-all-trades haskell - it's halfway between strong simple ML and flexible metaprog Prolog and... what a monster it is. you can look at Prolog as a Haskell with boolean-only functions/predicates. and how simple its flexibility is against Haskell...
Compile it as x64 with VS2005:
%llu works well.
<style name="Theme.AppCompat.Light.NoActionBar" parent="@style/Theme.AppCompat">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
Using the above xml in style.xml, you will be able to hide the title as well as action bar.
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)
Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.
In reply to gerardnll's answer the Less code to extend Bootstrap 3.3.x carousel by fade effect:
//
// Carousel Fade effect
// --------------------------------------------------
// inspired from http://codepen.io/Rowno/pen/Afykb
.carousel-fade {
.carousel-inner {
.item {
.opacity(0);
.transition-property(opacity);
//.transition-duration(.8s);
}
.active {
.opacity(1);
&.left,
&.right {
left: 0;
.opacity(0);
z-index: 1;
}
}
.next.left,
.prev.right {
.opacity(1);
}
}
.carousel-control {
z-index: 2;
}
}
// WHAT IS NEW IN 3.3:
// "Added transforms to improve carousel performance in modern browsers."
// now override the 3.3 new styles for modern browsers & apply opacity
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-fade {
.carousel-inner {
> .item {
&.next,
&.prev,
&.active.right,
&.active.left {
.opacity(0);
.translate3d(0; 0; 0);
}
&.next.left,
&.prev.right,
&.active {
.opacity(1);
.translate3d(0; 0; 0);
}
}
}
}
}
The only thing is the transition duration which is not working as expected when longer than .8s (around). Maybe someone has a solution to solve this strange behaviour.
Note: The LESS code has .transition-duration(.8s);
commented, so the default carousel transition duration is used. You can play with the value and see the effect. Longer duration (> 0.8) renders the fade effect less smooth.
I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:
PowerShell says "execution of scripts is disabled on this system."
What worked well for me was to use this solution:
powershell -ExecutionPolicy Bypass -File script.ps1
You can paste that into a .bat file and double-click on it.
To get the version of Redis server
redis-server -v
To get the version of Redis client
redis-cli -v
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
David Wolever's solution is good, but
If you want to have signed angles you have to determine if a given pair is right or left handed (see wiki for further info).
My solution for this is:
def unit_vector(vector):
""" Returns the unit vector of the vector"""
return vector / np.linalg.norm(vector)
def angle(vector1, vector2):
""" Returns the angle in radians between given vectors"""
v1_u = unit_vector(vector1)
v2_u = unit_vector(vector2)
minor = np.linalg.det(
np.stack((v1_u[-2:], v2_u[-2:]))
)
if minor == 0:
raise NotImplementedError('Too odd vectors =(')
return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
It's not perfect because of this NotImplementedError
but for my case it works well. This behaviour could be fixed (cause handness is determined for any given pair) but it takes more code that I want and have to write.
Thx for the above answer here is Swift 4.2
extension String {
var htmlToAttributedString: NSAttributedString? {
guard
let data = self.data(using: .utf8)
else { return nil }
do {
return try NSAttributedString(data: data, options: [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
You can use pragma related commands in sqlite like below
pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")
If you require column names like id|foo|bar|age|street|address
, basically your answer is in below query.
select group_concat(name,'|') from pragma_table_info("table_name")
SELECT <column_list>
FROM TABLEA a
LEFTJOIN TABLEB b
ON a.Key = b.Key
WHERE b.Key IS NULL;
https://www.cloudways.com/blog/how-to-join-two-tables-mysql/
Just do Ctrl + Enter inside the text box
Here is the Best and shortest solution that works for me as of may, 2018 for Laravel 5.5
just cut your .htaccess
file from the /public directory to the root directory and replace it content with the following code:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
</IfModule>
Just save the .htaccess
file and that is all.
Rename your server.php
file to index.php
. that is all enjoy!
Use:
if(comboBox.SelectedIndex > -1) //somthing was selected
To get the selected item you do:
Item m = comboBox.Items[comboBox.SelectedIndex];
As Matthew correctly states, to get the selected item you could also do
Item m = comboBox.SelectedItem;
Note that this most often occurs when the content has been "double encoded", meaning the encoding algorithm has accidentally been called twice.
The first call would encode the "text2" value:
FROM: Heute startet unsere Rundreise "Example text". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
TO: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
A second encoding then converts it again, escaping the already escaped characters:
FROM: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
TO: Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
So, if you are responsible for the implementation of the server here, check to make sure there aren't two steps trying to encode the same content.
I have an open source library that does this very well. It's a four gesture library that comes with an out-of-the-box pan zoom setting. You can find it here: https://bitbucket.org/warwick/hacergestov3 Or you can download the demo app here: https://play.google.com/store/apps/details?id=com.WarwickWestonWright.HacerGestoV3Demo This is a pure canvas library so it can be used in pretty any scenario. Hope this helps.
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
For me PHP is the easiest way to do it:
<?php
echo "Here are our files";
$path = ".";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != ".." && $file != "index.php" && $file != ".htaccess" && $file != "error_log" && $file != "cgi-bin") {
echo "<a href='$path/$file'>$file</a><br /><br />";
$i++;
}
}
closedir($dh);
?>
Place this in your directory and set where you want it to search on the $path. The first if statement will hide your php file and .htaccess and the error log. It will then display the output with a link. This is very simple code and easy to edit.
My work uses this tool, and it seems quite good: http://www.dallaway.com/sloppy/
Best of luck.
Expanding on Nathans post. The following will do the job lot in one batch file.
@echo off
if %1.==Sub. goto %2
for %%f in (*.in) do call %0 Sub action %%~nf
goto end
:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt
:end
SHOW CREATE TABLE bar;
you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.
This will allow you to copy the indexes and also manually tweak the table creation.
You can also run the query within a program.
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
In testing IE7/8/9 I was getting an ActiveX
warning trying to use this code snippet:
filter:progid:DXImageTransform.Microsoft.gradient
After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.
As stated in other answers, you can use WindowStyle="None"
to remove the Title Bar altogether.
And, as stated in the comments to those other answers, this prevents the window from being draggable so it is hard to move it from its initial position.
However, you can overcome this by adding a single line of code to the Constructor in the Window's Code Behind file:
MouseDown += delegate { DragMove(); };
Or, if you prefer Lambda Syntax:
MouseDown += (sender, args) => DragMove();
This makes the entire Window draggable. Any interactive controls present in the Window, such as Buttons, will still work as normal and won't act as drag-handles for the Window.
Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = EmailControllerBootApplication.class
)
public class SendEmailTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void testSend() throws Exception{
String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
+ "\"CDM - Spring Boot email service with attachment\","
+ "\"body\": \"Email body will contain test results, with screenshot\"}";
Resource fileResource = new ClassPathResource(
"screen-shots/HomePage-attachment.png");
assertNotNull(fileResource);
MockMultipartFile firstFile = new MockMultipartFile(
"attachments",fileResource.getFilename(),
MediaType.MULTIPART_FORM_DATA_VALUE,
fileResource.getInputStream());
assertNotNull(firstFile);
MockMvc mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext).build();
mockMvc.perform(MockMvcRequestBuilders
.multipart("/api/v1/email/send")
.file(firstFile)
.param("data", jsonStr))
.andExpect(status().is(200));
}
}
the shortest code is :
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL is PATH of image .
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
## b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3
df <- data.frame(a = c(0, 0, 0), df)
df
## a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3
Unlike another programming languages, any variable declared outside any function automatically becomes global,
<script>
//declare global variable
var __foo = '123';
function __test(){
//__foo is global and visible here
alert(__foo);
}
//so, it will alert '123'
__test();
</script>
You problem is that you declare variable inside ready()
function, which means that it becomes visible (in scope) ONLY inside ready()
function, but not outside,
Solution:
So just make it global, i.e declare this one outside $(document).ready(function(){});
I created a code to jump to the desired back stack index, it worked fine to my purpose.
ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1
I created a method called onBackPressed in Fragment3 that jumps to Fragment1
Fragment3:
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super
FragmentActivity:
@Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
if (f instanceof Fragment3)
{
((Fragment3)f).onBackPressed();
} else {
super.onBackPressed();
}
}
This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).
Here is my solution, give them different names:
<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>
And you must specify the names of buttons as arguments in the action like below:
public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
if (buttonSave!= null)
{
//save is pressed
}
if (buttonProcess!= null)
{
//Process is pressed
}
if (buttonCancel!= null)
{
//Cancel is pressed
}
}
when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.
Update
This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.
The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
or
http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html
Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.
Change the image source using jQuery click()
element:
<img class="letstalk btn" src="images/chatbuble.png" />
code:
$(".letstalk").click(function(){
var newsrc;
if($(this).attr("src")=="/images/chatbuble.png")
{
newsrc="/images/closechat.png";
$(this).attr("src", newsrc);
}
else
{
newsrc="/images/chatbuble.png";
$(this).attr("src", newsrc);
}
});
A vector is a container class while an array is an allocated memory.
XML version for @Asher Aslan cool effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
android:angle="180"
android:startColor="#00000000"
android:centerColor="#FFFF0000"
android:endColor="#00000000"/>
</shape>
Name for that shape as: list_driver.xml under drawable folder
<ListView
android:id="@+id/category_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@drawable/list_driver"
android:dividerHeight="5sp" />
Here is the full c# code to convert xml to json
public static class JSon
{
public static string XmlToJSON(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
StringBuilder sbJSON = new StringBuilder();
sbJSON.Append("{ ");
XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
sbJSON.Append("}");
return sbJSON.ToString();
}
// XmlToJSONnode: Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
sbJSON.Append("{");
// Build a sorted list of key-value pairs
// where key is case-sensitive nodeName
// value is an ArrayList of string or XmlElement
// so that we know whether the nodeName is an array or not.
SortedList<string, object> childNodeNames = new SortedList<string, object>();
// Add in all node attributes
if (node.Attributes != null)
foreach (XmlAttribute attr in node.Attributes)
StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
// Add in all nodes
foreach (XmlNode cnode in node.ChildNodes)
{
if (cnode is XmlText)
StoreChildNode(childNodeNames, "value", cnode.InnerText);
else if (cnode is XmlElement)
StoreChildNode(childNodeNames, cnode.Name, cnode);
}
// Now output all stored info
foreach (string childname in childNodeNames.Keys)
{
List<object> alChild = (List<object>)childNodeNames[childname];
if (alChild.Count == 1)
OutputNode(childname, alChild[0], sbJSON, true);
else
{
sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
foreach (object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" }");
}
// StoreChildNode: Store data associated with each nodeName
// so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
// Pre-process contraction of XmlElement-s
if (nodeValue is XmlElement)
{
// Convert <aa></aa> into "aa":null
// <aa>xx</aa> into "aa":"xx"
XmlNode cnode = (XmlNode)nodeValue;
if (cnode.Attributes.Count == 0)
{
XmlNodeList children = cnode.ChildNodes;
if (children.Count == 0)
nodeValue = null;
else if (children.Count == 1 && (children[0] is XmlText))
nodeValue = ((XmlText)(children[0])).InnerText;
}
}
// Add nodeValue to ArrayList associated with each nodeName
// If nodeName doesn't exist then add it
List<object> ValuesAL;
if (childNodeNames.ContainsKey(nodeName))
{
ValuesAL = (List<object>)childNodeNames[nodeName];
}
else
{
ValuesAL = new List<object>();
childNodeNames[nodeName] = ValuesAL;
}
ValuesAL.Add(nodeValue);
}
private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
if (alChild == null)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
sbJSON.Append("null");
}
else if (alChild is string)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
string sChild = (string)alChild;
sChild = sChild.Trim();
sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
}
else
XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
sbJSON.Append(", ");
}
// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
StringBuilder sbOut = new StringBuilder(sIn.Length);
foreach (char ch in sIn)
{
if (Char.IsControl(ch) || ch == '\'')
{
int ich = (int)ch;
sbOut.Append(@"\u" + ich.ToString("x4"));
continue;
}
else if (ch == '\"' || ch == '\\' || ch == '/')
{
sbOut.Append('\\');
}
sbOut.Append(ch);
}
return sbOut.ToString();
}
}
To convert a given XML string to JSON, simply call XmlToJSON() function as below.
string xml = "<menu id=\"file\" value=\"File\"> " +
"<popup>" +
"<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
"<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
"<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
"</popup>" +
"</menu>";
string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
I leave here my own solution, which is a workaround because seems as the problem is the FragmentPagerAdapter
doesn't clean the previous fragments
, you can be added to the ViewPager
, in the Fragment Manager. So, I create a method to execute before add the FragmentPagerAdapter
:
(In my case I never add more than 3 fragments, but you can use for example getFragmentManager().getBackStackEntryCount()
and check all the fragments
.
/**
* this method is solving a bug in FragmentPagerAdapter which don't delete in the fragment manager any previous fragments in a ViewPager.
*
* @param containerId
*/
public void cleanBackStack(long containerId) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
for (int i = 0; i < 3; ++i) {
String tag = "android:switcher:" + containerId + ":" + i;
Fragment f = getFragmentManager().findFragmentByTag(tag);
if (f != null) {
transaction.remove(f);
}
}
transaction.commit();
}
I know it is a workaround because it will stop work if the way the framework is creating the tags change.
(currently "android:switcher:" + containerId + ":" + i
)
Then the way to use it is after getting the container:
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
cleanBackStack(viewPager.getId());
Easy way:
str = "[12,23,987,43"
removed = str[1..str.length]
Awesome way:
class String
def reverse_chop()
self[1..self.length]
end
end
"[12,23,987,43".reverse_chop()
(Note: prefer the easy way :) )
The following worked best for me (this code lies in UIView extension, so self denotes some UIView to which we must add a shadow and round corner)
- (void)addShadowViewWithCornerRadius:(CGFloat)radius {
UIView *container = self.superview;
if (!container) {
return;
}
UIView *shadowView = [[UIView alloc] init];
shadowView.translatesAutoresizingMaskIntoConstraints = NO;
shadowView.backgroundColor = [UIColor lightGrayColor];
shadowView.layer.cornerRadius = radius;
shadowView.layer.masksToBounds = YES;
[container addSubview:shadowView];
[container bringSubviewToFront:shadowView];
[container addConstraint:[NSLayoutConstraint constraintWithItem:shadowView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0.0]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:shadowView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:2.0]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:shadowView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0.0]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:shadowView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:2.0]];
[container sendSubviewToBack:shadowView];
}
The main difference between this and other code samples is that this adds the shadow view as a sibling view (as against adding the current view as subview of shadow view), thereby eliminating the need to modify the existing view hierarchy in any way.
I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.
But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.
The sleep man page says it is declared in <unistd.h>
.
Synopsis:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
You could create a Scheduler Task that runs automatically on the start, even when the user is not logged in:
schtasks /create /tn "FileMonitor" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file C:\Doc\Files\FileMonitor.ps1"
Run this command once from a PowerShell as Admin and it will create a schedule task for you. You can list the task like this:
schtasks /Query /TN "FileMonitor" /V /FO List
or delete it
schtasks /Delete /TN "FileMonitor"
>>> log4j = sc._jvm.org.apache.log4j
>>> log4j.LogManager.getRootLogger().setLevel(log4j.Level.ERROR)
Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.
Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.
Javascript is the source, the actual scripts that browser responds to.
You can try this for get current month first day;
DateTime.Now.AddDays(-(DateTime.Now.Day-1))
and assign it a value.
Like this:
dateEndEdit.EditValue = DateTime.Now;
dateStartEdit.EditValue = DateTime.Now.AddDays(-(DateTime.Now.Day-1));
I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.
Because this is the first result on Google. I want to share with you a great Talk by Dave Smith on Youtube: Mastering the Android Touch System and the slides are available here. It gave me a good deep understanding about the Android Touch System:
How the Activity handles touch:
Activity.dispatchTouchEvent()
- Always first to be called
- Sends event to root view attached to Window
onTouchEvent()
- Called if no views consume the event
- Always last to be called
How the View handles touch:
View.dispatchTouchEvent()
- Sends event to listener first, if exists
View.OnTouchListener.onTouch()
- If not consumed, processes the touch itself
View.onTouchEvent()
How a ViewGroup handles touch:
ViewGroup.dispatchTouchEvent()
onInterceptTouchEvent()
- Check if it should supersede children
- Passes
ACTION_CANCEL
to active child- If it returns true once, the
ViewGroup
consumes all subsequent events- For each child view (in reverse order they were added)
- If touch is relevant (inside view),
child.dispatchTouchEvent()
- If it is not handled by a previous, dispatch to next view
- If no children handles the event, the listener gets a chance
OnTouchListener.onTouch()
- If there is no listener, or its not handled
onTouchEvent()
- Intercepted events jump over the child step
He also provides example code of custom touch on github.com/devunwired/.
Answer:
Basically the dispatchTouchEvent()
is called on every View
layer to determine if a View
is interested in an ongoing gesture. In a ViewGroup
the ViewGroup
has the ability to steal the touch events in his dispatchTouchEvent()
-method, before it would call dispatchTouchEvent()
on the children. The ViewGroup
would only stop the dispatching if the ViewGroup
onInterceptTouchEvent()
-method returns true. The difference is that dispatchTouchEvent()
is dispatching MotionEvents
and onInterceptTouchEvent
tells if it should intercept (not dispatching the MotionEvent
to children) or not (dispatching to children).
You could imagine the code of a ViewGroup doing more-or-less this (very simplified):
public boolean dispatchTouchEvent(MotionEvent ev) {
if(!onInterceptTouchEvent()){
for(View child : children){
if(child.dispatchTouchEvent(ev))
return true;
}
}
return super.dispatchTouchEvent(ev);
}
With jQuery, the actual DOM element is at index zero, this should work
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
I had a similar problem using Eclipse C++ 2019-03 for a mixed C and C++ project that used std::optional
and std::swap
. What worked for me was this.
In the project
Properties->C/C++ Build->Settings->Tool Settings->Cross G++ Compiler
, remove -std=gnu++17
from Miscellaneous
and put it in Dialect->Other Dialect Flags
instead.
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.
You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.
Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.
You need to tell Angular that your directive uses a scope variable:
You need to bind some property of the scope to your directive:
return {
restrict: 'E',
scope: {
whatever: '='
},
...
}
and then $watch
it:
$scope.$watch('whatever', function(value) {
// do something with the new value
});
Refer to the Angular documentation on directives for more information.
From RVM’s documentation:
Just add this line to your
~/.gemrc
or/etc/gemrc
:
gem: --no-document
Note: The original answer was:
install: --no-rdoc --no-ri
update: --no-rdoc --no-ri
This is no longer valid; the RVM docs have since been updated, thus the current answer to only include the gem
directive is the correct one.
You can use Google Cloud Messaging or GCM, it's free and easy to use. Also you can use third party push servers like PushWoosh which gives you more flexibility
Performance issue is the first reason. When you see the kind of hyper optimized C++ code that are in the Quake engines ( http://www.codemaestro.com/reviews/9 ), you know they're not gonna waste their time with a virtual machine.
Sure there may be some .NET games (which ones ? I'm interested. Are there some really CPU/GPU-intensive ones ?), but I guess it's more because lot of people are experts in MS technologies and followed Microsoft when they launched their new technology.
Oh and cross-platform just isn't in the mind of video games companies. Linux is just around 1% of market, Mac OS a few % more. They definitely think it's not worth dumping Windows-only technologies and librairies such as DirectX.
It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.
Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/
Edit: I fixed my problem, which was slightly different, after talking to microsoft support.
My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https
<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
This error can also happen when trying to clone an invalid HTTP URL. For example, this is the error I got when trying to clone a GitHub URL that was a few characters off:
$ git clone -v http://github.com/username/repo-name.git
Cloning into 'repo-name'...
Username for 'https://github.com':
Password for 'https://github.com':
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/username/repo-name.git/'
It actually happened inside Emacs, though, so the error in Emacs looked like this:
fatal: could not read Username for ’https://github.com’: No such device or address
So instead of a helpful error saying that there was no such repo at that URL, it gave me that, sending me on a wild goose chase until I finally realized that the URL was incorrect.
This is with git version 2.7.4.
I'm posting this here because it happened to me a month ago and again just now, sending me on the same wild goose chase again. >:(
I'm just adding this to be precise:
All other answers refer to modules. The original question explicitely mentioned __all__
in __init__.py
files, so this is about python packages.
Generally, __all__
only comes into play when the from xxx import *
variant of the import
statement is used. This applies to packages as well as to modules.
The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.
In short, __all__
on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__
specifies all modules that shall be loaded and imported into the current namespace when us use from package import *
.
The big difference is, that when you omit the declaration of __all__
in a package's __init__.py
, the statement from package import *
will not import anything at all (with exceptions explained in the documentation, see link above).
On the other hand, if you omit __all__
in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.
My Problem was solved
The problem occurs when you have the wrong/different team on MyProject and MyProjectTest.
Reconnecting your phone prior to rebuilding may also assist with fixing this issue.
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
Input elements have a property called disabled
. When the form submits, just run some code like this:
var myInput = document.getElementById('myInput');
myInput.disabled = true;
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
I've had this problem before, and the solution is simply to call window.print() in IE, as opposed to calling print from the window instance:
function printPage(htmlPage)
{
var w = window.open("about:blank");
w.document.write(htmlPage);
if (navigator.appName == 'Microsoft Internet Explorer') window.print();
else w.print();
}
Return a FileResult
or FileStreamResult
from your action, depending on whether the file exists or you create it on the fly.
public ActionResult GetPdf(string filename)
{
return File(filename, "application/pdf", Server.UrlEncode(filename));
}
I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:
private boolean isCallable(Intent intent) {
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
In use when I would usually just start the activity:
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
// call the intent as you intended.
} else {
// make alternative arrangements.
}
obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.
I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.
I was looking for the same funcionality and found this answer. However, I wanted to give you guys a quick update. It's CSS3's vmin unit.
p, li
{
font-size: 1.2vmin;
}
vmin means 'whichever is smaller between the 1% of the ViewPort's height and the 1% of the ViewPort's width'.
I know it's over a year old, but calling requestFeature()
never solved my problem. In fact I don't call it at all.
It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.
AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog()
to update that view.
Another alternative is to leverage AsyncTask for dialogs.
A final solution that I used is below:
public class CustomDialog extends AlertDialog {
private View content;
public CustomDialog(Context context) {
super(context);
LayoutInflater li = LayoutInflater.from(context);
content = li.inflate(R.layout.custom_view, null);
setUpAdditionalStuff(); // do more view cleanup
setView(content);
}
private void setUpAdditionalStuff() {
// ...
}
// Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method
public void prepare() {
setTitle(R.string.custom_title);
setIcon( getIcon() );
// ...
}
}
* Some Additional notes:
My problem was in web.xml
file. In one <servlet-mapping>
there was an error inside <url-pattern>
: I forgot to add /
before url.
To get a third order polynomial in x (x^3), you can do
lm(y ~ x + I(x^2) + I(x^3))
or
lm(y ~ poly(x, 3, raw=TRUE))
You could fit a 10th order polynomial and get a near-perfect fit, but should you?
EDIT: poly(x, 3) is probably a better choice (see @hadley below).
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.
So try wrapping the content in a div, and give the div a min-height
jsFiddle here
<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
<tbody>
<tr>
<td>
<div style="min-height: 100px; background-color: #ccc">
Hello World !
</div>
</td>
<td>
<div style="min-height: 100px; background-color: #f00">
Good Morning !
</div>
</td>
</tr>
</tbody>
</table>
duplicates=false;
for (j=0;j<zipcodeList.length;j++)
for (k=j+1;k<zipcodeList.length;k++)
if (k!=j && zipcodeList[k] == zipcodeList[j])
duplicates=true;
Edited to switch .equals()
back to ==
since I read somewhere you're using int
, which wasn't clear in the initial question. Also to set k=j+1
, to halve execution time, but it's still O(n2).
Here's a hash based approach. You gotta pay for the autoboxing, but it's O(n) instead of O(n2). An enterprising soul would go find a primitive int-based hash set (Apache or Google Collections has such a thing, methinks.)
boolean duplicates(final int[] zipcodelist)
{
Set<Integer> lump = new HashSet<Integer>();
for (int i : zipcodelist)
{
if (lump.contains(i)) return true;
lump.add(i);
}
return false;
}
See HuyLe's answer for a more or less O(n) solution, which I think needs a couple of add'l steps:
static boolean duplicates(final int[] zipcodelist)
{
final int MAXZIP = 99999;
boolean[] bitmap = new boolean[MAXZIP+1];
java.util.Arrays.fill(bitmap, false);
for (int item : zipcodeList)
if (!bitmap[item]) bitmap[item] = true;
else return true;
}
return false;
}
static boolean duplicates(final int[] zipcodelist)
{
final int MAXZIP = 99999;
boolean[] bitmap = new boolean[MAXZIP+1]; // Java guarantees init to false
for (int item : zipcodeList)
if (!(bitmap[item] ^= true)) return true;
return false;
}
Well, so I ran a little benchmark, which is iffy all over the place, but here's the code:
import java.util.BitSet;
class Yuk
{
static boolean duplicatesZero(final int[] zipcodelist)
{
boolean duplicates=false;
for (int j=0;j<zipcodelist.length;j++)
for (int k=j+1;k<zipcodelist.length;k++)
if (k!=j && zipcodelist[k] == zipcodelist[j])
duplicates=true;
return duplicates;
}
static boolean duplicatesOne(final int[] zipcodelist)
{
final int MAXZIP = 99999;
boolean[] bitmap = new boolean[MAXZIP + 1];
java.util.Arrays.fill(bitmap, false);
for (int item : zipcodelist) {
if (!(bitmap[item] ^= true))
return true;
}
return false;
}
static boolean duplicatesTwo(final int[] zipcodelist)
{
final int MAXZIP = 99999;
BitSet b = new BitSet(MAXZIP + 1);
b.set(0, MAXZIP, false);
for (int item : zipcodelist) {
if (!b.get(item)) {
b.set(item, true);
} else
return true;
}
return false;
}
enum ApproachT { NSQUARED, HASHSET, BITSET};
/**
* @param args
*/
public static void main(String[] args)
{
ApproachT approach = ApproachT.BITSET;
final int REPS = 100;
final int MAXZIP = 99999;
int[] sizes = new int[] { 10, 1000, 10000, 100000, 1000000 };
long[][] times = new long[sizes.length][REPS];
boolean tossme = false;
for (int sizei = 0; sizei < sizes.length; sizei++) {
System.err.println("Trial for zipcodelist size= "+sizes[sizei]);
for (int rep = 0; rep < REPS; rep++) {
int[] zipcodelist = new int[sizes[sizei]];
for (int i = 0; i < zipcodelist.length; i++) {
zipcodelist[i] = (int) (Math.random() * (MAXZIP + 1));
}
long begin = System.currentTimeMillis();
switch (approach) {
case NSQUARED :
tossme ^= (duplicatesZero(zipcodelist));
break;
case HASHSET :
tossme ^= (duplicatesOne(zipcodelist));
break;
case BITSET :
tossme ^= (duplicatesTwo(zipcodelist));
break;
}
long end = System.currentTimeMillis();
times[sizei][rep] = end - begin;
}
long avg = 0;
for (int rep = 0; rep < REPS; rep++) {
avg += times[sizei][rep];
}
System.err.println("Size=" + sizes[sizei] + ", avg time = "
+ avg / (double)REPS + "ms");
}
}
}
With NSQUARED:
Trial for size= 10
Size=10, avg time = 0.0ms
Trial for size= 1000
Size=1000, avg time = 0.0ms
Trial for size= 10000
Size=10000, avg time = 100.0ms
Trial for size= 100000
Size=100000, avg time = 9923.3ms
With HashSet
Trial for zipcodelist size= 10
Size=10, avg time = 0.16ms
Trial for zipcodelist size= 1000
Size=1000, avg time = 0.15ms
Trial for zipcodelist size= 10000
Size=10000, avg time = 0.0ms
Trial for zipcodelist size= 100000
Size=100000, avg time = 0.16ms
Trial for zipcodelist size= 1000000
Size=1000000, avg time = 0.0ms
With BitSet
Trial for zipcodelist size= 10
Size=10, avg time = 0.0ms
Trial for zipcodelist size= 1000
Size=1000, avg time = 0.0ms
Trial for zipcodelist size= 10000
Size=10000, avg time = 0.0ms
Trial for zipcodelist size= 100000
Size=100000, avg time = 0.0ms
Trial for zipcodelist size= 1000000
Size=1000000, avg time = 0.0ms
But only by a hair... .15ms is within the error for currentTimeMillis()
, and there are some gaping holes in my benchmark. Note that for any list longer than 100000, you can simply return true
because there will be a duplicate. In fact, if the list is anything like random, you can return true WHP for a much shorter list. What's the moral? In the limit, the most efficient implementation is:
return true;
And you won't be wrong very often.
In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
Don't just say "memory pool of strings is reused in the literal form, case closed". What compilers do under the hood is not the point here. The question is reasonable, specially given the number of up-votes it received.
It's about the symmetry, without it APIs are harder to use for humans. Early Java SDKs notoriously ignored the rule and now it's kind of too late. Here are a few examples on top of my head, feel free to chip in your "favorite" example:
The instantiateViewControllerWithIdentifier
is the Storyboard ID
.
NextViewController *NVC = [self.storyboard instantiateViewControllerWithIdentifier:@"NextViewController"];
[self presentViewController:NVC animated:YES completion:nil];
This can be done in in 3 lines of code:
// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow]
rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
Use maven and the plugin jaxws-maven-plugin. this will generate a web service client. Make sure you are setting the xadditionalHeaders to true. This will generate methods with header inputs.
So if i understood well, i would say that <pluginManagement>
just like <dependencyManagement>
are both used to share only the configuration between a parent and it's sub-modules.
For that we define the dependencie's and plugin's common configurations in the parent project and then we only have to declare the dependency/plugin in the sub-modules to use it, without having to define a configuration for it (i.e version or execution, goals, etc). Though this does not prevent us from overriding the configuration in the submodule.
In contrast <dependencies>
and <plugins>
are inherited along with their configurations and should not be redeclared in the sub-modules, otherwise a conflict would occur.
is that right ?
Okay, I assume you using php7.2 (or higher) on Ubuntu 16 or higher
if none of this worked, you must know nginx-fastCGI uses different pid and .sock for different sites hosted on the same server.
To troubleshoot 'No input file specified' problem, you must tell the nginx yoursite.conf file which one of the sock file to use.
Uncomment the default fastcgi_pass unix:/var/run/php7.2-fpm.sock
Make sure you have the following directives in place on the conf file,
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri /index.php =404;
#fastcgi_pass unix:/var/run/php7.2-fpm.sock;
fastcgi_pass unix:/var/php-nginx/158521651519246.sock/socket;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
ls -la /var/php-nginx/
(if you have recently added the file, it should be the last one on the list)3.copy the filename of the .sock file (usually a 15 digit number) and paste it to your location ~ \.php
directive
fastcgi_pass unix:/var/php-nginx/{15digitNumber}.sock/socket;
and restart nginx. Let me know if it worked.
<Image Source="MyRessourceDir\images\addButton.png"/>
Try to change directory to where the .box
is saved
Run vagrant box add my-box downloaded.box
, this may work as it avoids absolute path (on Windows?).
If you're using the resource routes, then in the HTML body of the form, you can use method_field helper like this:
<form>
{{ csrf_field() }}
{{ method_field('PUT') }}
<!-- ... -->
</form>
It will create hidden form input with method type, that is correctly interpereted by Laravel 5.5+.
Since Laravel 5.6 you can use following Blade directives in the templates:
<form>
@method('put')
@csrf
<!-- ... -->
</form>
Hope this might help someone in the future.
when you set the density to 96, doesn't it look good?
when i tried it i saw that saving as jpg resulted with better quality, but larger file size
With macOS 10.15 and Homebrew 2.1.6 I was getting this error with Python 3.7. I just needed to run:
python3 -m ensurepip
Now python3 -m pip
works for me.
You can use the parent selector reference &
, it will be replaced by the parent selector after compilation:
For your example:
.container {
background:red;
&.desc{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
.container.desc {
background: blue;
}
The &
will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &
.
This notation is most often used to write pseudo-elements and -classes:
.element{
&:hover{ ... }
&:nth-child(1){ ... }
}
However, you can place the &
at virtually any position you like*, so the following is possible too:
.container {
background:red;
#id &{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
#id .container {
background: blue;
}
However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.
*: No other characters than whitespaces are allowed in front of the &
. So you cannot do a direct concatenation of selector
+&
- #id&
would throw an error.
the reason for this error may be originate from forwarding of version dependent localdb in visual sudio 2013 to the version independent localDB in VS 2015 onwards, so simply change your web.config file connectionStrings from (localDb)\v11.0 to (localDB)\MSSQLLocalDB and it will certainly work. and this is a good explaination for that Version independent local DB in Visual Studio 2015
Decode it.
>>> b'a string'.decode('ascii')
'a string'
To get bytes from string, encode it.
>>> 'a string'.encode('ascii')
b'a string'
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<a href="">About</a>
</div>
<div class="col-md-4">
<img src="image.png">
</div>
<div class="col-md-4">
<a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
</div>
</div>
You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.
A simpler way would be
<div class="container">
<div class="row">
<div class="col-md-4">
<a href="">About</a>
</div>
<div class="col-md-4">
<img src="image.png">
</div>
<div class="col-md-4">
<a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
Try using phoneformat.js (http://www.phoneformat.com/), you can not only format phone number based on user locales (en-US, ja-JP, fr-FR, de-DE etc) but it also validates the phone number. Its very robust library based on googles libphonenumber project.
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
Content-Length = "Content-Length" ":" 1*DIGIT
An example is
Content-Length: 3495
Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.
Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.
Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.
My interpretation is that this means the length "on the wire", i.e. the length of the *encoded" content
No, don't do it that way.
From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.
Tadaa!! :)
Identify all the fields that could be related to your search and then use a query like:
SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
OR field2 LIKE '%Mary%'
OR field3 LIKE '%Mary%'
OR field4 LIKE '%Mary%'
....
(do that for each field you want to check)
Using LIKE '%Mary%'
instead of = 'Mary'
will look for the fields that contains someCaracters + 'Mary' + someCaracters.
This is easy and very short:
.block {_x000D_
display: table-row;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
.tile {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
}
_x000D_
<div class="body">_x000D_
<span class="tile">_x000D_
Hello middle world! :)_x000D_
</span>_x000D_
</div>
_x000D_
If you need to parse ASN.1 objects in script, there's a library for that: https://github.com/lapo-luchini/asn1js
For doing the math, I found jsbn convenient: http://www-cs-students.stanford.edu/~tjw/jsbn/
Walking the ASN.1 structure and extracting the exp/mod/subject/etc. is up to you -- I never got that far!
If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.
The HttpClient class documentation includes this example:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException
, and the fix is not found anywhere else so I thought I'd add an answer here.
java.net.UnknownHostException: google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
...
No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.
Not calling trim()
for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":")
by semicolons for the HOST
header. This left whitespace, and causes the UnknownHostException
as a host with whitespace is not a valid host. Doing a host = host.trim()
on the String host
solved the ambiguous issue.
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
The last p
after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
I am able to read both the IMEI's from OnePlus 2 Phone
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
Log.i(TAG, "Default device ID " + manager.getDeviceId());
Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
}
Try this:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
A related info, to the question...
In django, use timezone.now()
for the datetime field, as django supports timezone, it just returns datetime based on the USE TZ
settings, or simply timezone 'aware' datetime objects
For a reference, I've got TIME_ZONE = 'Asia/Kolkata'
and USE_TZ = True
,
from django.utils import timezone
import datetime
print(timezone.now()) # The UTC time
print(timezone.localtime()) # timezone specified time,
print(datetime.datetime.now()) # default local time
# output
2020-12-11 09:13:32.430605+00:00
2020-12-11 14:43:32.430605+05:30 # IST is UTC+5:30
2020-12-11 14:43:32.510659
refer timezone settings and Internationalization and localization in django docs for more details.
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings.
Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: https://stackoverflow.com/a/1151993/61569
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
just select '0' as the value for the desired column
Since Spring 5 you just need to implement the interface WebMvcConfigurer
:
public class MvcConfig implements WebMvcConfigurer {
This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter
class
See here:
We have seen this same behavior in the past. It turned out that, for some crazy reason, if a NullPointerException occurred at the same place in the code multiple times, after a while using Log.error(String, Throwable)
would stop including full stack traces.
Try looking further back in your log. You may find the culprit.
EDIT: this bug sounds relevant, but it was fixed so long ago it's probably not the cause.
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
Try this:
String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));
Just to confirm though you probably did...
Did you include the
<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!-- tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />
bits in your application context.xml?
Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE_LOCAL instead.
@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.
Another option is to use nav-justified
..
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav nav-justified">
<li><a href="#" class="navbar-brand">Brand</a></li>
</ul>
</div>
</nav>
CSS
.navbar-brand {
float:none;
}
Try this one to push basic authentication at url:
curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
^^^^^^^^^^^^^^^^^^
If above one doesn't work, then you have nothing to do with it. So try the following alternates.
You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.
curl -i http://dev.myapp.com/api/users \
-H "Authorization: Basic Ym9zY236Ym9zY28=" \
-H "Application-Authorization: mytoken123"
Notice I have changed the header into Application-Authorization
. So from your application catch the token under that header and process what you need to do.
Another thing you can do is, to pass the token
through the POST
parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:
-d "auth-token=mytoken123"
The gradle versions in android studio and your code is not the same. This is why even after you update the gradle version on android studio, the error still persist.
So, edit the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file:
distributionUrl = https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
Ref: https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle
In Windows 7 it is at the path
C:\Users\[username]\.android
debug.keystore
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication
In Startup.cs
:
Add below lines to ConfigureServices
method :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(
CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
services.AddMvc();
// authentication
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddTransient(
m => new UserManager(
Configuration
.GetValue<string>(
DEFAULT_CONNECTIONSTRING //this is a string constant
)
)
);
services.AddDistributedMemoryCache();
}
keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize]
, they well force redirect to /Account/Login
url.
Add below lines to Configure
method :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler(ERROR_URL);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: DEFAULT_ROUTING);
});
}
Create your UserManager
class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):
public class UserManager
{
string _connectionString;
public UserManager(string connectionString)
{
_connectionString = connectionString;
}
public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
{
using (var con = new SqlConnection(_connectionString))
{
var queryString = "sp_user_login";
var dbUserData = con.Query<UserDbModel>(
queryString,
new
{
UserEmail = user.UserEmail,
UserPassword = user.UserPassword,
UserCellphone = user.UserCellphone
},
commandType: CommandType.StoredProcedure
).FirstOrDefault();
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
}
}
public async void SignOut(HttpContext httpContext)
{
await httpContext.SignOutAsync();
}
private IEnumerable<Claim> GetUserClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
claims.AddRange(this.GetUserRoleClaims(user));
return claims;
}
private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
return claims;
}
}
Then maybe you have an AccountController
which has a Login
Action that should look like below :
public class AccountController : Controller
{
UserManager _userManager;
public AccountController(UserManager userManager)
{
_userManager = userManager;
}
[HttpPost]
public IActionResult LogIn(LogInViewModel form)
{
if (!ModelState.IsValid)
return View(form);
try
{
//authenticate
var user = new UserDbModel()
{
UserEmail = form.Email,
UserCellphone = form.Cellphone,
UserPassword = form.Password
};
_userManager.SignIn(this.HttpContext, user);
return RedirectToAction("Search", "Home", null);
}
catch (Exception ex)
{
ModelState.AddModelError("summary", ex.Message);
return View(form);
}
}
}
Now you are able to use [Authorize]
annotation on any Action
or Controller
.
Feel free to comment any questions or bug's.
Sometimes it may happen that there are multiple schema created in a database.
So to be specific schema we need to target, so this will help to do it.
SELECT count(*) into @colCnt FROM information_schema.columns WHERE table_name = 'mytable' AND column_name = 'mycolumn' and table_schema = DATABASE();
IF @colCnt = 0 THEN
ALTER TABLE `mytable` ADD COLUMN `mycolumn` VARCHAR(20) DEFAULT NULL;
END IF;
Let's assume our work on branch "contact-form" is done and we've already integrated it into "master". Since we don't need it anymore, we can delete it (locally):
$ git branch -d contact-form
And for deleting the remote branch:
git push origin --delete contact-form
I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:
score = [1,2,3,4,5]
with open("file.txt", "w") as f:
for s in score:
f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
for line in f:
score.append(int(line.strip()))
So the items in the file are read as integers, despite being stored to the file as strings.
As per Jenkins Documentation,
BUILD_NUMBER
is used. This number is identify how many times jenkins run this build process
$BUILD_NUMBER
is general syntax for it.
An easy way to turn multiple loops into a single, breakable loop is to use numpy.ndindex
for i in range(n):
for j in range(n):
val = x[i, j]
break # still inside the outer loop!
for i, j in np.ndindex(n, n):
val = x[i, j]
break # you left the only loop there was!
You do have to index into your objects, as opposed to being able to iterate through the values explicitly, but at least in simple cases it seems to be approximately 2-20 times simpler than most of the answers suggested.
The de-facto standard way to split up complex functions in C is per argument:
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
sp->name,
sp->args,
sp->value,
sp->arraysize);
Or if you will:
const char format_str[] = "name: %s\targs: %s\tvalue %d\tarraysize %d\n";
...
printf(format_str,
sp->name,
sp->args,
sp->value,
sp->arraysize);
You shouldn't split up the string, nor should you use \
to break a C line. Such code quickly turns completely unreadable/unmaintainable.
$computername = $env:computername
[System.Net.Dns]::GetHostAddresses($computername) | where {$_.AddressFamily -notlike "InterNetworkV6"} | foreach {echo $_.IPAddressToString }
I assume you install gems into vendor/bundle
? If so, why not just delete all the gems and do a clean bundle install
?
Set the window start style as maximized. Then, hide the minimize and maximize buttons.
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
In the HTML source provided, the element #tfl
has an inline style "display:block
". Inline style will always override stylesheets styles…
Then, you have some options (while as you said you can't modify the html code nor using javascript):
display:none
with !important
rule (not recommended)put the div offscreen with theses rules :
#tfl {
position: absolute;
left: -9999px;
}
clock()
-> floating point number
Return the CPU time or real time since the start of the process or since
the first call to clock()
. This has as much precision as the system
records.
time()
-> floating point number
Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
Usually time()
is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)
In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:
In my POM I found this dependency and changed it from 6.0 to 7.0:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Then later in the POM I upgraded this plugin from 6.0 to 7.0:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
...
<configuration>
...
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
Swift answer:
myButton.addTarget(self, action: "click:", for: .touchUpInside)
func click(sender: UIButton) {
print("click")
}
Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
This depends on the language being used. You wrote 'language-agnostic', so I'll give some examples.
In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls.
In functional programming language implementations, sometimes, iteration can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.
I know that in some Scheme implementations, recursion will generally be faster than looping.
In short, the answer depends on the code and the implementation. Use whatever style you prefer. If you're using a functional language, recursion might be faster. If you're using an imperative language, iteration is probably faster. In some environments, both methods will result in the same assembly being generated (put that in your pipe and smoke it).
Addendum: In some environments, the best alternative is neither recursion nor iteration but instead higher order functions. These include "map", "filter", and "reduce" (which is also called "fold"). Not only are these the preferred style, not only are they often cleaner, but in some environments these functions are the first (or only) to get a boost from automatic parallelization — so they can be significantly faster than either iteration or recursion. Data Parallel Haskell is an example of such an environment.
List comprehensions are another alternative, but these are usually just syntactic sugar for iteration, recursion, or higher order functions.
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
They are they same because your doSomething function happens faster than the granularity of the timer. Try:
printf ("**MyProgram::before time= %ld\n", time(NULL));
for(i = 0; i < 1000; ++i) {
doSomthing();
doSomthingLong();
}
printf ("**MyProgram::after time= %ld\n", time(NULL));
I use a simple jQuery plugin to return the numeric value of any single CSS property.
It applies parseFloat
to the value returned by jQuery's default css
method.
Plugin Definition:
$.fn.cssNum = function(){
return parseFloat($.fn.css.apply(this,arguments));
}
Usage:
var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);
You can capture a screenshot from Android Studio as shown in the image below.
Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).
If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp
If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
For Devs getting this error in Web API Project -
The GetOwinContext extension method is defined in System.Web.Http.Owin
dll and one more package will be needed i.e. Microsoft.Owin.Host.SystemWeb
. This package needs to be installed in your project from nuget.
Link To Package: OWIN Package Install Command -
Install-Package Microsoft.AspNet.WebApi.Owin
Link To System.web Package : Package Install Command -
Install-Package Microsoft.Owin.Host.SystemWeb
In order to resolve this error you need to find why its occurring in your case. Please Cross check below points in your code -
You must have reference to Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.Owin;
Define GetOwinContext()
Under HttpContext.Current
as below -
return _userManager1 ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
OR
return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
Complete Code Where GetOwinContext() is used -
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
Namespace's I'm Using in Code File where GetOwinContext() Is used
using AngularJSAuthentication.API.Entities;
using AngularJSAuthentication.API.Models;
using HomeCinema.Common;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
I got this error while moving my code from my one project to another.
(new) device not showing, Check List:
They are very similar. Some may argue that @import is more maintainable. However, each @import will cost you a new HTTP request in the same fashion as using the "link" method. So in the context of speed it is no faster. And as "duskwuff" said, it doesn't load simultaneously which is a downfall.
It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock
from <chrono>
header.
Use it like so:
#include <iostream>
#include <chrono>
void function()
{
long long number = 0;
for( long long i = 0; i != 2000000; ++i )
{
number += 5;
}
}
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
function();
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << duration;
return 0;
}
This will measure the duration of the function.
NOTE: You will not always get the same timing for a function. This is because the CPU of your machine can be less or more used by other processes running on your computer, just as your mind can be more or less concentrated when you solve a math exercise. In the human mind, we can remember the solution of a math problem, but for a computer the same process will always be something new; thus, as I said, you will not always get the same result!
Purely on the basis of inheritance, you would use an Abstract where you're defining clearly descendant, abstract relationships (i.e. animal->cat) and/or require inheritance of virtual or non-public properties, especially shared state (which Interfaces cannot support).
You should try and favour composition (via dependency injection) over inheritance where you can though, and note that Interfaces being contracts support unit-testing, separation of concerns and (language varying) multiple inheritance in a way Abstracts cannot.
If you really want to use regex, then
>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
0 1
0 a 10
1 c 5
But it should be faster to do it like this:
>>> df[0] = df[0].str.strip()
In my case, the error occured in phpmyadmin version 4.5.1 when i set lower_case_table_names = 2 and had a table name with uppercase characters, The table had a primary key set to auto increment but still showed the error. The issue stopped when i changed the table name to all lowercase.