For such companies as google, amazon etc, whose servers are running at max capacity in 24/7-mode, reducing traffic means real money - less hardware, less energy, less maintenance. Shifting CPU-usage from server to client pays off, and SPAs shine. The advantages overweight disadvantages by far. So, SPA or not SPA depends much on the use case.
Just for mentioning another, probably not so obvious (for Web-developers) use case for SPAs: I'm currently looking for a way to implement GUIs in embedded systems and browser-based architecture seems appealing to me. Traditionally there were not many possibilities for UIs in embedded systems - Java, Qt, wx, etc or propriety commercial frameworks. Some years ago Adobe tried to enter the market with flash but seems to be not so successful.
Nowadays, as "embedded systems" are as powerful as mainframes some years ago, a browser-based UI connected to the control unit via REST is a possible solution. The advantage is, the huge palette of tools for UI for no cost. (e.g. Qt require 20-30$ per sold unit on royalty fees plus 3000-4000$ per developer)
For such architecture SPA offers many advantages - e.g. more familiar development-approach for desktop-app developers, reduced server access (often in car-industry the UI and system muddles are separate hardware, where the system-part has an RT OS).
As the only client is the built-in browser, the mentioned disadvantages like JS-availability, server-side logging, security don't count any more.
A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).
Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl
) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).
As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.
I ran into a similar situation trying to convert a table with several 100k rows with a C++ program (MFC/ODBC).
Since this operation took a very long time, I figured bundling multiple inserts into one (up to 1000 due to MSSQL limitations). My guess that a lot of single insert statements would create an overhead similar to what is described here.
However, it turns out that the conversion took actually quite a bit longer:
Method 1 Method 2 Method 3
Single Insert Multi Insert Joined Inserts
Rows 1000 1000 1000
Insert 390 ms 765 ms 270 ms
per Row 0.390 ms 0.765 ms 0.27 ms
So, 1000 single calls to CDatabase::ExecuteSql each with a single INSERT statement (method 1) are roughly twice as fast as a single call to CDatabase::ExecuteSql with a multi-line INSERT statement with 1000 value tuples (method 2).
Update: So, the next thing I tried was to bundle 1000 separate INSERT statements into a single string and have the server execute that (method 3). It turns out this is even a bit faster than method 1.
Edit: I am using Microsoft SQL Server Express Edition (64-bit) v10.0.2531.0
Firstly, as Etienne says, float
in C# is Single
. It is just the C# keyword for that data type.
So you can definitely do this:
float f = 13.5f;
string s = f.ToString("R");
Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal
, which does maintain its own precision; however, calling simply decimal.ToString
should have the effect you want in that case.
How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?
Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
It will round up so be aware of that.
I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.
Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
This page on MSDN lists standard DateTime format strings, uncluding strings using the 'Z'.
Update: you will need to make sure that the rest of the date string follows the correct pattern as well (you have not supplied an example of what you send it, so it's hard to say whether you did or not). For the UTC format to work it should look like this:
// yyyy'-'MM'-'dd HH':'mm':'ss'Z'
DateTime utcTime = DateTime.Parse("2009-05-07 08:17:25Z");
Pure JS
window.innerHeight
window.scrollY
is more than 10x faster than jquery (and code has similar size):
Here you can perform test on your machine: https://jsperf.com/window-height-width
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
Try this:
<!-- first page -->
<?php
session_start();
session_register('myvar');
$_SESSION['myvar'] == 'myvalue';
?>
<!-- second page -->
<?php
session_start();
echo("1");
if(session_is_registered('myvar'))
{
echo("2");
if($_SESSION['myvar'] == 'myvalue')
{
echo("3");
exit;
}
}
?>
Best way for Oracle:
With hardcoded datetime:
SELECT TO_CHAR(CAST((FROM_TZ(CAST(TO_DATE('2018-10-27 21:00', 'YYYY-MM-DD HH24:MI') AS TIMESTAMP), 'UTC') AT TIME ZONE 'EET') AS DATE), 'YYYY-MM-DD HH24:MI') UTC_TO_EET FROM DUAL
Result:
2018-10-28 00:00
With column and table names:
SELECT TO_CHAR(CAST((FROM_TZ(CAST(COLUMN_NAME AS TIMESTAMP), 'UTC') AT TIME ZONE 'EET') AS DATE), 'YYYY-MM-DD HH24:MI') UTC_TO_EET FROM TABLE_NAME
Java API specifies two methods you could use: indexOf(Object obj)
and lastIndexOf(Object obj)
. The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
You can create this function to calculate absolute difference between two dates. As I found using DATEDIFF inbuilt system function we will get the difference only in months, days and years. For example : Let say there are two dates 18-Jan-2018 and 15-Jan-2019. So the difference between those dates will be given by DATEDIFF in month as 12 months where as it is actually 11 Months 28 Days. So using the function given below, we can find absolute difference between two dates.
CREATE FUNCTION GetDurationInMonthAndDays(@First_Date DateTime,@Second_Date DateTime)
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE @RESULT VARCHAR(500)=''
DECLARE @MONTHS TABLE(MONTH_ID INT,MONTH_NAME VARCHAR(100),MONTH_DAYS INT)
INSERT INTO @MONTHS
SELECT 1,'Jan',31
union SELECT 2,'Feb',28
union SELECT 3,'Mar',31
union SELECT 4,'Apr',30
union SELECT 5,'May',31
union SELECT 6,'Jun',30
union SELECT 7,'Jul',31
union SELECT 8,'Aug',31
union SELECT 9,'Sep',30
union SELECT 10,'Oct',31
union SELECT 11,'Nov',30
union SELECT 12,'Jan',31
IF(@Second_Date>@First_Date)
BEGIN
declare @month int=0
declare @days int=0
declare @first_year int
declare @second_year int
SELECT @first_year=Year(@First_Date)
SELECT @second_year=Year(@Second_Date)+1
declare @first_month int
declare @second_month int
SELECT @first_month=Month(@First_Date)
SELECT @second_month=Month(@Second_Date)
if(@first_month=2)
begin
IF((@first_year%100<>0) AND (@first_year%4=0) OR (@first_year%400=0))
BEGIN
SELECT @days=29-day(@First_Date)
END
else
begin
SELECT @days=28-day(@First_Date)
end
end
else
begin
SELECT @days=(SELECT MONTH_DAYS FROM @MONTHS WHERE MONTH_ID=@first_month)-day(@First_Date)
end
SELECT @first_month=@first_month+1
WHILE @first_year<@second_year
BEGIN
if(@first_month=13)
begin
set @first_month=1
end
WHILE @first_month<13
BEGIN
if(@first_year=Year(@Second_Date))
begin
if(@first_month=@second_month)
begin
SELECT @days=@days+DAY(@Second_Date)
break;
end
else
begin
SELECT @month=@month+1
end
end
ELSE
BEGIN
SELECT @month=@month+1
END
SET @first_month=@first_month+1
END
SET @first_year = @first_year + 1
END
select @month=@month+(@days/30)
select @days=@days%30
if(@days>0)
begin
SELECT @RESULT=CAST(@month AS VARCHAR)+' Month '+CAST(@days AS VARCHAR)+' Days '
end
else
begin
SELECT @RESULT=CAST(@month AS VARCHAR)+' Month '
end
END
ELSE
BEGIN
SELECT @RESULT='ERROR'
END
RETURN @RESULT
END
Create a variable:
var thing1 = undefined;
Declare a Function:
function something1 () {
return "Hi there, I'm number 1!";
}
Alert the value of thing1
(our first variable):
alert(thing1); // Outputs: "undefined".
Now, if we wanted thing1
to be a reference to the function something1
, meaning it would be the same thing as our created function, we would do:
thing1 = something1;
However, if we wanted the return
value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:
thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!"
BuildToolsVersion & Dependencies must be same with Base API version.
buildToolsVersion '23.0.2' & compile
&
com.android.support:appcompat-v7:24.0.0-alpha1
can not match with base API level.
It should be
compile 'com.android.support:appcompat-v7:21.0.3'
Done
You shouldn't be setting the value of the input through refs.
Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components
In a nutshell
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />
Then you will be able to control the disabled state by using disabled={!this.state.value}
Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.
Here is an example on how to parse a JSON string into a dynamic object:
string source = "{\r\n \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\", \r\n \"first_name\": \"Jerard\", \r\n \"last_name\": \"Jones\", \r\n \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n \"username\": \"Jerard.Jones\", \r\n \"gender\": \"female\", \r\n \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);
Happy coding!
In ssms we can use GO to execute same statement
Edit This mean if you put
some query
GO n
Some query will be executed n times
<script type="text/javascript">_x000D_
function get_param(param) {_x000D_
var search = window.location.search.substring(1);_x000D_
var compareKeyValuePair = function(pair) {_x000D_
var key_value = pair.split('=');_x000D_
var decodedKey = decodeURIComponent(key_value[0]);_x000D_
var decodedValue = decodeURIComponent(key_value[1]);_x000D_
if(decodedKey == param) return decodedValue;_x000D_
return null;_x000D_
};_x000D_
_x000D_
var comparisonResult = null;_x000D_
_x000D_
if(search.indexOf('&') > -1) {_x000D_
var params = search.split('&');_x000D_
for(var i = 0; i < params.length; i++) {_x000D_
comparisonResult = compareKeyValuePair(params[i]); _x000D_
if(comparisonResult !== null) {_x000D_
break;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
comparisonResult = compareKeyValuePair(search);_x000D_
}_x000D_
_x000D_
return comparisonResult;_x000D_
}_x000D_
_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_
_x000D_
_x000D_
</script>
_x000D_
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">_x000D_
document.write(registrySectionId)_x000D_
</script></td>
_x000D_
this line of code on your terminal, solves the problem
$ sudo chown -R $USER:$USER anaconda 3
If you just want to have an event when a tab is selected, this is the correct way:
<TabControl>
<TabItem Selector.Selected="OnTabSelected" />
<TabItem Selector.Selected="OnTabSelected" />
<TabItem Selector.Selected="OnTabSelected" />
<!-- You can also catch the unselected event -->
<TabItem Selector.Unselected="OnTabUnSelected" />
</TabControl>
And in your code
private void OnTabSelected(object sender, RoutedEventArgs e)
{
var tab = sender as TabItem;
if (tab != null)
{
// this tab is selected!
}
}
As I know you can't make array without size, but you can use
List<string> l = new List<string>()
and then l.ToArray()
.
Depending on the sort order, you can do this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)
));
... or this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
i1 and i2 are just reversed.
I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.
I also had the added complication of using Apache rewrite to change example.com/page-name
into example.com/index.pl?page=page-name
. I found that changing the form's action caused example.com/index.pl
(with no page parameter) to be rendered, even though the expected URL (example.com/page-name
) was displayed in the address bar.
To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
In the form:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
Here are my Apache rewrite rules:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
I'd be interested in any explanation as to why just setting the action didn't work.
java: Java application executor which is associated with a console to display output/errors
javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.
javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.
All are part of JRE and use the same JVM.
Here comes a rather obsqure idea. When every year dividable with 100 gets 365 days, what shall be done at this time? In the far future, when even years dividable with 400 only can get 365 days.
Then there is a possibility or reason to make corrections in years dividable with 80. Normal years will have 365 day and those dividable with 400 can get 366 days. Or is this a loose-loose situation.
I had exactly the same problem. My environment was:
The symptoms of the problems were:
The solution (described above) about updating the m2e extensions worked for me.
Better solution (my recommondation):
I know this thread is bit old.
But I'm going to post this anyway hoping it might help someone.
We can store fields of any Object to shared preference by serializing the object to String.
Here I have used GSON
for storing any object to shared preference.
Save Object to Preference :
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
Retrieve Object from Preference:
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
Note :
Remember to add compile 'com.google.code.gson:gson:2.6.2'
to dependencies
in your gradle.
Example :
//assume SampleClass exists
SampleClass mObject = new SampleObject();
//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
As @Sharp_Edge pointed out in comments, the above solution does not work with List
.
A slight modification to the signature of getSavedObjectFromPreference()
- from Class<GenericClass> classType
to Type classType
will make this solution generalized. Modified function signature,
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
For invoking,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
Happy Coding!
For Symfony 2.3+, to get the base url in a controller should be
$this->get('request')->getSchemeAndHttpHost();
The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed?
methods don't return true for changed attributes in the after_update
hook, only in the before_update
hook. I was able to get it to work using the (new?) around_update
hook:
class SomeModel < ActiveRecord::Base
around_update :send_notification_after_change
def send_notification_after_change
should_send_it = self.published_changed? && self.published == true
yield
Notification.send(...) if should_send_it
end
end
set phpmailer to work in debug to see the "real" error behind the generic message 'SMTP Error: data not accepted' in our case the text in the message was triggering the smtp server spam filter.
$email->SMTPDebug = true;
Add:
<%= csrf_meta_tag %> and
<%= javascript_include_tag :defaults %> to layouts
Use these link_to tags
link_to 'Sign out', destroy_user_session_path, :method => :delete
or
link_to 'Sign out', '/users/sign_out', :method => :delete
In routes add:
devise_for :users do
get '/users/sign_out' => 'devise/sessions#destroy'
end
I solved this issue by running cmd as an administrator. before that, I was trying to run in vs code.
run it in Power Shell or Cmd with administrative privilege. I hope that it will help.
npm install –g @angular/cli@latest
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
Update 2018
Here's a simple example using Bootstrap 4 with ChartJs. Use an HTML5 Canvas element for the chart...
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-body">
<canvas id="chLine"></canvas>
</div>
</div>
</div>
</div>
</div>
And then the appropriate JS to populate the chart...
var colors = ['#007bff','#28a745'];
var chLine = document.getElementById("chLine");
var chartData = {
labels: ["S", "M", "T", "W", "T", "F", "S"],
datasets: [{
data: [589, 445, 483, 503, 689, 692, 634],
borderColor: colors[0],
borderWidth: 4,
pointBackgroundColor: colors[0]
},
{
data: [639, 465, 493, 478, 589, 632, 674],
borderColor: colors[1],
borderWidth: 4,
pointBackgroundColor: colors[1]
}]
};
if (chLine) {
new Chart(chLine, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
}
}
});
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
It's strange because @ControllerAdvice should works, are you catching the correct Exception?
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ResponseBody
@ExceptionHandler(value = DataAccessException.class)
public String defaultErrorHandler(HttpServletResponse response, DataAccessException e) throws Exception {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//Json return
}
}
Also try to catch this exception in CorsFilter and send 500 error, something like this
@ExceptionHandler(DataAccessException.class)
@ResponseBody
public String handleDataException(DataAccessException ex, HttpServletResponse response) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//Json return
}
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY()
function being used in SQL Server
.
You also need to keep in mind that this will only work if Last_INSERT_ID()
is fired following by your Insert
query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
If all you need is a subject line (as in an alert message) simply do:
mailx -s "This is all she wrote" < /dev/null "myself@myaddress"
High level consumers are registered into Zookeeper, so you can fetch a list from ZK, similarly to the way kafka-topics.sh
fetches the list of topics. I don't think there's a way to collect all consumers; any application sending in a few consume requests is actually a "consumer", and you cannot tell whether they are done already.
On the consumer side, there's a JMX metric exposed to monitor the lag. Also, there is Burrow for lag monitoring.
It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:
axs.set_ylabel('mylabel',size=6)
you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.
def set_pubfig:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.
Note: If you specify these numbers, specifying font_scale
in sns.set_context
is ignored for all specified font elements, even if you set it.
document.getElementsByClassName
returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0];
should get you what you want.
Update #1:
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Update #2: (with removeEventListener
incorporated as well)
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment(e) {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
for (var i = 0; i < numComments; i++) {
comments[i].removeEventListener('click', showComment, false);
}
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Don't use systemPath. Contrary to what people have said here, you can put an external jar in a folder under your checked-out project directory and haven Maven find it like other dependencies. Here are two crucial steps:
It is fairly straightforward and you can find a step-by-step example here: http://randomizedsort.blogspot.com/2011/10/configuring-maven-to-use-local-library.html
Just to help anyone coming to this page. This is an alternate if you are flexible with using some other icon library.
James is correct that you cannot change the font weight however if you are looking for more modern look for icons then you might consider ionicons
It has both ios and android versions for icons.
DON'T use (.|[\r\n])
instead of .
for multiline matching.
DO use [\s\S]
instead of .
for multiline matching
Also, avoid greediness where not needed by using *?
or +?
quantifier instead of *
or +
. This can have a huge performance impact.
See the benchmark I have made: http://jsperf.com/javascript-multiline-regexp-workarounds
Using [^]: fastest
Using [\s\S]: 0.83% slower
Using (.|\r|\n): 96% slower
Using (.|[\r\n]): 96% slower
NB: You can also use [^]
but it is deprecated in the below comment.
Another difference to pay attention to is handling of undefined
values:
mergeInto = { a: 1}
toMerge = {a : undefined, b:undefined}
lodash.extend({}, mergeInto, toMerge) // => {a: undefined, b:undefined}
lodash.merge({}, mergeInto, toMerge) // => {a: 1, b:undefined}
So merge
will not merge undefined
values into defined values.
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
CASE AlarmEventTransactions.DeviceID
should just be CASE
.
You are mixing the 2 forms of the CASE
expression.
Range("A:B,D:E,G:H").Select
can help
Edit note: I just saw you have used different column sequence, I have updated my answer
Eloquent::insert
is the proper solution but it wont update the timestamps, so you can do something like below
$json_array=array_map(function ($a) {
return array_merge($a,['created_at'=>
Carbon::now(),'updated_at'=> Carbon::now()]
);
}, $json_array);
Model::insert($json_array);
The idea is to add created_at and updated_at on whole array before doing insert
Try this :
$('#resetBtn').on('click', function(e){
e.preventDefault();
$("#myform")[0].reset.click();
}
I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn't change length etc.)
something like
$in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4);
should do it.
pom.xml
as -<project>
....
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
...
</build>
...
</project>
In Rails 4, this is a better (DRYer) solution:
change_column_null :my_models, :date_column, false
To ensure no records exist with NULL
values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL
values:
change_column_null :my_models, :date_column, false, Time.now
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:
import matplotlib.pyplot as plt
import numpy
w = 7195
h = 3841
im_np = numpy.random.rand(h, w)
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig('figure.png', dpi=1)
I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.
Hope that helps!
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
I found the ioctl solution problematic on os x (which is POSIX compliant so should be similiar to linux). However getifaddress() will let you do the same thing easily, it works fine for me on os x 10.5 and should be the same below.
I've done a quick example below which will print all of the machine's IPv4 address, (you should also check the getifaddrs was successful ie returns 0).
I've updated it show IPv6 addresses too.
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
int main (int argc, const char * argv[]) {
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
} else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6
// is a valid IP6 Address
tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
}
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
return 0;
}
I have found following solution to replace following code
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
It's work fine for me
Since most of the answers here are targeted towards iOS here's a solution for changing icon in Android.
For android:
Make changes in <project location>\platforms\android\ant-build\res and not <project location>\platforms\android\res
For some people making changes in the latter location may have worked, but having noticed Phonegap copying from \android\res into \android\ant-build\res, I decided to check in there and found a separate set of drawable folders containing the default phonegap icon.
Changing those finally worked.
Since I'm building and running locally and not using Adobe PhoneGap Build, changing icons in <project location>\www\res\icon\android didn't work either.
This is a 100% solution. I tried it myself.
myisamchk -r -v -f --sort_buffer_size=128M --key_buffer_size=128M /var/lib/mysql/databasename/tabloname
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
If you need the highlighted tint which the OS provides by default when you tap and hold on a custom button for the selected state as well, use this UIButton subclass. Written in Swift 5:
import Foundation
import UIKit
class HighlightOnSelectCustomButton: UIButton {
override var isHighlighted: Bool {
didSet {
if (self.isSelected != isHighlighted) {
self.isHighlighted = self.isSelected
}
}
}
}
why don't you use width: 100%
and height: 100%
.
Programmatically display text over rect using basic Javascript
var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];_x000D_
_x000D_
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text.setAttribute('x', 20);_x000D_
text.setAttribute('y', 50);_x000D_
text.setAttribute('width', 500);_x000D_
text.style.fill = 'red';_x000D_
text.style.fontFamily = 'Verdana';_x000D_
text.style.fontSize = '35';_x000D_
text.innerHTML = "Some text line";_x000D_
_x000D_
svg.appendChild(text);_x000D_
_x000D_
var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text2.setAttribute('x', 20);_x000D_
text2.setAttribute('y', 100);_x000D_
text2.setAttribute('width', 500);_x000D_
text2.style.fill = 'green';_x000D_
text2.style.fontFamily = 'Calibri';_x000D_
text2.style.fontSize = '35';_x000D_
text2.style.fontStyle = 'italic';_x000D_
text2.innerHTML = "Some italic line";_x000D_
_x000D_
_x000D_
svg.appendChild(text2);_x000D_
_x000D_
var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
text3.setAttribute('x', 20);_x000D_
text3.setAttribute('y', 150);_x000D_
text3.setAttribute('width', 500);_x000D_
text3.style.fill = 'green';_x000D_
text3.style.fontFamily = 'Calibri';_x000D_
text3.style.fontSize = '35';_x000D_
text3.style.fontWeight = 700;_x000D_
text3.innerHTML = "Some bold line";_x000D_
_x000D_
_x000D_
svg.appendChild(text3);
_x000D_
<svg width="510" height="250" xmlns="http://www.w3.org/2000/svg">_x000D_
<rect x="0" y="0" width="510" height="250" fill="aquamarine" />_x000D_
</svg>
_x000D_
It is recommend to use List to deal with small scale size.
If you have a huge number of numbers, NEVER use List and autoboxing,
List< Integer> list
For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects. In this case, to use a estimated size would be better,
int[] array = new int[ESTIMATED_SIZE];
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
One possible idea is to write separate constructor function
//Something is the structure we work with
type Something struct {
Text string
DefaultText string
}
// NewSomething create new instance of Something
func NewSomething(text string) Something {
something := Something{}
something.Text = text
something.DefaultText = "default text"
return something
}
The use of -X [WHATEVER]
merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER]
and one without — and the associated HTTP request headers for each:
# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
Here is the code to redirect to some other page with a timeout of 10 seconds.
<script>
function Redirect()
{
window.location="http://www.adarshkr.com";
}
document.write("You will be redirected to a new page in 10 seconds.");
setTimeout('Redirect()', 10000);
</script>
You can also do it like this, on click of a button using location.assign:
<input type="button" value="Load new document" onclick="newPage()">
<script>
function newPage() {
window.location.assign("http://www.adarshkr.com")
}
</script>
I faced this problem while using AptanaStudio3 on windows7. This helped me:
git config --global credential.helper wincred
Code taken from here
Simple and neat with fontawesome
input[type=radio] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
outline: none;
content: none;
margin-left: 5px;
}
input[type=radio]:before {
font-family: "FontAwesome";
content: "\f00c";
font-size: 25px;
color: transparent !important;
background: #fff;
width: 25px;
height: 25px;
border: 2px solid black;
margin-right: 5px;
}
input[type=radio]:checked:before {
color: black !important;
}
In my opinion, this will be the best approach as a beginner:
echo "<pre>";
print_r($query->toSql());
print_r($query->getBindings());
This is also depicted here. https://stackoverflow.com/a/59207557/9573341
From the accepted answer, it looks like your desired behaviour is to turn
skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
into
2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
If that's right, then I think something like
import csv
with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile, quoting=False)
for i, line in enumerate(reader):
if i < 4: continue
date = line[0].split()
day = date[0].split('-')
time = date[1].split(':')
newline = day + time + line[1:]
writer.writerow(newline)
would be a little simpler than the reps
stuff.
z-index only works on absolute or relatively positioned elements. I would use an outer div set to position relative. Set the div on top to position absolute to remove it from the flow of the document.
.wrapper {position:relative;width:500px;}_x000D_
_x000D_
.front {_x000D_
border:3px solid #c00;_x000D_
background-color:#fff;_x000D_
width:300px;_x000D_
position:absolute;_x000D_
z-index:10;_x000D_
top:30px;_x000D_
left:50px;_x000D_
}_x000D_
_x000D_
.behind {background-color:#ccc;}
_x000D_
<div class="wrapper">_x000D_
<p class="front">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>_x000D_
<div class="behind">_x000D_
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>aaa</th>_x000D_
<th>bbb</th>_x000D_
<th>ccc</th>_x000D_
<th>ddd</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>111</td>_x000D_
<td>222</td>_x000D_
<td>333</td>_x000D_
<td>444</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
</div> _x000D_
</div>
_x000D_
Update: ICS emulator supports camera.
Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with @SupressWarnings("unchecked")
, would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.
@SuppressWarnings("unchecked")
public static List<String> getFooStrings(Map<String, List<String>> ctx) {
return (List<String>) ctx.get("foos");
}
So there are few places where terminal looks for commands. This places are stored in your $PATH
variable. Think of it as a global variable where terminal iterates over to look up for any command. This are usually binaries look how /bin folder is usually referenced.
/bin
folder has lots of executable files inside it. Turns out this are command. This different folder locations are stored inside one Global variable i.e. $PATH
separated by :
Now usually programs upon installation takes care of updating PATH
& telling your terminal that hey i can be all commands inside my bin
folder.
Turns out MySql doesn't do it upon install so we manually have to do it.
We do it by following command,
export PATH=$PATH:/usr/local/mysql/bin
If you break it down, export
is self explanatory. Think of it as an assignment. So export
a variable PATH
with value old $PATH
concat with new bin
i.e. /usr/local/mysql/bin
This way after executing it all the commands inside /usr/local/mysql/bin
are available to us.
There is a small catch here. Think of one terminal window as one instance of program and maybe something like $PATH
is class variable ( maybe ). Note this is pure assumption. So upon close we lose the new assignment. And if we reopen terminal we won't have access to our command again because last when we exported, it was stored in primary memory which is volatile.
Now we need to have our mysql binaries exported every-time we use terminal. So we have to persist concat in our path.
You might be aware that our terminal using something called dotfiles
to load configuration on terminal initialisation. I like to think of it's as sets of thing passed to constructer every-time a new instance of terminal is created ( Again an assumption but close to what it might be doing ). So yes by now you get the point what we are going todo.
.bash_profile
is one of the primary known dotfile
.
So in following command,
echo 'export PATH=$PATH:/usr/local/mysql/bin' >> ~/.bash_profile
What we are doing is saving result of echo
i.e. output string to ~/.bash_profile
So now as we noted above every-time we open terminal or instance of terminal our dotfiles
are loaded. So .bash_profile
is loaded respectively and export
that we appended above is run & thus a our global $PATH
gets updated and we get all the commands inside /usr/local/mysql/bin
.
P.s.
if you are not running first command export directly but just running second in order to persist it? Than for current running instance of terminal you have to,
source ~/.bash_profile
This tells our terminal to reload that particular file.
There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend()
method/function that operates on the OrderedDict
internals with O(1) complexity.
For Python 3.2 and later, you should use the move_to_end
method. The method accepts a last
argument which indicates whether the element will be moved to the bottom (last=True
) or the top (last=False
) of the OrderedDict
.
Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict
from scratch.
Details for the four different solutions:
OrderedDict
and add a new instance methodfrom collections import OrderedDict
class MyOrderedDict(OrderedDict):
def prepend(self, key, value, dict_setitem=dict.__setitem__):
root = self._OrderedDict__root
first = root[1]
if key in self:
link = self._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
dict_setitem(self, key, value)
Demo:
>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict
objectsThis function does the same thing by accepting the dict object, key and value. I personally prefer the class:
from collections import OrderedDict
def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
root = dct._OrderedDict__root
first = root[1]
if key in dct:
link = dct._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
dict_setitem(dct, key, value)
Demo:
>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict.move_to_end()
(Python >= 3.2)Python 3.2 introduced the OrderedDict.move_to_end()
method. Using it, we can move an existing key to either end of the dictionary in O(1) time.
>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])
If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend()
wrapper (not presented here).
OrderedDict
- slow!!!If you don't want to do that and performance is not an issue then easiest way is to create a new dict:
from itertools import chain, ifilterfalse
from collections import OrderedDict
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)]) #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
unique_everseen(chain(d2, d1)))
print new_dic
output:
OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])
This might be helpful
from bs4 import UnicodeDammit
with open('automate_data/billboard.csv', 'rb') as file:
content = file.read()
suggestion = UnicodeDammit(content)
suggestion.original_encoding
#'iso-8859-1'
This is correct query for join 3 table with same id**
select a.empname,a.empsalary,b.workstatus,b.bonus,c.dateofbirth from employee a, Report b,birth c where a.empid=b.empid and a.empid=c.empid and b.empid='103';
employee first table. report second table. birth third table
Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).
Let's say we have these tables and columns:
Company:
CompanyId (primary key)
CostCenter:
CompanyId (primary key, foreign key to Company)
CostCentre (primary key)
CostElement
CompanyId (primary key, foreign key to Company)
CostElement (primary key)
Invoice:
InvoiceId (primary key)
CompanyId (primary key, in foreign key to CostCentre, in foreign key to CostElement)
CostCentre (in foreign key to CostCentre)
CostElement (in foreign key to CostElement)
In case that last bit doesn't make sense, Invoice.CompanyId
is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).
In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.
The fewer chances to screw up, the better.
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
Make sure your .NET version 4.5 or greater
you can try this code:
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells[0];
dataGridView1.BeginEdit(true);
if (chk.Value == null || (int)chk.Value == 0)
{
chk.Value = 1;
}
else
{
chk.Value = 0;
}
dataGridView1.EndEdit();
Set a minimum width at the top most layout.
android:minWidth="300dp"
For example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="300dp">
<!-- Put remaining contents here -->
</LinearLayout>
Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
You have no public getters for your UpdateResult, for example :
public static class UploadResult {
private String value;
public UploadResult(final String value)
{
this.value = value;
}
public String getValue() {
return this.value;
}
}
I believe by default auto discovery is on and will try to discover your getters. You can disable it with @JsonAutoDetect(getterVisibility=Visibility.NONE)
, and in your example will result in []
.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}
}
}
Output:
1234
789
2345
Use the ? symbol (encoded as ⚲
or ⚲
), and rotate it to achieve the desired effect:
<div style="-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);">
⚲
</div>
It rotates a symbol :)
I just cleaned up RHT's answer to eliminate some warnings and thought I would share. Eclipse did most of the work:
public List<HashMap<String,Object>> convertResultSetToList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
while (rs.next()) {
HashMap<String,Object> row = new HashMap<String, Object>(columns);
for(int i=1; i<=columns; ++i) {
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
return list;
}
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
No you would have to create your own solution. Like using the Observer design pattern or something.
If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!
Mike
To reset your keyring.
Go into your home folder.
Press ctrl & h to show your hidden folders.
Now look in your .gnome2/keyrings directory.
Find the default.keyring file.
Move that file to a different folder.
Once done, reboot your computer.
One way is to use window.print() function. Which does not require any library
Pros
1.No external library require.
2.We can print only selected parts of body also.
3.No css conflicts and js issues.
4.Core html/js functionality
---Simply add below code
CSS to
@media print {
body * {
visibility: hidden; // part to hide at the time of print
-webkit-print-color-adjust: exact !important; // not necessary use
if colors not visible
}
#printBtn {
visibility: hidden !important; // To hide
}
#page-wrapper * {
visibility: visible; // Print only required part
text-align: left;
-webkit-print-color-adjust: exact !important;
}
}
JS code - Call bewlow function on btn click
$scope.printWindow = function () {
window.print()
}
Note: Use !important in every css object
Example -
.legend {
background: #9DD2E2 !important;
}
You can use getFragmentManager().popBackStack()
in basic Fragment
to go back.
After upgrading to macOS v10.15 (Catalina), and upgrading all my vEnv modules, pip3 stopped working (gave error: "TypeError: 'module' object is not callable").
I found question 58386953 which led to here and solution.
sudo python3 -m pip uninstall pip
(this is necessary, but it did not fix problem, because it removed the base Python pip, but it didn't touch my vEnv pip)sudo easy_install pip
(reinstalling pip in base Python, not in vEnv)vEnv/bin
and type "source activate" to get into vEnvrm pip pip3 pip3.6
(it seems to be the only way to get rid of the bogus pip's in vEnv)connect your server from mysqlworkbench and run this command-> ALTER USER 'root'@'localhost' IDENTIFIED BY 'yourpassword';
This adds to rm8x's answer.
Download and install the NuGet command line tool.
List all of our locals:
$ nuget locals all -list
http-cache: C:\Users\MyUser\AppData\Local\NuGet\v3-cache
packages-cache: C:\Users\MyUser\AppData\Local\NuGet\Cache
global-packages: C:\Users\MyUser\.nuget\packages\
We can now delete these manually or as rm8x suggests, use nuget locals all -clear
.
Today. I have same problem... my solution:
1) check inode: df -i
I saw:
root@vm22433:/etc/mysql# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 452 127062 1% /run
/dev/vda1 1969920 1969920 0 100% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
2) I began to look what folders use the maximum number of inods:
for i in /*; do echo $i; find $i |wc -l; done
soon I found in /home/tomnolane/tmp folder, which contained a huge number of files.
3) I removed /home/tomnolane/tmp folder PROFIT.
4) checked:
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 454 127060 1% /run
/dev/vda1 1969920 450857 1519063 23% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
it's ok.
5) restart mysql service
- it's ok!!!!
This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.
It worked for me quite well.
NOTE: See @SDP's answer for a clean, built-in solution
I fixed it as follows:
make sure you include application.js before the other app dependent js files get included by changing the include order as follows:
// in application.js - make sure `require_self` comes before `require_tree .`
//= require_self
//= require_tree .
Define a global function that handles the binding in application.js
// application.js
window.onLoad = function(callback) {
// binds ready event and turbolink page:load event
$(document).ready(callback);
$(document).on('page:load',callback);
};
Now you can bind stuff like:
// in coffee script:
onLoad ->
$('a.clickable').click =>
alert('link clicked!');
// equivalent in javascript:
onLoad(function() {
$('a.clickable').click(function() {
alert('link clicked');
});
Try to implement dynamic data structure such as a linked list
Let me address your question about "modes." AES256 is a kind of block cipher. It takes as input a 32-byte key and a 16-byte string, called the block and outputs a block. We use AES in a mode of operation in order to encrypt. The solutions above suggest using CBC, which is one example. Another is called CTR, and it's somewhat easier to use:
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
# AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
key_bytes = 32
# Takes as input a 32-byte key and an arbitrary-length plaintext and returns a
# pair (iv, ciphtertext). "iv" stands for initialization vector.
def encrypt(key, plaintext):
assert len(key) == key_bytes
# Choose a random, 16-byte IV.
iv = Random.new().read(AES.block_size)
# Convert the IV to a Python integer.
iv_int = int(binascii.hexlify(iv), 16)
# Create a new Counter object with IV = iv_int.
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Encrypt and return IV and ciphertext.
ciphertext = aes.encrypt(plaintext)
return (iv, ciphertext)
# Takes as input a 32-byte key, a 16-byte IV, and a ciphertext, and outputs the
# corresponding plaintext.
def decrypt(key, iv, ciphertext):
assert len(key) == key_bytes
# Initialize counter for decryption. iv should be the same as the output of
# encrypt().
iv_int = int(iv.encode('hex'), 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Decrypt and return the plaintext.
plaintext = aes.decrypt(ciphertext)
return plaintext
(iv, ciphertext) = encrypt(key, 'hella')
print decrypt(key, iv, ciphertext)
This is often referred to as AES-CTR. I would advise caution in using AES-CBC with PyCrypto. The reason is that it requires you to specify the padding scheme, as exemplified by the other solutions given. In general, if you're not very careful about the padding, there are attacks that completely break encryption!
Now, it's important to note that the key must be a random, 32-byte string; a password does not suffice. Normally, the key is generated like so:
# Nominal way to generate a fresh key. This calls the system's random number
# generator (RNG).
key1 = Random.new().read(key_bytes)
A key may be derived from a password, too:
# It's also possible to derive a key from a password, but it's important that
# the password have high entropy, meaning difficult to predict.
password = "This is a rather weak password."
# For added # security, we add a "salt", which increases the entropy.
#
# In this example, we use the same RNG to produce the salt that we used to
# produce key1.
salt_bytes = 8
salt = Random.new().read(salt_bytes)
# Stands for "Password-based key derivation function 2"
key2 = PBKDF2(password, salt, key_bytes)
Some solutions above suggest using SHA256 for deriving the key, but this is generally considered bad cryptographic practice. Check out wikipedia for more on modes of operation.
In my case, I had created a run configuration and whenever I tried to run it, the error would be displayed. After searching on some websites, I edited the run configuration and under JRE tab, selected the runtime JRE as 'workspace default JRE' which I had already configured to point to my local Java JDK installation (ex. C:\Program Files (x86)\Java\jdk1.8.0_51). This solved my issue. Maybe it helps someone out there.
Here is an example of what I would do. I hope it's what you're looking for.
char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)
a should now contain:
data data2
1 foo_ 1
2 bar_ 2
3 ap 3
4 b 4
If you use <img> tags, then webkit based browsers won't display embedded bitmapped images.
For any kind of advanced SVG use, including the SVG inline offers by far the most flexibility.
Internet Explorer and Edge will resize the SVG correctly, but you must specify both the height and width.
You can add onclick, onmouseover, etc. inside the svg, to any shape in the SVG: onmouseover="top.myfunction(evt);"
You can also use web fonts in the SVG by including them in your regular style sheet.
Note: if you are exporting SVG's from Illustrator, the web font names will be wrong. You can correct this in your CSS and avoid messing around in the SVG. For example, Illustrator gives the wrong name to Arial, and you can fix it like this:
@font-face {
font-family: 'ArialMT';
src:
local('Arial'),
local('Arial MT'),
local('Arial Regular');
font-weight: normal;
font-style: normal;
}
All this works on any browser released since 2013.
For an example, see ozake.com. The whole site is made of SVG's except for the contact form.
Warning: Web fonts are imprecisely resized in Safari — and if you have lots of transitions from plain text to bold or italic, there may be a small amount of extra or missing space at the transition points. See my answer at this question for more information.
I have faced the same problem a week ago. The problem is with the time zone setting. Specify in other formats like mm/dd/yyyy (usually works).
Specifying the date as 30/12/2013 resulted in the error for me. However, specifying it as mm/dd/yyyy format worked.
If you need to convert your input the you can try looking into the CONVERT
method.
Syntax is
CONVERT(VARCHAR,@your_date_Value,103)
CONVERT(VARCHAR, '12/30/2013', 103)
The finishing 103 is the datetime format.
Refer this link for conversion formats and further reading. https://www.w3schools.com/sql/func_sqlserver_convert.asp
In XCode 6.3.1, if you use a NSTextField
you will not see the checkbox for secure
.
Instead of using NSTextField
use NSSecureTextField
I'm guessing this is a Swift/Objective-C change since there is now a class for secure text fields. In the above link it says Available in OS X v10.0 and later.
If you know more about when/why/what versions of Swift/Objective-C, XCode, or OS X this
readline
is specifically designed to work with terminal (that is process.stdin.isTTY === true
). There are a lot of modules which provide split functionality for generic streams, like split. It makes things super-easy:
process.stdin.pipe(require('split')()).on('data', processLine)
function processLine (line) {
console.log(line + '!')
}
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
From https://www.w3schools.com/css/css_boxmodel.asp
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
Navigate to the folder in Windows Explorer, highlight the complete folder path in the top pane and type "cmd" - voila!
HTML:
<div id="myElement">Rounded Corner Box</div>
CSS:
#myElement {
background: #EEE;
padding: 2em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
behavior: url(PIE.htc);
border: 1px solid red;
}
PIE.htc file can be downloaded from http://www.css3pie.com
Give unique class and different id for file input
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.
public static void main(String[] args) {
Map<String, String> test = new HashMap<String, String>();
test.put("a", "1");
test.put("d", "1");
test.put("b", "2");
test.put("c", "3");
test.put("d", "4");
test.put("d", "41");
System.out.println(test);
Map<String, String> test1 = MapUtils.invertMap(test);
System.out.println(test1);
Map<String, String> mapInversed =
test.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
System.out.println(mapInversed);
}
Output:
{a=1, b=2, c=3, d=41}
{1=a, 2=b, 3=c, 41=d}
{1=a, 2=b, 3=c, 41=d}
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
From the official documentation:
It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.
...
This file should contain lines of the following format:
hostname:port:database:username:password
The password field from the first line that matches the current connection parameters will be used.
@klode's answer is right.
However, you are supposed to set another response header to make your header accessible to others.
Example:
First, you add 'page-size' in response header
response.set('page-size', 20);
Then, all you need to do is expose your header
response.set('Access-Control-Expose-Headers', 'page-size')
For me, it turns out that there was an iOS system update pending asking to restart the computer. Restart and let the update finish solved my problem.
For enter event handling you can use
@keyup.enter
or@keyup.13
13 is the keycode of enter. For @ key event, the keycode is 50. So you can use @keyup.50
.
For example:
<input @keyup.50="atPress()" />
Your error is caused by these:
Dim oTable As Table, oRow As Row,
These types, Table
and Row
are not variable types native to Excel. You can resolve this in one of two ways:
Dim oTable as Word.Table, oRow as Word.Row
. This is called early-binding. Object
type: Dim oTable as Object, oRow as Object
. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.I have not tested your code but I suspect ActiveDocument
won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:
Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long
Set wdApp = GetObject(,"Word.Application")
Application.ScreenUpdating = False
For Each oTable In wdApp.ActiveDocument.Tables
Scripts are loaded in the order you have defined them in the HTML.
Therefore if you first load:
<script type="text/javascript" src="./javascript.js"></script>
without loading jQuery first, then $ is not defined
.
You need to first load jQuery so that you can use it.
I would also recommend placing your scripts at the bottom of your HTML for performance reasons.
this work for me:-
String[] array = {"A", "B", "C"};
String abc = "";
Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
I am using a Fragment.
Ubuntu 18.04
Install and ensure mysqld us running..
Go into database and setup root user:
sudo mysql -u root
SELECT User,Host FROM mysql.user;
DROP USER 'root'@'localhost';
CREATE USER 'root'@'%' IDENTIFIED BY 'obamathelongleggedmacdaddy';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;
Edit mysqld permissions and restart:
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
# edit the line to be this:
bind-address=0.0.0.0
sudo systemctl stop mysql
sudo systemctl start mysql
From another machine, test.. Obvs port (3306) on mysqld machine must allow connection from test machine.
mysql -u root -p -h 123.456.789.666
All the additional "security" of MySql doesn't help security at all, it just complicates and obfuscates, it is now actually easier to screw it up than in the old days, where you just used a really long password.
Just try this:
<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
});
</script>
In script.php
<?php
echo "You win";
?>
Suppose if the list is a collection of objects like given below:
obj = [
{
"subjectId" : "577a54c09c57916109142248",
"evaluableMaterialCount" : 0,
"subjectName" : "ASP.net"
},
{
"subjectId" : "56645cd63c43a07b61c2c650",
"subjectName" : ".NET",
},
{
"subjectId" : "5656a2ec3c43a07b61c2bd83",
"subjectName" : "Python",
},
{
"subjectId" : "5662add93c43a07b61c2c58c",
"subjectName" : "HTML"
}
]
You can use the following method to find the index. Suppose the subjectId is 5662add93c43a07b61c2c58c then to get the index of the object in the list,
subjectId = "5662add93c43a07b61c2c58c"
for i, subjobj in enumerate(obj):
if(subjectId == subjobj['subjectId']):
print(i)
There are some good resources for ramping up on crypto. Here's one:
From that page:
In the most commonly used public-key cryptography system, invented by Ron Rivest, Adi Shamir, and Len Adleman in 1977, both the public and the private keys are derived from a pair of large prime numbers according to a relatively simple mathematical formula. In theory, it might be possible to derive the private key from the public key by working the formula backwards. But only the product of the large prime numbers is public, and factoring numbers of that size into primes is so hard that even the most powerful supercomputers in the world cant break an ordinary public key.
Bruce Schneier's book Applied Cryptography is another. I highly recommend that book; it's fun reading.
Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.
Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.
you can also change you can also change MinimumSize
No, you cannot set them all in a single statement.
At the general case, you need at least three properties:
border-color: red green white blue;
border-style: solid dashed dotted solid;
border-width: 1px 2px 3px 4px;
However, that would be quite messy. It would be more readable and maintainable with four:
border-top: 1px solid #ff0;
border-right: 2px dashed #f0F;
border-bottom: 3px dotted #f00;
border-left: 5px solid #09f;
Not sure what your desired output is, but if you're using list comprehension, the order follows the order of nested loops, which you have backwards. So I got the what I think you want with:
[float(y) for x in l for y in x]
The principle is: use the same order you'd use in writing it out as nested for loops.
This is my version referring @Virako 's code snippet
def adjust_column_width_from_col(ws, min_row, min_col, max_col):
column_widths = []
for i, col in \
enumerate(
ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
):
for cell in col:
value = cell.value
if value is not None:
if isinstance(value, str) is False:
value = str(value)
try:
column_widths[i] = max(column_widths[i], len(value))
except IndexError:
column_widths.append(len(value))
for i, width in enumerate(column_widths):
col_name = get_column_letter(min_col + i)
value = column_widths[i] + 2
ws.column_dimensions[col_name].width = value
And how to use is as follows,
adjust_column_width_from_col(ws, 1,1, ws.max_column)
actually a much easier way to get a readable array of what you (probably) want to see, is instead of using
dd($users);
or
dd(User::all());
use this
dd($users->toArray());
or
dd(User::all()->toArray());
which is a lot nicer to debug with.
EDIT - additional, this also works nicely in your views / templates so if you pass the get all users to your template, you can then dump it into your blade template
{{ dd($users->toArray()) }}
There are some great examples in here, but I couldn't get this to work in all cases when also dealing with multiple lines of text (text wrapping). To finally get it to work I combined a couple of the techniques:
I used Jesse Crossen example above. However, I fixed a text height issue and I added the ability to specify a horizontal text margin. The margin is useful when allowing text to wrap so it doesn't hit the edge of the button:
// the space between the image and text
CGFloat spacing = 10.0;
float textMargin = 6;
// get the size of the elements here for readability
CGSize imageSize = picImage.size;
CGSize titleSize = button.titleLabel.frame.size;
CGFloat totalHeight = (imageSize.height + titleSize.height + spacing); // get the height they will take up as a unit
// lower the text and push it left to center it
button.titleEdgeInsets = UIEdgeInsetsMake( 0.0, -imageSize.width +textMargin, - (totalHeight - titleSize.height), +textMargin ); // top, left, bottom, right
// the text width might have changed (in case it was shortened before due to
// lack of space and isn't anymore now), so we get the frame size again
titleSize = button.titleLabel.bounds.size;
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width ); // top, left, bottom, right
Make sure you setup the text label to wrap
button.titleLabel.numberOfLines = 2; button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; button.titleLabel.textAlignment = UITextAlignmentCenter;
This will mostly work now. However, I had some buttons that wouldn't render their image correctly. The image was either shifted to far to the right or left (it wasn't centered). So I used an UIButton layout override technique to force the imageView to be centered.
@interface CategoryButton : UIButton @end @implementation CategoryButton - (void)layoutSubviews { // Allow default layout, then center imageView [super layoutSubviews]; UIImageView *imageView = [self imageView]; CGRect imageFrame = imageView.frame; imageFrame.origin.x = (int)((self.frame.size.width - imageFrame.size.width)/ 2); imageView.frame = imageFrame; } @end
I am about 8 years late, well...anyways, I don't really know what then() does but maybe MDN might have an answer. Actually, I might actually understand it a little more.
This will show you all the information (hopefully), you need. Unless someone already posted this link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The format is promise.prototype.then() The promise and prototype are kind of like variables but not like variables in javascript, I mean like other things go there like navigator.getBattery().then() where this one actually exists but is barely used on the web, this one shows statuses about the battery of the device, more information and more on MDN if you are curious.
//Disable right click script via java script code
<script language=JavaScript>
//Disable right click script
var message = "";
///////////////////////////////////
function clickIE() {
if (document.all) {
(message);
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2 || e.which == 3) {
(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
</script>
In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K
and for move cursor to previous line: \33[1A
. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant)
:
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
There are codes for cursor navigation, clearing screen and so on.
I think there are some libraries which helps with it (ncurses
?).
The difference is that the value of a static readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.
Remember: For reference types, in both cases (static and instance), the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
For details, please refer to C# Frequently Asked Questions on this topic: http://blogs.msdn.com/csharpfaq/archive/2004/12/03/274791.aspx
Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":
txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
e.consume();
}
});
This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.
The solution that for me works is:
For Each xCell In Selection
xCell.Value = CDec(xCell.Value)
Next xCell
This is how I use it across domains...
I hope it helps :)
Since C++11 it can be done inside a class with constexpr
.
class stat {
public:
// init inside class
static constexpr double inlineStaticVar = 22;
};
The variable can now be accessed with:
stat::inlineStaticVar
SELECT table_name from all_tables where owner = 'YOURSCHEMA';
Just create another class and add along with the bootstrap container
class. You can also use container-fluid
though.
<div class="container full-width">
<div class="row">
....
</div>
</div>
The CSS part is pretty simple
* {
margin: 0;
padding: 0;
}
.full-width {
width: 100%;
min-width: 100%;
max-width: 100%;
}
Hope this helps, Thanks!
Just incase if anyone is looking for how to do it in typescript here is the solution
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
// Some action
}
And yes as mentioned by @Coops below, please do not forget to include
import { Watch } from 'vue-property-decorator';
Edit: Alcalyn made a very good point of using Route type instead of using any
import { Watch } from 'vue-property-decorator';
import { Route } from 'vue-router';
I think the first thing to do before all the other solutions is:
1. Check whether your device is online or not?
2. If you are running the application on the real device then the device should be on the same network where the development server is running.
More information at this page.
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener
callback function will not execute synchronously with your code (that is, before React.createClass
), but only after your entire snippet has run, and the response has been received from your remote location.
Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:
function reqListener(e) {
data = JSON.parse(this.responseText);
console.log(data);
}
I'm not seeing the use of data
in the React component, so I can only suggest this theoretically: why not update your component in the callback?
Class selectors are prefixed with a dot. Your .find()
is missing that so jQuery thinks you're looking for <myClass>
elements.
var myVar = $("#start").find('.myClass').val();
I fixed the problem by reinstalling the package with:
pip install --force-reinstall google-api-python-client
I had the same problem and found that there was no package.json in my project (but only the package-lock.json). I then
..and all worked out fine. Took a while to figure it out, but that did it for me.
I asked in the discussion:
does
ssh -T [email protected]
ouput the same username (in Hi [My Username]!
) as in the one used for the ssh url of your repo ([email protected]:username/repo.git
)?Sorry It not showing same name
That means somehow the credentials have changed.
One solution would be to at least copy %HOME%\.ssh\id_rsa.pub
in the SSH keys section of the right GitHub account
The OP adds:
I am working on private repo. So In [email protected]:username/repo.git,
I replied:
If you were able to clone/push to that repo whose username is not your own GitHub account, that must be because you had your previous public ssh key added as a contributor to that repo by the repo's owner.
What next is to ask that same repo owner to add your current public ssh key
%HOME%\.ssh\id_rsa.pub
to the repo contributor list.
So check with the owner that you (meaning your public ssh key) are declared as a contributor.
git diff path/file.css | grep -E "^\+" | grep -v '+++ b/' | cut -c 2-
grep -E "^\+"
is from previous accepted answer, it is incomplete because leaves non-source stuffgrep -v '+++ b'
removes non-source line with file name of later versioncut -c 2-
removes column of +
signs, also may use sed 's/^\+//'
comm
or sdiff
were not an option because of git.
If you have one project referencing another project (such as a 'Windows Application' type referencing a 'Class Library') and both have the same Assembly name, you'll get this error. You can either strongly name the referenced project or (even better) rename the assembly of the referencing project (under the 'Application' tab of project properties in VS).
Here are a few ways of removing a single '
from a string in python.
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Using list comprehension
''.join([c for c in string if c != "'"])
Using generator Expression
''.join(c for c in string if c != "'")
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
in java1.7+ You can use this code to get file`s create time !
private static LocalDateTime getCreateTime(File file) throws IOException {
Path path = Paths.get(file.getPath());
BasicFileAttributeView basicfile = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
BasicFileAttributes attr = basicfile.readAttributes();
long date = attr.creationTime().toMillis();
Instant instant = Instant.ofEpochMilli(date);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
Here I got the error:
Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
Because you didn't pass a base64-encoded string. Look at your functions: both download
and dataURItoBlob
do expect a data URI for some reason; you however are passing a plain html markup string to download
in your example.
Not only is HTML invalid as base64, you are calling .split(',')[1]
on it which will yield undefined
- and "undefined"
is not a valid base64-encoded string either.
I don't know, but I read that I need to encode my string to base64
That doesn't make much sense to me. You want to encode it somehow, only to decode it then?
What should I call and how?
Change the interface of your download
function back to where it received the filename
and text
arguments.
Notice that the BlobBuilder
does not only support appending whole strings (so you don't need to create those ArrayBuffer
things), but also is deprecated in favor of the Blob
constructor.
Can I put a name on my saved file?
Yes. Don't use the Blob
constructor, but the File
constructor.
function download(filename, text) {
try {
var file = new File([text], filename, {type:"text/plain"});
} catch(e) {
// when File constructor is not supported
file = new Blob([text], {type:"text/plain"});
}
var url = window.URL.createObjectURL(file);
…
}
download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");
See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
Another approach to remove the first line from file, using multiple assignment technique. Refer Link
$firstLine, $restOfDocument = Get-Content -Path $filename
$modifiedContent = $restOfDocument
$modifiedContent | Out-String | Set-Content $filename
it looks like datetime.now()
is being evaluated when the model is defined, and not each time you add a record.
Django has a feature to accomplish what you are trying to do already:
date = models.DateTimeField(auto_now_add=True, blank=True)
or
date = models.DateTimeField(default=datetime.now, blank=True)
The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now
without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now()
, then you are just evaluating the function and passing it the return value.
More information is available at Django's model field reference
Simlpy close and re-open the PR if you do not have the write access.
Have a look at: Greybox
It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.
You will find many information on how to use Greybox and also some great examples. Cheers Kara
For API 21+, Use Clip Views
Rounded outline clipping was added to the View
class in API 21. See this training doc or this reference for more info.
This in-built feature makes rounded corners very easy to implement. It works on any view or layout and supports proper clipping.
Here's What To Do:
android:background="@drawable/round_outline"
setClipToOutline(true)
The documentation used to say that you can set android:clipToOutline="true"
the XML, but this bug is now finally resolved and the documentation now correctly states that you can only do this in code.
What It Looks Like:
Special Note About ImageViews
setClipToOutline()
only works when the View's background is set to a shape drawable. If this background shape exists, View treats the background's outline as the borders for clipping and shadowing purposes.
This means that if you want to round the corners on an ImageView with setClipToOutline()
, your image must come from android:src
instead of android:background
(since background is used for the rounded shape). If you MUST use background to set your image instead of src, you can use this nested views workaround:
If no table with such name exists, DROP
fails with error while DROP IF EXISTS
just does nothing.
This is useful if you create/modifi your database with a script; this way you do not have to ensure manually that previous versions of the table are deleted. You just do a DROP IF EXISTS
and forget about it.
Of course, your current DB engine may not support this option, it is hard to tell more about the error with the information you provide.
var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
var cars = [
"volvo",
"saab",
"mercedes",
"audi"
];
var options_str = "";
cars.forEach( function(car) {
options_str += '<option value="' + car + '">' + car + '</option>';
});
sel.innerHTML = options_str;
window.onload = function() {
document.body.appendChild(sel);
};
For an extensive coverage review the contents of RFC2965. Of course that doesn't necessarily mean that all browsers behave exactly the same way.
However in general the rule for default Path if none specified in the cookie is the path in the URL from which the Set-Cookie header arrived. Similarly the default for the Domain is the full host name in the URL from which the Set-Cookie arrived.
Matching rules for the domain require the cookie Domain to match the host to which the request is being made. The cookie can specify a wider domain match by include *. in the domain attribute of Set-Cookie (this one area that browsers may vary). Matching the path (assuming the domain matches) is a simple matter that the requested path must be inside the path specified on the cookie. Typically session cookies are set with path=/ or path=/applicationName/ so the cookie is available to all requests into the application.
*
I'm unable to test this right now but I have an inkling that at least IE7/6 would treat the path example.com
as if it were .example.com
.
$path = "C:\DemoFolder"
$acl = Get-Acl $path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Attribs = $username, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AcessControl.FileSystemAccessRule($Attribs)
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
Get-ChildItem -Path "$path" -Recourse -Force | Set-Acl -aclObject $acl -Verbose
instead of using the ==
sign, more safer use the ===
sign when compare, the code that you post is work well
I update my Hibernate JPA to 2.1 and It works.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
Kinda late.But it just takes a bit of math.
.content {
margin-top: 50px;
background: #777;
padding: 30px;
padding-bottom: 0;
font-size: 11px;
border: 1px dotted #222;
}
.bottom-content {
background: #999;
width: 100%; /* you need this for it to work */
margin-left: -30px; /* will touch very left side */
padding-right: 60px; /* will touch very right side */
}
<div class='content'>
<p>A paragraph</p>
<p>Another paragraph.</p>
<p>No more content</p>
<div class='bottom-content'>
I want this div to ignore padding.
</div>
I don't have Windows so I didn't test this in IE.
fiddle: fiddle example..
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
To read you should create an instance of ifsteam and not ofstream.
ifstream iusrfile;
You should open the file in read mode.
iusrfile.open("usrfile.txt", ifstream::in);
Also this statement is not correct.
cout<<iusrfile;
If you are trying to print the data you read from the file you should do:
cout<<usr;
You can read more about ifstream and its API here
I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.
fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
A SurfaceView
is a custom view in Android that can be used to drawn inside it.
The main difference between a View
and a SurfaceView
is that a View is drawn in the
UI Thread
, which is used for all the user interaction.
If you want to update the UI rapidly enough and render a good amount of information in
it, a SurfaceView is a better choice.
But there are a few technical insides to the SurfaceView
:
1. They are not hardware accelerated.
2. Normal views are rendered when you call the methods invalidate
or postInvalidate()
, but this does not mean the view will be
immediately updated (A VSYNC
will be sent, and the OS decides when
it gets updated. The SurfaceView
can be immediately updated.
3. A SurfaceView has an allocated surface buffer
, so it is more costly
What worked for me was manually adding the path variable in my system.
I followed the instructions from Method 3 in this post:
https://appuals.com/fix-git-is-not-recognized-as-an-internal-or-external-command/
This GitPro page does summarize the consequence of a git submodule update nicely
When you run
git submodule update
, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.
Note March 2013:
As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
# or (with rebase)
git submodule update --rebase --remote
See "git submodule update --remote
vs git pull
".
MindTooth's answer illustrate a manual update (without local configuration):
git submodule -q foreach git pull -q origin master
In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.
The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).
To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.
Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:
So, to answer your questions:
can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?
You can create a branch and push modifications.
WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.
how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)
The page "Understanding Submodules" can help
Git submodules are implemented using two moving parts:
- the
.gitmodules
file and- a special kind of tree object.
These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.
From the git submodule page
you cannot modify the contents of the submodule from within the main project
100% correct: you cannot modify a submodule, only refer to one of its commits.
This is why, when you do modify a submodule from within the main project, you:
A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").
A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.
However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.
But the main idea remains: referencing specific components which:
The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)
If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.
Does that help understanding the true nature of Git Submodules?
// Create lag time before redirecting
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
$errors=null;
if ( ($name == "Name") ) {
$errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
$errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
$errors .= $spamError; // spam error
}
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
echo "Your message was successfully sent!";
//instead of echoing this message, I want a page redirect to thankyou.html
// redirect
setTimeout();
} else {
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
As of Android Studio 1.1, we've got official (experimental) support for writing Unit Tests (Roboelectric works as well).
Source: https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support
You probably want to use the 'onbeforeunload' event. It will allow you call a function in the parent window from the child immediately before the child window closes.
So probably something like this:
window.onbeforeunload = function (e) {
window.parent.functonToCallBeforeThisWindowCloses();
};
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
This answer builds on Zach Smith's answer by resetting the identity column as well:
Here is the query:
-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where
TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME != 'sysdiagrams'
AND TABLE_NAME != '__RefactorLog'
-- Optional
-- AND (TABLE_SCHEMA = 'dbo')
OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
/* Make sure these are the commands you want to execute before executing */
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
-- Reset identity counter if one exists
IF ((SELECT OBJECTPROPERTY( OBJECT_ID(@catalog + '.' + @schema + '.' + @tbl), 'TableHasIdentity')) = 1)
BEGIN
SET @sql = N'DBCC CHECKIDENT ([' + @catalog + '.' + @schema + '.' + @tbl + '], RESEED, 0)'
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
END
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
END
CLOSE i;
DEALLOCATE i;
-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
We can use contains
method to check if an item exists if we have provided the implementation of equals
and hashCode
else object reference will be used for equality comparison. Also in case of a list contains
is O(n)
operation where as it is O(1)
for HashSet
so better to use later. In Java 8 we can use streams also to check item based on its equality or based on a specific property.
CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true
String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true
I found the following article to be very helpful:
In my case, I had to set the following before Owin authentication would work instead of windows authentication:
<system.web>
<authentication mode="None" />
<system.web>
@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)
yourCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
}
});
}
Obviously you have to make your XML with the id of your checkbox :
<CheckBox
android:id="@+id/checkbox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your label"
/>
So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked()
it returns true
if the check box is checked.
Swift 5 - This works for me:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
selectedCell.contentView.backgroundColor = .red
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
cellToDeSelect.contentView.backgroundColor = .clear
}
I know it's not your specific problem, but I faced the same symptoms when I configured a static IP address in the network adapter settings and forgot to enter a "Default Gateway".
Leaving the field blank, the network icon shows an Internet connection, and I could ping internal servers but not external ones, so I assumed it was a DNS problem. NSLookup still worked, but of course, ping failed to find the server (again, seemed like a DNS issue.) Anyway, one more thing to check. =P
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
I am just doing this without even trying it. Would this work?
myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");
Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).
From the jQuery API Document
While JavaScript provides the
load
event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to.ready()
is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the
load
event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
You can also right click on the project -> Android Tools -> Fix Project Properties
. That should cause the R.java class to be re-generated.
Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.
In the Java context, we first need to make a distinction between "copying a value" and "copying an object".
int a = 1;
int b = a; // copying a value
int[] s = new int[]{42};
int[] t = s; // copying a value (the object reference for the array above)
StringBuffer sb = new StringBuffer("Hi mom");
// copying an object.
StringBuffer sb2 = new StringBuffer(sb);
In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new
, either explicitly or under the hood.
Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:
public class Example {
public int foo;
public int[] bar;
public Example() { };
public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}
Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ...
The normal interpretation is that a "shallow" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to the same array as in the original; e.g.
Example eg2 = new Example(eg1.foo, eg1.bar);
The normal interpretation of a "deep" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to a copy of the original array; e.g.
Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));
(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)
Two more questions / areas of uncertainty exist:
How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?
What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?
Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:
The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).
In fact, the specification does not even specifically state that clone produces a new object.
Here's what the javadoc says:
"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression
x.clone() != x
will be true, and that the expressionx.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case thatx.clone().equals(x)
will be true, this is not an absolute requirement."
Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.
In short, clone potentially means something different for every Java class.
Some people argue (as @supercat does in comments) that the Java clone()
method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.
You can try something like process.argv
, that is if you are using node.js
to run the program.
console.log(process.argv)
=> Would print an array containing
[
'/usr/bin/node',
'/home/user/path/filename.js',
'your_input'
]
You get the user provided input via array index, i.e., console.log(process.argv[3])
This should provide you with the input which you can store.
Example:
var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two
console.log(somevariable);
console.log(somevariable2);
If you are building a command-line program then the npm package yargs would be really helpful.
You can also use the following to include the TIME portion in your query:
SELECT EMP_NAME
, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011 00:00:00', 'dd/mon/yyyy HH24:MI:SS');
You can use splice
to remove objects or values from an array.
Let's consider an array of length 5
, with values 10
,20
,30
,40
,50
, and I want to remove the value 30
from it.
var array = [10,20,30,40,50];_x000D_
if (array.indexOf(30) > -1) {_x000D_
array.splice(array.indexOf(30), 1);_x000D_
}_x000D_
console.log(array); // [10,20,40,50]
_x000D_
You can try this Circle Progress library
NB: please always use same width and height for progress views
DonutProgress:
<com.github.lzyzsd.circleprogress.DonutProgress
android:id="@+id/donut_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
CircleProgress:
<com.github.lzyzsd.circleprogress.CircleProgress
android:id="@+id/circle_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
ArcProgress:
<com.github.lzyzsd.circleprogress.ArcProgress
android:id="@+id/arc_progress"
android:background="#214193"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:arc_progress="55"
custom:arc_bottom_text="MEMORY"/>
The new official AWS CLI natively supports most of the functionality of s3cmd
. I'd previously been using s3cmd
or the ruby AWS SDK to do things like this, but the official CLI works great for this.
http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html
aws s3 sync s3://oldbucket s3://newbucket
Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/
See the docs about querying.
It would be:
$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
I always liked going after it directly:
SELECT
DB_NAME( dbid ) AS DatabaseName,
CAST( ( SUM( size ) * 8 ) / ( 1024.0 * 1024.0 ) AS decimal( 10, 2 ) ) AS DbSizeGb
FROM
sys.sysaltfiles
GROUP BY
DB_NAME( dbid )
I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).
I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.
Maybe the problem is not in the format
but in the JavaScript
implementation of the play/ pause
methods. May I suggest visiting the following link where Google developer explains it in a good way?
Additionally, you could choose to use the newer webp
format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.
On that note: I've created a small script
that easily converts all standard formats to webp
. You can easily configure it to fit your needs. Here's the Github repo of the same projects.
Use GroupBy.sum
:
df.groupby(['Fruit','Name']).sum()
Out[31]:
Number
Fruit Name
Apples Bob 16
Mike 9
Steve 10
Grapes Bob 35
Tom 87
Tony 15
Oranges Bob 67
Mike 57
Tom 15
Tony 1
From effective java book
.
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly doubling the capacity
* each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
Can you spot the memory leak? So where is the memory leak? If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again. In this case, any references outside of the “active portion” of the element array are obsolete. The active portion consists of the elements whose index is less than size.
You can do that just using CSS.
You'll need to place another tag inside the <a>
and then you can change the CSS background-image
attribute on a:hover
.
i.e.
HTML:
<a href="#" id="name">
<span> </span>
</a>
CSS:
a#name span{
background-image:url(image/path);
}
a#name:hover span{
background-image:url(another/image/path);
}