If you want color animation like this,
this code will help you:
ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
anim.setDuration(2000);
float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
hsv[0] = 360 * animation.getAnimatedFraction();
runColor = Color.HSVToColor(hsv);
yourView.setBackgroundColor(runColor);
}
});
anim.setRepeatCount(Animation.INFINITE);
anim.start();
There was an issue with a build of Google Chrome Dev build 24.0.1312.5 that caused the preview panel to no longer display a json object tree but rather flat text. It should be fixed in the next dev
See more here: http://code.google.com/p/chromium/issues/detail?id=160733
In case if you use new swift version.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ChannelMoreSegue" {
}
}
Q. When is the "with grant option" required ?
A. when you have a view executed from a third schema.
Example: schema DSDSW has a view called view_name
a) that view selects from a table in another schema (FDR.balance)
b) a third shema X_WORK tries to select from that view
Typical grants: grant select on dsdw.view_name to dsdw_select_role; grant dsdw_select_role to fdr;
But: fdr gets select count(*) from dsdw.view_name; ERROR at line 1: ORA-01031: insufficient privileges
issue the grant:
grant select on fdr.balance to dsdw with grant option;
now fdr: select count(*) from dsdw.view_name; 5 rows
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev
command. View definitions will show in your configured editor.
julian@assange=# \ev {your_view_names}
Bonus. Some useful command to interact with query buffer.
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
I'm amazed by everyone else's MUCH more complicated answers.
You can very simply define the alpha in the color definition of the button (or any other view) in your xml:
android:color="#66FF0000" // Partially transparent red
In the above example, the color would be a partially transparent red.
When defining the color of a view, the format can be either #RRGGBB
or #AARRGGBB
, where AA
is the hex alpha value. FF
would be fully opaque and 00
would be full transparent.
If you need to dynamically alter the opacity in your code, use
myButton.getBackground().setAlpha(128); // 50% transparent
Where the INT ranges from 0
(fully transparent) to 255
(fully opaque).
This is my way to achieve that.
First of all add Root_fragment
inside viewPager
tab in which you want to implement button click fragment
event. Example;
@Override
public Fragment getItem(int position) {
if(position==0)
return RootTabFragment.newInstance();
else
return SecondPagerFragment.newInstance();
}
First of all, RootTabFragment
should be include FragmentLayout
for fragment change.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Then, inside RootTabFragment
onCreateView
, implement fragmentChange
for your FirstPagerFragment
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, FirstPagerFragment.newInstance()).commit();
After that, implement onClick
event for your button inside FirstPagerFragment
and make fragment change like that again.
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, NextFragment.newInstance()).commit();
Hope this will help you guy.
Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.
use Procedure
Create proc MyView as begin SELECT TOP 99999999999999 Column1, Column2 FROM dbo.Table Order by Column1 end
execute procedure
exec MyView
A more cleaner and dynamic way without hardcoding any pixel values in the code.
I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.
and solved it this way :
// get the yoffset of the position where your View has to be placed
final int yoffset = < calculate the position of the view >
// position using top margin
if(myView.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
}
However you have to make sure the parent layout of myView
is an instance of RelativeLayout
.
more complete code :
// identify the button
final Button clickedButton = <... code to find the button here ...>
// inflate the dialog - the following style preserves xml layout params
final View floatingDialog =
this.getLayoutInflater().inflate(R.layout.floating_dialog,
this.floatingDialogContainer, false);
this.floatingDialogContainer.addView(floatingDialog);
// get the buttons position
final int[] buttonPos = new int[2];
clickedButton.getLocationOnScreen(buttonPos);
final int yOffset = buttonPos[1] + clickedButton.getHeight();
// position using top margin
if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
}
This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
I create 2 different methods to remove subview. And it's much easier to use if we put them in extension
extension UIView {
/// Remove all subview
func removeAllSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
/// Remove all subview with specific type
func removeAllSubviews<T: UIView>(type: T.Type) {
subviews
.filter { $0.isMember(of: type) }
.forEach { $0.removeFromSuperview() }
}
}
You can use the lower
function:
Guide.where("lower(title)='attack'")
As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>
tag
<%= stylesheet_link_tag controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
Also, to specify the same class CSS on a different controller
Add this line in the body
of application.html.erb
<body class="<%= controller.controller_name %>-<%= controller.action_name %>">
So, now for example I would like to change the p
tag in 'home' controller and 'index' action.
Inside index.scss
file adds.
.nameOfController-nameOfAction <tag> { }
.home-index p {
color:red !important;
}
The code on Scene delegate in Swift UI
Content view background-color
window.rootViewController?.view.backgroundColor = .lightGray
This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)
public void verifyDrawable (View view, int drawable){
int sdk = Build.VERSION.SDK_INT;
if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(
ContextCompat.getDrawable(getContext(),drawable));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(getResources().getDrawable(drawable));
}
}
Different ways to handle button event
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Button 1",
Toast.LENGTH_LONG).show();
}
});
[Check this article for more details about button event handlers]
See the LayoutInflater
class.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);
They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.
The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.
They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.
In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.
Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.
Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.
Use the LayoutInflater as I shown below.
public View myView() {
View v; // Creating an instance for View Object
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.myview, null);
TextView text1 = v.findViewById(R.id.dolphinTitle);
Button btn1 = v.findViewById(R.id.dolphinMinusButton);
TextView text2 = v.findViewById(R.id.dolphinValue);
Button btn2 = v.findViewById(R.id.dolphinPlusButton);
return v;
}
Table:
Table stores the data in database and contains the data.
View:
View is an imaginary table, contains only the fields(columns) and does not contain data(row) which will be framed at run time Views created from one or more than one table by joins, with selected columns. Views are created to hide some columns from the user for security reasons, and to hide information exist in the column. Views reduces the effort for writing queries to access specific columns every time Instead of hitting the complex query to database every time, we can use view
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
There is no way to set maxHeight. But you can set the Height.
To do that you will need to discovery the height of each item of you scrollView. After that just set your scrollView height to numberOfItens * heightOfItem.
To discovery the height of an item do that:
View item = adapter.getView(0, null, scrollView);
item.measure(0, 0);
int heightOfItem = item.getMeasuredHeight();
To set the height do that:
// if the scrollView already has a layoutParams:
scrollView.getLayoutParams().height = heightOfItem * numberOfItens;
// or
// if the layoutParams is null, then create a new one.
scrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, heightOfItem * numberOfItens));
you can set the height and width of a view in a relative layout like this
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);
You can simply use EditorTemplates to do that, you need to create a directory named "EditorTemplates" in your controller's view folder and place a seperate view for each of your nested entities (named as entity class name)
Main view :
@model ViewModels.MyViewModels.Theme
@Html.LabelFor(Model.Theme.name)
@Html.EditorFor(Model.Theme.Categories)
Category view (/MyController/EditorTemplates/Category.cshtml) :
@model ViewModels.MyViewModels.Category
@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Products)
Product view (/MyController/EditorTemplates/Product.cshtml) :
@model ViewModels.MyViewModels.Product
@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Orders)
and so on
this way Html.EditorFor helper will generate element's names in an ordered manner and therefore you won't have any further problem for retrieving the posted Theme entity as a whole
Create a xml file under your drawable folder with following code. (The name of the file I created is rounded_corner.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#a9c5ac" >
</solid>
<!-- view border color and width -->
<stroke
android:width="3dp"
android:color="#1c1b20" >
</stroke>
<!-- If you want to add some padding -->
<padding
android:left="4dp"
android:top="4dp"
android:right="4dp"
android:bottom="4dp" >
</padding>
<!-- Here is the corner radius -->
<corners
android:radius="10dp" >
</corners>
</shape>
And keep this drawable
as background
for the view to which you want to keep rounded corner border. Let’s keep it for a LinearLayout
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_corner"
android:layout_centerInParent="true">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hi, This layout has rounded corner borders ..."
android:gravity="center"
android:padding="5dp"/>
</LinearLayout>
actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
Inside our activity we can get the root
view with:
ViewGroup rootView = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
or
View rootView = getWindow().getDecorView().getRootView();
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
IN SQL Server ,
declare @ViewName nvarchar(20)='ViewNameExample'
if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
begin
-- Your SQL Code goes here ...
end
Try using toDegrees="359"
since 360° and 0° are the same.
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if pArray
is the array, type pArray,10
in the watch window.
Oh there are many differences you will need to consider
Views for selection:
Views for insertion/updates:
Drawbacks
Padding means space between widget and widget original frame. But the margin is space between widget's original frame to boundaries other widget's frame..
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
it work in my case, oldSensor and newSnsor - oldView and newView:
private void replaceSensors(View oldSensor, View newSensor) {
ViewGroup parent = (ViewGroup) oldSensor.getParent();
if (parent == null) {
return;
}
int indexOldSensor = parent.indexOfChild(oldSensor);
int indexNewSensor = parent.indexOfChild(newSensor);
parent.removeView(oldSensor);
parent.addView(oldSensor, indexNewSensor);
parent.removeView(newSensor);
parent.addView(newSensor, indexOldSensor);
}
A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.
A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.
The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.
The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.
You could create an animation and apply it to your button view. For example:
// Locate view
ImageView diskView = (ImageView) findViewById(R.id.imageView3);
// Create an animation instance
Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);
// Set the animation's parameters
an.setDuration(10000); // duration in ms
an.setRepeatCount(0); // -1 = infinite repeated
an.setRepeatMode(Animation.REVERSE); // reverses each repeat
an.setFillAfter(true); // keep rotation after animation
// Aply animation to image view
diskView.setAnimation(an);
In SQL SERVER you do it like this:
SELECT *
INTO A
FROM dbo.myView
This will create a new table A
with the contents of your view.
See here for more info.
I understand your frustration the " Graphics view widget" is not the best way to do this, yes it can be done, but it's almost exactly the same as using a label ( for what you want any way) now all the ways listed do work but...
For you and any one else that may come across this question he easiest way to do it ( what you're asking any way ) is this.
QPixmap pix("Path\\path\\entername.jpeg");
ui->label->setPixmap(pix);
}
In order to refresh a table layout (TableLayout) I ended up having to use the recursive approach mentioned above to get all the children's children and so forth.
My situation was somewhat simplified because I only needed to work with LinearLayout and those classes extended from it such as TableLayout. And I was only interested in finding TextView children. But I think it's still applicable to this question.
The final class runs as a separate thread, which means it can do other things in the background before parsing for the children. The code is small and simple and can be found at github: https://github.com/jkincali/Android-LinearLayout-Parser
Let's say you generate a bunch of views that are similar. You could set an OnClickListener
for each view individually:
button1.setOnClickListener(new OnClickListener ... );
button2.setOnClickListener(new OnClickListener ... );
...
Then you have to create a unique onClick
method for each view even if they do the similar things, like:
public void onClick(View v) {
doAction(1); // 1 for button1, 2 for button2, etc.
}
This is because onClick
has only one parameter, a View
, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.
Enter getTag
/setTag
:
button1.setTag(1);
button2.setTag(2);
Now we can use the same OnClickListener for every button:
listener = new OnClickListener() {
@Override
public void onClick(View v) {
doAction(v.getTag());
}
};
It's basically a way for views to have memories.
Never ever use getApplicationContext() with views.
It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.
Simply use RelativeLayout
or FrameLayout
. The last child view will overlay everything else.
Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.
Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.
Example (second EditText will completely cover the first one):
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root_view">
<EditText
android:layout_width="fill_parent"
android:id="@+id/editText1"
android:layout_height="fill_parent">
</EditText>
<EditText
android:layout_width="fill_parent"
android:id="@+id/editText2"
android:layout_height="fill_parent">
<requestFocus></requestFocus>
</EditText>
</FrameLayout>
FrameLayout
is some kind of view stack. Made for special cases.
RelativeLayout
is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc
Update based on comment
Usually you set the content with setContentView(R.layout.your_layout)
in onCreate
(it will inflate the layout for you). You can do that manually and call setContentView(inflatedView)
, there's no difference.
The view itself might be a single view (like TextView
) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).
After calling setContentView
your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view)
to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)
).
Try this in your constructor
MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('your View Name');
In Management Studio, open the Object Explorer.
Views
Script view as > Create To > New query window
and you're done!
If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:
SELECT
m.definition
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'
Check my answer here
The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
You could use the android.text.StaticLayout
class to specify the bounds required and then call getHeight()
. You can draw the text (contained in the layout) by calling its draw(Canvas)
method.
Due to variation in device screen pixel densities its good to always use DIP
unit to set margin programmatically. Like below_
//get resources
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
//get layout params...
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.setMargins(Math.round(pxLeftMargin), Math.round(pxTopMargin), Math.round(pxRightMargin), Math.round(pxBottomMargin));
//set margin...
yourLayoutTOsetMargin.setLayoutParams(params);
Hope this will help.
Include in your manifest file under activity which you want to display .But make sure not using Full screen Activity
android:windowSoftInputMode="adjustPan"
you can put the input inside a form like this:-
<script>
$(document).ready(function(){
$(document).on('click','#send', function(){
$('#hid').val(data)
document.forms["myForm"].submit();
})
})
</script>
<form id="myForm" action="/request_page url/" method="post">
<input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>
You can use:
try:
# get your models
except ObjectDoesNotExist:
# do something
How about something like this, comments should explain:
--DJ - 2015-07-15 Example for view CREATE or REPLACE
--Replace with schema and view names
DECLARE @viewName NVARCHAR(30)= 'T';
DECLARE @schemaName NVARCHAR(30)= 'dbo';
--Leave this section as-is
BEGIN TRY
DECLARE @view AS NVARCHAR(100) = '
CREATE VIEW ' + @schemaName + '.' + @viewName + ' AS SELECT '''' AS [1]';
EXEC sp_executesql
@view;
END TRY
BEGIN CATCH
PRINT 'View already exists';
END CATCH;
GO
--Put full select statement here after modifying the view & schema name appropriately
ALTER VIEW [dbo].[T]
AS
SELECT '' AS [2];
GO
--Verify results with select statement against the view
SELECT *
FROM [T];
Cheers -DJ
This works well for me :
targetView.getParent().requestChildFocus(targetView,targetView);
public void RequestChildFocus (View child, View focused)
child - The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus.
focused - The view that is a descendant of child that actually has focus
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
Yes, you can dynamically set the position of the view in Android. Likewise, you have an ImageView
in LinearLayout
of your XML file. So you can set its position through LayoutParams
.But make sure to take LayoutParams
according to the layout taken in your XML file. There are different LayoutParams
according to the layout taken.
Here is the code to set:
LayoutParams layoutParams=new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
Found in one of the Chrome sample applications, although this is meant for larger blocks of data where you're okay with an asynchronous conversion.
/**
* Converts an array buffer to a string
*
* @private
* @param {ArrayBuffer} buf The buffer to convert
* @param {Function} callback The function to call when conversion is complete
*/
function _arrayBufferToString(buf, callback) {
var bb = new Blob([new Uint8Array(buf)]);
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result);
};
f.readAsText(bb);
}
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
Whether you should use a join is first and foremost about whether a join makes sense. Only at that point is performance even something to be considered, as nearly all other cases will result in significantly worse performance.
Performance differences will largely be tied to how related the info you're querying for is. Joins work, and they're fast when the data is related and you index stuff correctly, but they do often result in some redundancy and sometimes more results than needed. And if your data sets are not directly related, sticking them in a single query will result in what's called a Cartesian product (basically, all possible combinations of rows), which is almost never what you want.
This is often caused by many-to-one-to-many relationships. For example, HoldOffHunger's answer mentioned a single query for posts, tags, and comments. Comments are related to a post, as are tags...but tags are unrelated to comments.
+------------+ +---------+ +---------+
| comment | | post | | tag |
|------------|* 1|---------|1 *|---------|
| post_id |-----| post_id |-----| post_id |
| comment_id | | ... | | tag_id |
| user_id | | | | ... |
| ... | | | | ... |
+------------+ +---------+ +---------+
In this case, it is unambiguously better for this to be at least two separate queries. If you try to join tags and comments, because there's no direct relation between the two, you end up with every possible combination of tag and comment. many * many == manymany
. Aside from that, since posts and tags are unrelated, you can do those two queries in parallel, leading to potential gain.
Let's consider a different scenario, though: You want the comments attached to a post, and the commenters' contact info.
+----------+ +------------+ +---------+
| user | | comment | | post |
|----------|1 *|------------|* 1|---------|
| user_id |-----| post_id |-----| post_id |
| username | | user_id | | ... |
| ... | | ... | +---------+
+----------+ +------------+
This is where you should consider a join. Aside from being a much more natural query, most database systems (including MySQL) have lots of smart people put lots of hard work into optimizing queries just like it. For separate queries, since each query depends on the results of the previous one, the queries can't be done in parallel, and the total time becomes not just the actual execute time of the queries, but also the time spent fetching results, sifting through them for IDs for the next query, linking rows together, etc.
In my case, the problem was caused by some Response.Write commands at Master Page of the website (code behind). They were there only for debugging purposes (that's not the best way, I know)...
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC
The type
for a function is FN
rather than P
for procedure. Or you can filter on the name column.
I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.
Template:
<select class="randomClass" id="randomId" (change) =
"filterSelected($event.target.value)">
<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}}
</option>
</select>
Component:
public filterTypes = [{
value : 'New', display : 'Open'
},
{
value : 'Closed', display : 'Closed'
}]
filterSelected(selectedValue:string){
console.log('selected value= '+selectedValue)
}
In my case, I was using Google's Roboto font. So I had to import it at the beginning of my page with its proper weights.
<link href = "https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto+Slab|Roboto:300,400,500,700" rel = "stylesheet" />
First, try omitting the quotes from 12 and 24. Worth a shot.
Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:
<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>
Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .
I faced the same issue, but the one which works for me best is below:
public DateTime CreatedOn { get; set; } = DateTime.Now;
When I had this error in a MS Access database I used the /decompile command line switch along with the Compact/Repair option. Worked for me. I had removed a reference that I was sure my code no longer used and started getting this error.
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time
DetailsThe Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
.
The Month
class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I don't know of an existing function in the Java API that does this (which is not to say it doesn't exist), but here's my own implementation (one or more delimiters will be returned as a single token; if you want each delimiter to be returned as a separate token, it will need a bit of adaptation):
static String[] splitWithDelimiters(String s) {
if (s == null || s.length() == 0) {
return new String[0];
}
LinkedList<String> result = new LinkedList<String>();
StringBuilder sb = null;
boolean wasLetterOrDigit = !Character.isLetterOrDigit(s.charAt(0));
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c) ^ wasLetterOrDigit) {
if (sb != null) {
result.add(sb.toString());
}
sb = new StringBuilder();
wasLetterOrDigit = !wasLetterOrDigit;
}
sb.append(c);
}
result.add(sb.toString());
return result.toArray(new String[0]);
}
As soon as python requests
will be merged with SOCKS5
pull request it will do as simple as using proxies
dictionary:
#proxy
# SOCKS5 proxy for HTTP/HTTPS
proxies = {
'http' : "socks5://myproxy:9191",
'https' : "socks5://myproxy:9191"
}
#headers
headers = {
}
url='http://icanhazip.com/'
res = requests.get(url, headers=headers, proxies=proxies)
Another options, in case that you cannot wait request
to be ready, when you cannot use requesocks
- like on GoogleAppEngine due to the lack of pwd
built-in module, is to use PySocks that was mentioned above:
socks.py
file from the repo and put a copy in your root folder;import socks
and import socket
At this point configure and bind the socket before using with urllib2
- in the following example:
import urllib2
import socket
import socks
socks.set_default_proxy(socks.SOCKS5, "myprivateproxy.net",port=9050)
socket.socket = socks.socksocket
res=urllib2.urlopen(url).read()
the solution what I found to work in my case
$('#multiselect1').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
maxHeight: '300',
buttonWidth: '235',
onChange: function(element, checked) {
var brands = $('#multiselect1 option:selected');
var selected = [];
$(brands).each(function(index, brand){
selected.push([$(this).val()]);
});
console.log(selected);
}
});
If you're using Laravel 5, the command would be;
php artisan make:migration add_paid_to_users
All of the commands for making things (controllers, models, migrations etc) have been moved under the make:
command.
php artisan migrate
is still the same though.
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?
You could check in the following way (extra = and making length a truthy evaluation)
if (typeof(sub.from) !== 'undefined' && sub.from.length) {
[update]
I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:
for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
mainid = sub.from[i]['id'];
var sub = afcHelper_Submissions[mainid]; // <== re setting sub
My guess is that the error is not on the if statement but on the for(i...
statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).
You can skip the var declaration and the stringify. Otherwise, that will work just fine.
$.ajax({
url: '/home/check',
type: 'POST',
data: {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
},
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
Try a custom propTypes :
const childrenPropTypeLogic = (props, propName, componentName) => {
const prop = props[propName];
return React.Children
.toArray(prop)
.find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
};
static propTypes = {
children : childrenPropTypeLogic
}
const {Component, PropTypes} = React;_x000D_
_x000D_
const childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
var error;_x000D_
var prop = props[propName];_x000D_
_x000D_
React.Children.forEach(prop, function (child) {_x000D_
if (child.type !== 'div') {_x000D_
error = new Error(_x000D_
'`' + componentName + '` only accepts children of type `div`.'_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
return error;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
static propTypes = {_x000D_
children: childrenPropTypeLogic,_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
{this.props.children}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
render(){_x000D_
return (_x000D_
<ContainerComponent>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
</ContainerComponent>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
No one mentioned Raw Post Data, but it's good to know, if posted data has no key, but only value, use Raw Post Data:
$postdata = file_get_contents("php://input");
PHP Man:
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
While @pritam kumar gives a good overview the 5th point is not true.
Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions.
https://blogs.oracle.com/carolmcdonald/entry/jpa_caching
JPA's EntityManager and Hibernate's Session offer an extended Persistence Context.
You can also do this by service name.
First, try to find the service name of the respective pod which corresponds to multiple pods of the same service. kubectl get svc
.
Next, run the following command to display logs from each container.
kubectl logs -f service/<service-name>
From the docs:
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.
If no block is given, an enumerator is returned instead.
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35
This worked for me:
clients.detect{|client| client.last['client_id'] == '2180' } #=> ["orange", {"client_id"=>"2180"}]
clients.detect{|client| client.last['client_id'] == '999999' } #=> nil
See: http://rubydoc.info/stdlib/core/1.9.2/Enumerable#find-instance_method
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.
one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.
as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.
as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):
/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_
/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */
namespace NamespaceName {
/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
/* private types */
class t_thing {
/*...*/
};
public:
/* public types */
typedef uint64_t t_nanosecond;
/* factory initializers -- UpperCamel */
t_nanotimer* WithFloat(const float& arg);
/* public/protected class interface -- UpperCamel */
static float Uptime();
protected:
/* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
static const t_spoke Spoke;
public:
/* enums in interface are labeled as static class data */
enum { Granularity = 4 };
public:
/* construction/destruction -- always use proper initialization list */
explicit t_nanotimer(t_init);
explicit t_nanotimer(const float& arg);
virtual ~t_nanotimer();
/*
public and protected instance methods -- lowercaseCamel()
- booleans prefer is/has
- accessors use the form: getVariable() setVariable().
const-correctness is important
*/
const void* address() const;
virtual uint64_t hashCode() const;
protected:
/* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
virtual bool hasExpired() const;
private:
/* private methods and private static data */
void invalidate();
private:
/*
instance variables
- i tend to use underscore suffix, but d_ (for example) is another good alternative
- note redundancy in visibility
*/
t_thing ivar_;
private:
/* prohibited stuff */
explicit t_nanotimer();
explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */
I got this error with GitHub gist. I was trying to push a commit with files in sub-directories. Turned out gist can only have files in root directory.
All of these answers, as of January 2016, are unnecessary. In Interface Builder, set the View Semantic to Force Right-to-Left
, or if you prefer programmatic way, semanticContentAttribute = .forceRightToLeft
That will cause the image to appear on the right of your text.
There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.
Just overwrite style, but you don't have to parse anything, why would you?
// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
// Remove previously defined property
if (element.style.setProperty)
element.style.setProperty(property, '');
else
element.style.setAttribute(property, '');
// Insert the new style with all the old rules
element.setAttribute('style', element.style.cssText +
property + ':' + value + ((important) ? ' !important' : '') + ';');
}
Can't use removeProperty()
, because it won't remove !important
rules in Chrome.
Can't use element.style[property] = ''
, because it only accepts camelCase in Firefox.
You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.
foreach ($array as $key => $val) {
echo $val;
}
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
To disable all access to sub dirs (safest) use:
<Directory full-path-to/USERS>
Order Deny,Allow
Deny from All
</Directory>
If you want to block only PHP files from being served directly, then do:
1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:
# Example of existing recognized extenstions:
AddType application/x-httpd-php .php .phtml .php3
2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)
<Directory full-path-to/USERS>
<FilesMatch "(?i)\.(php|php3?|phtml)$">
Order Deny,Allow
Deny from All
</FilesMatch>
</Directory>
Or use Location to match php files (I prefer the above files approach)
<LocationMatch "/USERS/.*(?i)\.(php3?|phtml)$">
Order Deny,Allow
Deny from All
</LocationMatch>
return 0
When a C or C++ program reaches the end of main
the compiler will automatically generate code to return 0, so there is no need to put return 0;
explicitly at the end of main
.
Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments: "I didn't know that." or "That's bad advice!" My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:
[...] a return from the initial call to the
main
function is equivalent to calling theexit
function with the value returned by themain
function as its argument; reaching the}
that terminates themain
function returns a value of 0.
For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:
If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit return;
statements at the end of a void
function. Reasons against omitting seem to boil down to "it looks weird". If, like me, you're curious about the rationale for the change to the C standard read this question. Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.
Additionally, the C++ Core Guidelines contains multiple instances of omitting return 0;
at the end of main
and no instances in which an explicit return is written. Although there is not yet a specific guideline on this particular topic in that document, that seems at least a tacit endorsement of the practice.
So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.
For my this is best solution.
function strip_tags_content($string) {
// ----- remove HTML TAGs -----
$string = preg_replace ('/<[^>]*>/', ' ', $string);
// ----- remove control characters -----
$string = str_replace("\r", '', $string);
$string = str_replace("\n", ' ', $string);
$string = str_replace("\t", ' ', $string);
// ----- remove multiple spaces -----
$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;
}
If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:
String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e
The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc
sample.codePointCount(0, sample.length()) // returns 5
http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/
We pull in content frequently from our CMS as [innerHTML]="content.title"
. We place the necessary classes in the application's root styles.scss
file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}}
in the template will not render html from the content.
ROWID is a hidden column on Oracle tables, so, for SQL Server, build your own. Add a column called ROWID with a default value of NEWID()
.
How to do that: Add column, with default value, to existing table in SQL Server
Add $("#id").select2()
out of document.ready()
function.
Another option is using command line:
code -d left.txt right.txt
Note: You may need to add code
to your path first. See: How to call VS Code Editor from command line
Well in my case the following work fine
<div class="card-body p-2">
<div class="d-flex flex-row justify-content-center">
<div style="margin: auto;">
<input type="text" autocomplete="off"
style="max-width:150px!important; "
class="form-control form-control-sm font-weight-bold align-self-center w-25" id="dtTechState">
</div>
</div>
</div>
Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do
s = 'ABCDEFG'
for pos in 0...s.length
puts s[pos].chr
end
The .chr
is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.
No, you're creating an array, but there's a big difference:
char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!
The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:
char string[] = "Some string";
creates the same, read only, constant string, and copies it to the stack array. That's why:
string[1] = 'v';
Is valid in the latter case.
If you write:
char string[] = {"some", " string"};
the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:
char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};
Where the last version gives you an array of strings (arrays of chars) that you actually can edit...
You can directly access BODY.values
:
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
BODY.values.push(item1);
}
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
Try like below
select
split.field(column_name,1,',','"') name1,
split.field(column_name,2,',','"') name2
from table_name
Go to the download page and download the Windows x86
version with filename jdk-7-windows-i586.exe
.
Okay, so you want to calculate a^b mod m
. First we'll take a naive approach and then see how we can refine it.
First, reduce a mod m
. That means, find a number a1
so that 0 <= a1 < m
and a = a1 mod m
. Then repeatedly in a loop multiply by a1
and reduce again mod m
. Thus, in pseudocode:
a1 = a reduced mod m
p = 1
for(int i = 1; i <= b; i++) {
p *= a1
p = p reduced mod m
}
By doing this, we avoid numbers larger than m^2
. This is the key. The reason we avoid numbers larger than m^2
is because at every step 0 <= p < m
and 0 <= a1 < m
.
As an example, let's compute 5^55 mod 221
. First, 5
is already reduced mod 221
.
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
Therefore, 5^55 = 112 mod 221
.
Now, we can improve this by using exponentiation by squaring; this is the famous trick wherein we reduce exponentiation to requiring only log b
multiplications instead of b
. Note that with the algorithm that I described above, the exponentiation by squaring improvement, you end up with the right-to-left binary method.
a1 = a reduced mod m
p = 1
while (b > 0) {
if (b is odd) {
p *= a1
p = p reduced mod m
}
b /= 2
a1 = (a1 * a1) reduced mod m
}
Thus, since 55 = 110111 in binary
1 * (5^1 mod 221) = 5 mod 221
5 * (5^2 mod 221) = 125 mod 221
125 * (5^4 mod 221) = 112 mod 221
112 * (5^16 mod 221) = 112 mod 221
112 * (5^32 mod 221) = 112 mod 221
Therefore the answer is 5^55 = 112 mod 221
. The reason this works is because
55 = 1 + 2 + 4 + 16 + 32
so that
5^55 = 5^(1 + 2 + 4 + 16 + 32) mod 221
= 5^1 * 5^2 * 5^4 * 5^16 * 5^32 mod 221
= 5 * 25 * 183 * 1 * 1 mod 221
= 22875 mod 221
= 112 mod 221
In the step where we calculate 5^1 mod 221
, 5^2 mod 221
, etc. we note that 5^(2^k)
= 5^(2^(k-1)) * 5^(2^(k-1))
because 2^k = 2^(k-1) + 2^(k-1)
so that we can first compute 5^1
and reduce mod 221
, then square this and reduce mod 221
to obtain 5^2 mod 221
, etc.
The above algorithm formalizes this idea.
If you set the the index than the dictionary will result in unique key value pairs
encoder=LabelEncoder()
df['airline_enc']=encoder.fit_transform(df['airline'])
dictAirline= df[['airline_enc','airline']].set_index('airline_enc').to_dict()
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
If you have inserted a row into table 1 before creating the foreign key in table 2, then you will get a foreign key constraint error, because the auto increment value is 2 in table 1 and 1 in table 2. To solve this you have to truncate table 1 and set the auto increment value back to 1. Then you can add table 2.
You can use opacity:
.image {
background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
width: 58px;
height: 58px;
opacity:0.5;
}
.image:hover{
opacity:1;
}
The <font>
tag has been deprecated, at least in XHTML. That means that it's use is officially "frowned upon," and there is no guarantee that future browsers will continue to display the text as you intended.
You have to use CSS. Go with the <span>
tag, or a separate style sheet. According to its specification, the <span>
tag has no semantic meaning and just allows you to change the style of a particular region.
If you have installed mongodb through homebrew
then you can simply start mongodb through
brew services start mongodb
Then access the shell by
mongo
You can shut down your db by
brew services stop mongodb
You can restart your db by
brew services restart mongodb
For more options
brew info mongodb
May be too late, but javascript array has two methods some
and every
method that returns a boolean and can help you achieve this.
I think some
would be most appropriate for what you intend to achieve.
vendors.some( vendor => vendor['Name'] !== 'Magenic' )
Some validates that any of the objects in the array satisfies the given condition.
vendors.every( vendor => vendor['Name'] !== 'Magenic' )
Every validates that all the objects in the array satisfies the given condition.
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
It's called a shebang. In unix-speak, # is called sharp (like in music) or hash (like hashtags on twitter), and ! is called bang. (You can actually reference your previous shell command with !!, called bang-bang). So when put together, you get haSH-BANG, or shebang.
The part after the #! tells Unix what program to use to run it. If it isn't specified, it will try with bash (or sh, or zsh, or whatever your $SHELL variable is) but if it's there it will use that program. Plus, # is a comment in most languages, so the line gets ignored in the subsequent execution.
I know this is an old question but I came here first and then discovered the atexit
module. I do not know about its cross-platform track record or a full list of caveats yet, but so far it is exactly what I was looking for in trying to handle post-KeyboardInterrupt
cleanup on Linux. Just wanted to throw in another way of approaching the problem.
I want to do post-exit clean-up in the context of Fabric operations, so wrapping everything in try
/except
wasn't an option for me either. I feel like atexit
may be a good fit in such a situation, where your code is not at the top level of control flow.
atexit
is very capable and readable out of the box, for example:
import atexit
def goodbye():
print "You are now leaving the Python sector."
atexit.register(goodbye)
You can also use it as a decorator (as of 2.6; this example is from the docs):
import atexit
@atexit.register
def goodbye():
print "You are now leaving the Python sector."
If you wanted to make it specific to KeyboardInterrupt
only, another person's answer to this question is probably better.
But note that the atexit
module is only ~70 lines of code and it would not be hard to create a similar version that treats exceptions differently, for example passing the exceptions as arguments to the callback functions. (The limitation of atexit
that would warrant a modified version: currently I can't conceive of a way for the exit-callback-functions to know about the exceptions; the atexit
handler catches the exception, calls your callback(s), then re-raises that exception. But you could do this differently.)
For more info see:
atexit
Maybe this link will help you.
See: std::string documentation.
#include <string>
is the most widely accepted.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
Check the domain's web server for http://www.<domain>.com
configuration for X-Frame-Options
It is a security feature designed to prevent clickJacking attacks,
Technically the evil has an iframe
with the source to the victim page.
<html>
<iframe src='victim_domain.com'/>
<input id="username" type="text" style="display: none;"/>
<input id="password" type="text" style="display: none;"/>
<script>
//some JS code that click jacking the user username and input from inside the iframe...
<script/>
<html>
If you want to prevent web server request to be rendered within an iframe
add the x-frame-options
X-Frame-Options DENY
The options are:
This is IIS config example:
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
If the web server activated the security feature it may cause a client-side SecurityError as it should.
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
I always tend to set the JAVA_HOME according to the /usr/bin/java
.
JAVA_HOME="$(dirname -- "$(dirname -- "$(readlink -f /usr/bin/java)")")"
This way, both alternatives point to the same location
Both tmux and GNU Screen work under cygwin. They can be installed from the cygwin installer. Just search for their name there and you probably will get to the latest version (at least for tmux).
I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...
import unicodedata
The dataframe object can be whatever you like, let's call it table...
table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
table.index+= 1
encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))
#this is where the magic happens
html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')
export normalized string to html file
file = open("templates/home.html","w")
file.write(html_data)
file.close()
Reference: unicodedata documentation
This worked for me but this depends on what you get when you hit Date()
:
Date().slice(16,-12)
Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id
?
UPDATE
SELECT t.*
FROM
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a
INNER JOIN temp_tickets t ON (t.id = a.id)
use mysql_real_escape_string()
instead of mysqli_real_escape_string()
like so:
$username = mysql_real_escape_string($_POST['username']);
Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
But when space is removed it works -
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);?
Hope it helps !!
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
You could also do a set diff, for example:
list(set(nltk.regexp_tokenize(sentence, pattern, gaps=True)) - set(nltk.corpus.stopwords.words('english')))
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));
If you alert(JSON.stringify(objToJson))
you will get {"response":"value"}
Put into a script I like something like that:
#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database
BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"
# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
mkdir $BASE_DIR
chown -R postgres:postgres $BASE_DIR
fi
sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME
As said, this error usually comes if u stay behind proxy. So to get with this, open IE-Internet options-Connections-LAN settings and take the proxy address. Configure the SDK Manager.exe (settings tab) to that proxy address with port. Check Force Http....
If u have a Proxy script in your LAN settings, copy the address and paste in address bar. Open the downloaded file in notepad. Find your ip address from ipconfig. In the file, go the subnet range in which your ip falls. Eg: isInNet(resolved_ip, "198.175.111.0", "255.255.255.0") will be true for 198.175.111.53 take the return value: after the word PROXY and use this for configuring SDK Manager.
Now the SDK will be downloaded happily.
this seems to be working nicely for me
$(window).bind('resize', function() {
jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
It's a list of public objects of that module, as interpreted by import *
. It overrides the default of hiding everything that begins with an underscore.
You could use Linq.
var prod = from p in prods
where p.ID != 1
select p;
Use null to define something as having no value, use undefined when you expect something might not be defined at all.
For example, if a variable has no value, assign it as null.
var weDontHaveAValue = null;
If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.
if (typeof args.optionalParam !== 'undefined') { }
As I cannot comment, here as answer: I would write Can Berk Güder's solution in a more general way, so you may reuse the function for other checkboxes
<script language="JavaScript">
function toggleCheckboxes(source, cbName) {
checkboxes = document.getElementsByName(cbName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
1) Download winutils.exe from https://github.com/steveloughran/winutils
2) Create a directory In windows "C:\winutils\bin
3) Copy the winutils.exe inside the above bib folder .
4) Set the environmental property in the code
System.setProperty("hadoop.home.dir", "file:///C:/winutils/");
5) Create a folder "file:///C:/temp" and give 777 permissions.
6) Add config property in spark Session ".config("spark.sql.warehouse.dir", "file:///C:/temp")"
You can configure patterns to hide files and folders from the explorer and searches.
File > Preferences > Settings
). This will open the setting screen.files:exclude
in the search at the top.node_modules/
then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic. When you are done it should look something like this:
If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:
"files.exclude": {
"node_modules/": true
}
To hide all files that start with ._
such as ._.DS_Store
files found on OSX:
"files.exclude": {
"**/._*": true
}
You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings
). Workspace settings will create a .vscode/settings.json
file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.
Nothing seemd to work for me, but this did the trick
$(parent.window.document).scroll(function() {
alert("bottom!");
});
RENAME TABLE old_table_name TO new_table_name;
Here is the code to create a simple one second timer tick:
using System;
using System.Threading;
class TimerExample
{
static public void Tick(Object stateInfo)
{
Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
}
static void Main()
{
TimerCallback callback = new TimerCallback(Tick);
Console.WriteLine("Creating timer: {0}\n",
DateTime.Now.ToString("h:mm:ss"));
// create a one second timer tick
Timer stateTimer = new Timer(callback, null, 0, 1000);
// loop here forever
for (; ; )
{
// add a sleep for 100 mSec to reduce CPU usage
Thread.Sleep(100);
}
}
}
And here is the resulting output:
c:\temp>timer.exe
Creating timer: 5:22:40
Tick: 5:22:40
Tick: 5:22:41
Tick: 5:22:42
Tick: 5:22:43
Tick: 5:22:44
Tick: 5:22:45
Tick: 5:22:46
Tick: 5:22:47
EDIT: It is never a good idea to add hard spin loops into code as they consume CPU cycles for no gain. In this case that loop was added just to stop the application from closing, allowing the actions of the thread to be observed. But for the sake of correctness and to reduce the CPU usage a simple Sleep call was added to that loop.
Well, getting full path is not possible but we can have a temporary path.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
Assume you have three view controllers instantiated like so:
UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];
You have added them to a tab bar like this:
UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];
Now you are trying to do something like this:
[tabBarController presentModalViewController:vc3];
This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.
Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".
I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.
$(function() {
//Listen for a click on the girl button
$('#girl-btn').click(function() {
// When the girl button has been clicked, change the source of the #square image to be the girl PNG
$('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
});
//Listen for a click on the plane button
$('#plane-btn').click(function() {
// When the plane button has been clicked, change the source of the #square image to be the plane PNG
$('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
});
//Listen for a click on the fruit button
$('#fruits-btn').click(function() {
// When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
$('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
<button id="girl-btn">Girl</button>
<button id="plane-btn">Plane</button>
<button id="fruits-btn">Fruits</button>
<a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>
_x000D_
There's no need to do this in two commits, you can add the file and mark it executable in a single commit:
C:\Temp\TestRepo>touch foo.sh
C:\Temp\TestRepo>git add foo.sh
C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:
C:\Temp\TestRepo>git update-index --chmod=+x foo.sh
C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
And now the file is mode 0755 (executable).
C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100755 foo.sh
And now we have a single commit with a single executable file.
I figured out how to do this in Powershell that someone asked about:
$keyname=(((gci cert:\LocalMachine\my | ? {$_.thumbprint -like $thumbprint}).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
$keypath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”
$fullpath=$keypath+$keyname
$Acl = Get-Acl $fullpath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$iisAppPoolName", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $fullpath $Acl
Have you tried to cast it to a date, with <mydatetime>::date
?
Assuming you are using an iframe to import content available to the public but not owned by you into your website, you can always use the page anchor to direct you iframe to load where you want it to.
First you create an iframe with the width and height needed to display the data.
<iframe src="http://www.mygreatsite.com/page2.html" width="200px" height="100px"></iframe>
Second install addon such as Show Anchors 2 for Firefox and use it to display all the page anchors on the page you would like display in your iframe. Find the anchor point you want your frame to use and copy the anchor location by right clicking on it.
(You can download and install the plugin here => https://addons.mozilla.org/en-us/firefox/addon/show-anchors-2/)
Third use the copied web address with anchor point as your iframe source. When the frame loads, it will show the page starting at the anchor point you specified.
<iframe src="http://www.mygreatsite.com/page2.html#anchorname_1" width="200px" height="100px"></iframe>
That is the condensed instruction list. Hope it helps!
Try chmod u+x testscript.sh
I know it from here: http://www.linuxquestions.org/questions/red-hat-31/running-shell-script-command-not-found-202062/
item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
http://docs.angularjs.org/api/ng.filter:date
But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.
item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
http://www.w3.org/TR/html-markup/input.date.html
NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.
Collections use generics which support either reference types or wilcards. You can however use an Integer
wrapper
List<Integer> list = new ArrayList<>();
If the entire program should stop use sys.exit() otherwise just use an empty return.
Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.
Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none
version: '3.7'
services:
app:
image: ramansharma/einwohnertomcat:v0.0.1
deploy:
replicas: 1
ports:
- '8080:8080'
volumes:
- type: bind
source: /proc
target: /hostfs/proc
read_only: true
- type: bind
source: /sys/fs/cgroup
target: /hostfs/sys/fs/cgroup
read_only: true
- type: bind
source: /
target: /hostfs
read_only: true
networks:
hostnet: {}
networks:
- einwohner_net
- elk_elk_net
networks:
einwohner_net:
elk_elk_net:
external: true
hostnet:
external: true
name: host
Here's another, perhaps more familiar-looking way to do it:
for i in (0..10).step(2) do
puts i
end
If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:
library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)
From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.
import java.lang.reflect.ParameterizedType;
class Foo {
public bar() {
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
Class type = (Class) superClass.getActualTypeArguments()[0];
try {
T t = type.newInstance();
//Do whatever with t
} catch (Exception e) {
// Oops, no default constructor
throw new RuntimeException(e);
}
}
}
'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim theta As Double = lon1 - lon2
Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
Math.Cos(deg2rad(theta))
dist = Math.Acos(dist)
dist = rad2deg(dist)
dist = dist * 60 * 1.1515
If unit = "K" Then
dist = dist * 1.609344
ElseIf unit = "N" Then
dist = dist * 0.8684
End If
Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim R As Double = 6371 'earth radius in km
Dim dLat As Double
Dim dLon As Double
Dim a As Double
Dim c As Double
Dim d As Double
dLat = deg2rad(lat2 - lat1)
dLon = deg2rad((lon2 - lon1))
a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
d = R * c
Select Case unit.ToString.ToUpper
Case "M"c
d = d * 0.62137119
Case "N"c
d = d * 0.5399568
End Select
Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
Return rad / Math.PI * 180.0
End Function
A modified version of above to make it more dynamic.
Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
On Error GoTo Failed
Dim WinHttpReq As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URL, False, Username, Password
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Dim oStream As Object: Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
oStream.Close
DownloadFileB = Len(Dir(DownloadPath)) > 0
Exit Function
End If
Failed:
DownloadFileB = False
End Function
Django code views.py
:
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
HTML code view.html
:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/view/',
data: {
'fruit': selected
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{{data}}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
str.replace()
v2|v3 does not recognize regular expressions.
To perform a substitution using a regular expression, use re.sub()
v2|v3.
For example:
import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
In a loop, it would be better to compile the regular expression first:
import re
regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
# do something with the updated line
If you want to know when home is clicked is an AppCompatActivity
then you should try it like this:
First tell Android you want to use your Toolbar
as your ActionBar
:
setSupportActionBar(toolbar);
Then set Home to be displayed via setDisplayShowHomeEnabled
like this:
getSupportActionBar().setDisplayShowHomeEnabled(true);
Finally listen for click events on android.R.id.home
like usual:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Timber.d("Home pressed");
}
return super.onOptionsItemSelected(menuItem);
}
If you want to know when the navigation button is clicked on a Toolbar
in a class other than AppCompatActivity
you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar
where the the "home" button used to be.
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("cek", "home selected");
}
});
If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened
and onDrawerClosed
so you'll want to see if those callbacks fit your requirements.
HTML
<img id="close" className="fa fa-close" src="" alt="" title="Close Me" />
CSS
#close[title]:hover:after {
color: red;
content: attr(title);
position: absolute;
left: 50px;
}
I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me
const [state, setState] = useState({
foo: "abc",
bar: 123
});
// Do this!
setState(prevState => {
return {
...prevState,
foo: "def"
};
});
setState(prevState => {
return {
...prevState,
bar: 456
};
});
On Windows:
Assign value to PGPASSWORD: C:\>set PGPASSWORD=pass
Run command: C:\>psql -d database -U user
Ready
Or in one line,
set PGPASSWORD=pass&& psql -d database -U user
Note the lack of space before the && !
How about something like this: http://jsfiddle.net/EgLKV/3/
Its done by using position:absolute
and z-index
to place the text over the image.
#container {_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
position: relative;_x000D_
}_x000D_
#image {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
}_x000D_
#text {_x000D_
z-index: 100;_x000D_
position: absolute;_x000D_
color: white;_x000D_
font-size: 24px;_x000D_
font-weight: bold;_x000D_
left: 150px;_x000D_
top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
<img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
<p id="text">_x000D_
Hello World!_x000D_
</p>_x000D_
</div>
_x000D_
You can follow one of the below approaches:
1) Basic, single type :
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
2) Multiple Types :
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.
//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
Correct : Compiles fine
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
Sample Class Code :
package generics.basics;
import java.util.ArrayList;
import java.util.List;
public class GenericMethods {
/*
Declare the generic type parameter T in this method.
After the qualifiers public and static, you put <T> and
then followed it by return type, method name, and its parameters.
Observe : type of val is 'T' and not '<T>'
* */
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
/*// Q: To audience -> will this compile ?
*
* public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}*/
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return null;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list.toString());
fill(list, 100);
System.out.println(list.toString());
List<String> Strlist = new ArrayList<>();
Strlist.add("Chirag");
Strlist.add("Nayak");
System.out.println(Strlist.toString());
fill(Strlist, "GOOD BOY");
System.out.println(Strlist.toString());
System.out.println(multipleTypeArgument("Chirag", 100));
System.out.println(multipleTypeArgument(100,"Nayak"));
}
}
// class definition ends
Sample Output:
[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak
Since we're offering alternatives to what you asked..
If you're in .Net, you should look at the Database Publishing Wizard in Visual Studio. Easy way to script your tables/data to a text file.
http://www.codeplex.com/sqlhost/Wiki/View.aspx?title=Database%20Publishing%20Wizard
You can just create an Image
object and put the base64 as its src
, including the data:image...
part like this:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
It's what they call "Data URIs" and here's the compatibility table for inner peace.
What ever instance you are using to call the void method , You can just use ,Verfiy
For Example:
In My case its _Log
is the instance and LogMessage
is the method to be tested:
try
{
this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch
{
Assert.IsFalse(ex is Moq.MockException);
}
Is the Verify
throws an exception due to failure of the method the test would Fail ?
Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:
if (lista.contains(conta1)) {
System.out.println("Account found");
} else {
System.out.println("Account not found");
}
Edit:
Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount
object and the selecting Source > Generate hashCode() and equals()...
In case someone else facing same issue as me. On Ubuntu 16.04, the only persistent solution it worked for me:
Edit /lib/systemd/system/mysql.service and set it to:
[Unit]
Description=MySQL Community Server
After=network.target
[Install]
WantedBy=multi-user.target
[Service]
User=mysql
Group=mysql
PermissionsStartOnly=true
ExecStartPre=/usr/share/mysql/mysql-systemd-start pre
# Normally, we'd simply use:
# ExecStart=/usr/sbin/mysqld
ExecStart=/usr/sbin/mysqld --sql-mode=ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
ExecStartPost=/usr/share/mysql/mysql-systemd-start post
TimeoutSec=600
Restart=on-failure
RuntimeDirectory=mysqld
RuntimeDirectoryMode=755`
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next()
executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next()
only consumes the "end of line" and does not wait to read from keyboard.
Tip: use scanner.nextLine()
instead of scanner.next()
because scanner.next()
does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)
This error may be a permission one. So, test executing the command with -H flag:
sudo -H pip3 install numpy
If you'd like a version on npm, array-move is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.
I had fairly good success with this function:
function array_move(arr, old_index, new_index) {_x000D_
if (new_index >= arr.length) {_x000D_
var k = new_index - arr.length + 1;_x000D_
while (k--) {_x000D_
arr.push(undefined);_x000D_
}_x000D_
}_x000D_
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);_x000D_
return arr; // for testing_x000D_
};_x000D_
_x000D_
// returns [2, 1, 3]_x000D_
console.log(array_move([1, 2, 3], 0, 1));
_x000D_
Note that the last return
is simply for testing purposes: splice
performs operations on the array in-place, so a return is not necessary. By extension, this move
is an in-place operation. If you want to avoid that and return a copy, use slice
.
Stepping through the code:
new_index
is greater than the length of the array, we want (I presume) to pad the array properly with new undefined
s. This little snippet handles this by pushing undefined
on the array until we have the proper length.arr.splice(old_index, 1)[0]
, we splice out the old element. splice
returns the element that was spliced out, but it's in an array. In our above example, this was [1]
. So we take the first index of that array to get the raw 1
there.splice
to insert this element in the new_index's place. Since we padded the array above if new_index > arr.length
, it will probably appear in the right place, unless they've done something strange like pass in a negative number. A fancier version to account for negative indices:
function array_move(arr, old_index, new_index) {_x000D_
while (old_index < 0) {_x000D_
old_index += arr.length;_x000D_
}_x000D_
while (new_index < 0) {_x000D_
new_index += arr.length;_x000D_
}_x000D_
if (new_index >= arr.length) {_x000D_
var k = new_index - arr.length + 1;_x000D_
while (k--) {_x000D_
arr.push(undefined);_x000D_
}_x000D_
}_x000D_
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);_x000D_
return arr; // for testing purposes_x000D_
};_x000D_
_x000D_
// returns [1, 3, 2]_x000D_
console.log(array_move([1, 2, 3], -1, -2));
_x000D_
Which should account for things like array_move([1, 2, 3], -1, -2)
properly (move the last element to the second to last place). Result for that should be [1, 3, 2]
.
Either way, in your original question, you would do array_move(arr, 0, 2)
for a
after c
. For d
before b
, you would do array_move(arr, 3, 1)
.
You can simply use the indexOf method on the input string:
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
Or you can use the test method, on a simple RegEx:
function hasWhiteSpace(s) {
return /\s/g.test(s);
}
This will also check for other white space characters like Tab.
Short answer: download Linux Device Drivers and read the chapter on memory management.
Seriously, there are a lot of subtle issues related to kernel memory management that you need to understand - I spend a lot of my time debugging problems with it.
vmalloc() is very rarely used, because the kernel rarely uses virtual memory. kmalloc() is what is typically used, but you have to know what the consequences of the different flags are and you need a strategy for dealing with what happens when it fails - particularly if you're in an interrupt handler, like you suggested.
Another yet simple solution is to paste these line into the build.gradle file
dependencies {
//import of gridlayout
compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:appcompat-v7:+'
}
Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.
You can use URL encoding to encode the newline as %0A
.
mailto:[email protected]?subject=test&body=type%20your%0Amessage%20here
While the above appears to work in many cases, user olibre points out that the RFC governing the mailto URI scheme specifies that %0D%0A
(carriage return + line feed) should be used instead of %0A
(line feed). See also: Newline Representations.
VS Code 1.6.0 and Greater
As mentioned by aloisdg below, editor.renderWhitespace
is now an enum taking either none
, boundary
or all
. To view all whitespaces:
"editor.renderWhitespace": "all",
Before VS Code 1.6.0
Before 1.6.0, you had to set editor.renderWhitespace
to true
:
"editor.renderWhitespace": true
If the text's meaning is semantically strong, use the strong
element. If not, use a semantic named class (one that clearly shows the meaning of the element, don't mix presentation and data by calling it bold
etc) and reference it in your CSS.
<span class="important-message">I'm important!</span>
.important-message {
font-weight: bold;
}
Some people still use the b
element as a presentational hook, but it hasn't been deprecated, though most people favour the strong
element nowadays. Just make sure they are used correctly.
>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'
.replace
doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.
You need to take the return values from x.replace
and put them in a new set.
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
A hidden attribute is a boolean attribute (True/False). When this attribute is used on an element, it removes all relevance to that element. When a user views the html page, elements with the hidden attribute should not be visible.
Example:
<p hidden>You can't see this</p>
Aria-hidden attributes indicate that the element and ALL of its descendants are still visible in the browser, but will be invisible to accessibility tools, such as screen readers.
Example:
<p aria-hidden="true">You can't see this</p>
Take a look at this. It should answer all your questions.
Note: ARIA stands for Accessible Rich Internet Applications
Sources: Paciello Group
I had the same issue although I was requesting data from another web server and not locally. The response status code was 200 but I still didnt get the data, even though it was sent in JSON format by default. The (simple) problem was that I had forgot to include 'https://' in the url, so instead it used the local host in the beginning.
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
An undirected graph without cycle has |E| < |V|-1.
public boolean hasCycle(Graph g) {
int totalEdges = 0;
for(Vertex v : g.getVertices()) {
totalEdges += v.getNeighbors().size();
}
return totalEdges/2 > g.getVertices().size - 1;
}
I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.
If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.
In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.
I would say that (and if someone knows better, please correct me) the first example
AClass[] array = {object1, object2}
actually means
AClass[] array = new AClass[]{object1, object2};
but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.
The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.
According to your Code :
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n');
}
If You check System.out.print(name.length);
you will get 3;
that mean your name length is 3
your loop is running from 0 to 3 which should be running either "0 to 2" or "1 to 3"
Answer
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
System.out.print(name[i] +'\n');
}
Perl can be used for this, even on exotic platforms like AIX. Example:
#!/usr/bin/perl -w
use strict;
use Time::HiRes qw(gettimeofday);
my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime ($t_sec);
printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;
Here's a possible solution:
var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001
eval(x) --> 1.234
eval(y) --> 1.234001
This is a lot simpler with .slideToggle():
jQuery('.class1 a').click( function() {
$(this).next('.class2').slideToggle();
});
EDIT: made it .next instead of .siblings
http://www.mredesign.com/demos/jquery-effects-1/
You can also add cookie's to remember where you're at...
http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/
you could also do show columns in $table
or see Hive, how do I retrieve all the database's tables columns for access to hive metadata
This is a security issue that browsers ignore now. Browsers identify and store content using input names, even if developers consider the information to be sensitive and should not be stored.
Making an input name different between 2 requests will solve the problem (but will still be saved in browser's cache and will also increase browser's cache).
Asking the user to activate or deactivate options in their browser's settings is not a good solution. The issue can be fixed in the backend.
Here's the fix. All autocomplete elements are generated with a hidden input like this:
<?php $r = md5(rand() . microtime(TRUE)); ?>
<form method="POST" action="./">
<input type="text" name="<?php echo $r; ?>" />
<input type="hidden" name="__autocomplete_fix_<?php echo $r; ?>" value="username" />
<input type="submit" name="submit" value="submit" />
</form>
The server then processes the post variables like this: (Demo)
foreach ($_POST as $key => $val) {
$newKey = preg_replace('~^__autocomplete_fix_~', '', $key, 1, $count);
if ($count) {
$_POST[$val] = $_POST[$newKey];
unset($_POST[$key], $_POST[$newKey]);
}
}
The value can be accessed as usual
echo $_POST['username'];
And the browser won't be able to suggest information from the previous request or from previous users.
This will continue to work even if browsers update their techniques to ignore/respect autocomplete attributes.
You're focusing on the wrong thing. The difference between instanceof and any other method for checking the same thing would probably not even be measurable. If performance is critical then Java is probably the wrong language. The major reason being that you can't control when the VM decides it wants to go collect garbage, which can take the CPU to 100% for several seconds in a large program (MagicDraw 10 was great for that). Unless you are in control of every computer this program will run on you can't guarantee which version of JVM it will be on, and many of the older ones had major speed issues. If it's a small app you may be ok with Java, but if you are constantly reading and discarding data then you will notice when the GC kicks in.
You can use os.system function for simplicity and to invoke bash to accomplish the task:
import os
os.system('mv old_filename new_filename')
I had this problem with version 6.7.4 and resolved it by installing version 6.5.6.
My setup is Win 2008 R2 SP1 Data Center edition, SQL Server 2008 R2 with Business Intelligence Development Studio (VS2008). Very basic install.
When I was installing 6.7.4, i could not even see the MySQL provider as a choice. However, when i looked into the machine.config file, I saw references for MySQL role provider etc, but no entry was added in the .
del
won't trigger any dialogs or message boxes. You have a few problems, though:
start
will just open Explorer which would be useless. You need cd
to change the working directory of your batch file (the /D
is there so it also works when run from a different drive):
cd /D %temp%
You may want to delete directories as well:
for /d %%D in (*) do rd /s /q "%%D"
You need to skip the question for del
and remove read-only files too:
del /f /q *
so you arrive at:
@echo off
cd /D %temp%
for /d %%D in (*) do rd /s /q "%%D"
del /f /q *
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
In my case the user agent was not good enought since in the Ipad the user agent was the same as in Mac OS, therefore I had to do a nasty trick:
var mql = window.matchMedia("(orientation: landscape)");
/**
* If we are in landscape but the height is bigger than width
*/
if(mql.matches && window.screen.height > window.screen.width) {
// IOS
} else {
// Mac OS
}
Try:
public static void TestI(ref string test)
{
test = "after passing";
}
Case 1: If you run only this command to generate scaffold -
rails generate scaffold MODEL_NAME FIELD_NAME:DATATYPE
Ex - rails generate scaffold User name:string address:text
but till now you did not run any command for migration like
rake db:migrate
then you should need to run only this command like -
rails destroy scaffold User name:string address:text
Case 2: If you already run(Scaffold and Migration) by below commands like -
rails generate scaffold User name:string address:text
rake db:migrate
Then you should need to run first rollback migration command then destroy scaffold like below -
rake db:rollback
rails destroy scaffold User name:string address:text
So In this manner, we can undo scaffolding. Also we can use d for destroy and g for generate as a shortcut.
This may do the trick:
import sys
if sys.version_info[0] > 2:
# py3k
pass
else:
# py2
import codecs
import warnings
def open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None):
if newline is not None:
warnings.warn('newline is not supported in py2')
if not closefd:
warnings.warn('closefd is not supported in py2')
if opener is not None:
warnings.warn('opener is not supported in py2')
return codecs.open(filename=file, mode=mode, encoding=encoding,
errors=errors, buffering=buffering)
Then you can keep you code in the python3 way.
Note that some APIs like newline
, closefd
, opener
do not work
wget -m -A * -pk -e robots=off www.mysite.com/
this will download all type of files locally and point to them from the html file and it will ignore robots file
It works well:
py -m pip install --user --upgrade pip==9.0.3
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
I had the same problem but the issue was a different one, I was trying to create a service and pass $scope to it as a parameter.
That's another way to get this error as the documentation of that link says:
Attempting to inject a scope object into anything that's not a controller or a directive, for example a service, will also throw an Unknown provider: $scopeProvider <- $scope error. This might happen if one mistakenly registers a controller as a service, ex.:
angular.module('myModule', [])
.service('MyController', ['$scope', function($scope) {
// This controller throws an unknown provider error because
// a scope object cannot be injected into a service.
}]);
How about
# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))
or
# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))
or
# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))
Following @Francisco Goldenstein answer, I wrote an extension method
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Mediatel.Framework
{
public static class XDocumentHelper
{
public static IEnumerable<XElement> DescendantElements(this XDocument xDocument, string nodeName)
{
return xDocument.Descendants().Where(p => p.Name.LocalName == nodeName);
}
}
}
You can also use string.match().
var string1 = "aBc";
var match = string1.match(/AbC/i);
if(match) {
}
The best method that I know of and probably the simplest is to use the Windows Task Scheduler to execute your code at a specific time of day or have you application run permanently and check for a particular time of day or write a windows service that does the same.
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)
yields
0 1 2 newcol
0 1 2 3 [0, 1, 0]
1 4 5 6 [0, 0, 1]
2 7 8 9 [1, 0, 0]
Yes, you could also use COALESCE(@value,'')=''
which is based on the ANSI SQL standard:
SELECT CASE WHEN COALESCE(@value,'')=''
THEN 'Yes, it is null or empty' ELSE 'No, not null or empty'
END AS IsNullOrEmpty
ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
// To dismiss the dialog
progress.dismiss();
OR
ProgressDialog.show(this, "Loading", "Wait while loading...");
By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)
By default Mysql store and return ‘date’ data type values in “YYYY/MM/DD” format. So if we want to display date in different format then we have to format date values as per our requirement in scripting language
And by the way what is the column data type and in which format you are storing the value.
If you're using Python, you can define your environment variables in a .env
file and load them from within a Jupyter notebook using python-dotenv.
Install python-dotenv:
pip install python-dotenv
Load the .env
file in a Jupyter notebook:
%load_ext dotenv
%dotenv
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
To force TCP/IP being used replace localhost with 127.0.0.1 in your connection string.
As you are using a username and password make sure SQL authentication is enabled. By default only Windows integrated is enabled on sqlserver 2008.
With SqlServer authentication keep in mind that a password policy is in place to enforce security.
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
Google has created a library for easy Permissions management. Its called EasyPermissions
Here is a simple example on requesting Location permission using this library.
public class MainActivity extends AppCompatActivity {
private final int REQUEST_LOCATION_PERMISSION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestLocationPermission();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
@AfterPermissionsGranted(REQUEST_CODE)
is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE
has been granted.
This above case, the method requestLocationPermission()
method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.
You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.
A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.
Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.
Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).
The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.
Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.
the error explain all things, the idea is confused between gradle and maven.
try to create new project with two gradle modules, you can build spring application with gradle as maven.
see this example from spring guides
For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0
for 32-bit editions of Windows, and
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0
for 64-bit editions of Windows.
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
Use a Comparator:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
Additionally, if CustomObject
implements Comparable
, then just use Collections.sort(list)
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
Much simplier
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
Simplest
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
Obviously the initial code can be used for JDK 8 too.
Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1
:
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
function ThrowOnNativeFailure {
if (-not $?)
{
throw 'Native Failure'
}
}
Then in any powershell file, after the CmdletBinding
and Param
for the file (if present), I have the following:
$ErrorActionPreference = "Stop"
. "$PSScriptRoot\ps_support.ps1"
The duplicated ErrorActionPreference = "Stop"
line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1
wrong, that needs to not silently fail!
I keep ps_support.ps1
in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1
file is.
Any native call gets this treatment:
native_call.exe
ThrowOnNativeFailure
Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)
Slightly different case, but it may help someone.
I followed the instructions to create a secondary database instance, and I had to clone the ini file as part of that. It was failing to start the service, with the same error. Turns out notepad.exe had re-encoded the cloned ini file as UTF8-BOM, and MySQL (version 8) refused to work with it. Removing the BOM fixed the problem.
Use Cheerio. It isn't as strict as jsdom and is optimized for scraping. As a bonus, uses the jQuery selectors you already know.
? Familiar syntax: Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.
? Blazingly fast: Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.
? Insanely flexible: Cheerio wraps around @FB55's forgiving htmlparser. Cheerio can parse nearly any HTML or XML document.
If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:
;extension=php_imap.dll
to
extension=php_imap.dll
I am using Jenkins with .net projects and had troubles with MVC 4 references.
I finallys solved my issue by using a .Net reference search engine functionality based on the registry using :
"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v2.0.50727\AssemblyFoldersEx"
You can create subkey et set the default key to "c:\myreferenceedir" for example.
It saved me with MVC versions and also ASP.net Web pages.
Usefull to add references to the "Add Reference Dialog"
If you don't want to bother with a file, you can do something like this in your code:
static
{
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(
new PatternLayout("%-6r [%p] %c - %m%n")));
}
You can use these options as well, either use \footnotesize
or \tiny
. This would really help in fitting big tables.
\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
\toprule
S.No & HMD \\
\midrule
1 & HTC Vive \\
2 & HTC Vive Pro \\
\bottomrule
\end{tabular}
\end{table}
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:
public bool IsNumeric(string val) => int.TryParse(val, out int result);
Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.
here is how you can perform simply, make a drawable resource file in drawable.xml. Say round_button.xml and then paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="oval">
<solid
android:color="@color/button_start_gradient_color"/>
</shape>
</item>
<item
android:drawable="@drawable/microphone"/>
</layer-list>
Note:- use your own color and drawable resource as i have used @drawable/microphone
Following is the result [1]: https://i.stack.imgur.com/QyhdJ.png
Use target="_top"
attribute in anchor tag that will really work.
I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.
Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html
How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/
I was able to resolve this by following the steps posted here: xampp phpmyadmin, Incorrect format parameter
Because I'm not using XAMPP, I also needed to update my php.ini.default
to php.ini
which finally did the trick.
Since your issue is mostly stylistic (not wanting to fill up the constructor with a bunch of declarations) it can be solved stylistically as well.
The way I view it, many class based languages have the constructor be a function named after the class name itself. Stylistically we could use that that to make an ES6 class that stylistically still makes sense but does not group the typical actions taking place in the constructor with all the property declarations we're doing. We simply use the actual JS constructor as the "declaration area", then make a class named function that we otherwise treat as the "other constructor stuff" area, calling it at the end of the true constructor.
"use strict"; class MyClass { // only declare your properties and then call this.ClassName(); from here constructor(){ this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; this.MyClass(); } // all sorts of other "constructor" stuff, no longer jumbled with declarations MyClass() { doWhatever(); } }
Both will be called as the new instance is constructed.
Sorta like having 2 constructors where you separate out the declarations and the other constructor actions you want to take, and stylistically makes it not too hard to understand that's what is going on too.
I find it's a nice style to use when dealing with a lot of declarations and/or a lot of actions needing to happen on instantiation and wanting to keep the two ideas distinct from each other.
NOTE: I very purposefully do not use the typical idiomatic ideas of "initializing" (like an init()
or initialize()
method) because those are often used differently. There is a sort of presumed difference between the idea of constructing and initializing. Working with constructors people know that they're called automatically as part of instantiation. Seeing an init
method many people are going to assume without a second glance that they need to be doing something along the form of var mc = MyClass(); mc.init();
, because that's how you typically initialize. I'm not trying to add an initialization process for the user of the class, I'm trying to add to the construction process of the class itself.
While some people may do a double-take for a moment, that's actually the bit of the point: it communicates to them that the intent is part of construction, even if that makes them do a bit of a double take and go "that's not how ES6 constructors work" and take a second looking at the actual constructor to go "oh, they call it at the bottom, I see", that's far better than NOT communicating that intent (or incorrectly communicating it) and probably getting a lot of people using it wrong, trying to initialize it from the outside and junk. That's very much intentional to the pattern I suggest.
For those that don't want to follow that pattern, the exact opposite can work too. Farm the declarations out to another function at the beginning. Maybe name it "properties" or "publicProperties" or something. Then put the rest of the stuff in the normal constructor.
"use strict"; class MyClass { properties() { this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; } constructor() { this.properties(); doWhatever(); } }
Note that this second method may look cleaner but it also has an inherent problem where properties
gets overridden as one class using this method extends another. You'd have to give more unique names to properties
to avoid that. My first method does not have this problem because its fake half of the constructor is uniquely named after the class.
Here's an expression that works for MariaDB and MySQL >= 5.6:
SELECT (UNIX_TIMESTAMP(NOW()) * 1000000 + MICROSECOND(NOW(6))) AS unix_now_in_microseconds;
This relies on the fact that NOW() always returns the same time throughout a query; it's possible that a plain UNIX_TIMESTAMP()
would work as well, I'm not sure based on the documentation. It also requires MySQL >= 5.6 for the new precision argument for NOW()
function (MariaDB works too).
Let me make a recap.
When you build a view containing object of different owners, those other owners have to grant "with grant option" to the owner of the view. So, the view owner can grant to other users or schemas....
Example: User_a is the owner of a table called mine_a User_b is the owner of a table called yours_b
Let's say user_b wants to create a view with a join of mine_a and yours_b
For the view to work fine, user_a has to give "grant select on mine_a to user_b with grant option"
Then user_b can grant select on that view to everybody.
When you print it with this print 'I\nwould\nexpect\nmultiple\nlines'
you would get:
I
would
expect
multiple
lines
The \n
is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.
Think about it from the browser's point of view. For readonly the browser will send in a variable/value pair. For disabled, it won't.
Run this, then look at the URL after you hit submit:
<html>
<form action=foo.html method=get>
<input name=dis type=text disabled value="dis">
<input name=read type=text readonly value="read">
<input name=normal type=text value="normal">
<input type=submit>
</form>
</html>
UPDATE: This is wrong answer, but it's still useful to understand why it's wrong. See comments.
How about unicode-escape
?
>>> d = {1: "??? ????", 2: u"??? ????"}
>>> json_str = json.dumps(d).decode('unicode-escape').encode('utf8')
>>> print json_str
{"1": "??? ????", "2": "??? ????"}
Update: I'm doing this with date.toISOString().substr(0, 10)
. Gives the same result as the accepted answer and has good support.
Here's the code with parameter labels
def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
if x is not None and y is not None:
cv2.putText(
frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)
For font name please see another answer in this thread.
Excerpt from answer by @Roeffus
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
For more see this http://www.programcreek.com/python/example/83399/cv2.putText
The following fails the test for all exceptions, checked or unchecked:
@Test
public void testMyCode() {
try {
runMyTestCode();
} catch (Throwable t) {
throw new Error("fail!");
}
}
Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static
keyword in C/C++.
static
keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static
keyword because of which unnamed namespace has advantage over static. static
keyword can be used with variable, function and objects but not with user defined class.
For example:
static int x; // Correct
But,
static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong
But same can be possible with unnamed namespace. For example,
namespace {
class xyz {/*Body of class*/}
static structure {/*Body of structure*/}
} //Correct
Explicit conversion constructors (C++ only)
The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.
class A
{
public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal:
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A( 1 );
.
If you declare the constructor of the class as explicit
, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{
public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements are legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<A>(1);
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
This looks more to me like what you probably want.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());
function getReplacementString(str){
return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you.
This seems a little strange to only have 3 of the url characters so I would recommend this if possible.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());
function getReplacementString(str){
return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
which would rip out the http:// or https:// and print up to 10 charaters of www.example.com
Here's my pure bash solution that doesn't change IFS, and can take in a custom regex delimiter.
loop_custom_delimited() {
local list=$1
local delimiter=$2
local item
if [[ $delimiter != ' ' ]]; then
list=$(echo $list | sed 's/ /'`echo -e "\010"`'/g' | sed -E "s/$delimiter/ /g")
fi
for item in $list; do
item=$(echo $item | sed 's/'`echo -e "\010"`'/ /g')
echo "$item"
done
}