lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
If you want to have a new data frame then:
import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new= old[['A', 'C', 'D']]
I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.
Just add
::-webkit-scrollbar {display:none;}
To your id or class of the div you're using the scroll bar with.
Here is a helpful link Custom Scroll Bar in Webkit
Youtube data 3 API , duration string to seconds conversion in Python
convert_YouTube_duration_to_seconds('P2DT1S')
172801convert_YouTube_duration_to_seconds('PT2H12M51S')
7971
def convert_YouTube_duration_to_seconds(duration):
day_time = duration.split('T')
day_duration = day_time[0].replace('P', '')
day_list = day_duration.split('D')
if len(day_list) == 2:
day = int(day_list[0]) * 60 * 60 * 24
day_list = day_list[1]
else:
day = 0
day_list = day_list[0]
hour_list = day_time[1].split('H')
if len(hour_list) == 2:
hour = int(hour_list[0]) * 60 * 60
hour_list = hour_list[1]
else:
hour = 0
hour_list = hour_list[0]
minute_list = hour_list.split('M')
if len(minute_list) == 2:
minute = int(minute_list[0]) * 60
minute_list = minute_list[1]
else:
minute = 0
minute_list = minute_list[0]
second_list = minute_list.split('S')
if len(second_list) == 2:
second = int(second_list[0])
else:
second = 0
return day + hour + minute + second
The following is a native js solution.
function export2csv() {_x000D_
let data = "";_x000D_
const tableData = [];_x000D_
const rows = [_x000D_
['111', '222', '333'],_x000D_
['aaa', 'bbb', 'ccc'],_x000D_
['AAA', 'BBB', 'CCC']_x000D_
];_x000D_
for (const row of rows) {_x000D_
const rowData = [];_x000D_
for (const column of row) {_x000D_
rowData.push(column);_x000D_
}_x000D_
tableData.push(rowData.join(","));_x000D_
}_x000D_
data += tableData.join("\n");_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));_x000D_
a.setAttribute("download", "data.csv");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2csv()">Export array to csv file</button>
_x000D_
for me, shift + enter did the trick.
All of these suggestions are great and all, but they're either only fixing either the header or a column, not both, or they're using javascript. The reason - it don't believe it can be done in pure CSS. The reason:
If it were possible to do it, you would need to nest several scrollable divs one inside the other, each with a scroll in a different direction. Then you would need to split your table into three parts - the fixed header, the fixed column and the rest of the data.
Fine. But now the problem - you can make one of them stay put when you scroll, but the other one is nested inside the scrolling area of first and is therefore subject to being scrolled out of sight itself, so can't be fixed in place on the screen. 'Ah-ha' you say 'but I can somehow use absolute or fixed position to do that' - no you can't. As soon as you do that you lose the ability to scroll that container. It's a chicken and egg situation - you can't have both, they cancel each other out.
I believe the only solution is through javascript. You need to completely seperate out the three elements and keep their positions in sync through javascript. There are good examples in other posts on this page. This one is also worth a look:
http://tympanus.net/codrops/2014/01/09/sticky-table-headers-columns/
One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:
#include <iostream>
using namespace std;
int variable = 20;
int main()
{
float variable = 30;
cout << "This is local to the main function: " << variable << endl;
cout << "This is global to the main function: " << ::variable << endl;
return 0;
}
The resulting output would be:
This is local to the main function: 30
This is global to the main function: 20
Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.
java.awt.Desktop
is the class you're looking for.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
or:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
Just a little modification to @Epsicron 's answer
SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%',
string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
('Coordination005'),
('Balance1000sheet')) as a(string)
no need for a temporary variable
Under my Android Studio\bin there are two folder
studio.exe and studio64.exe
I tried to run the first program and it gives me the mentioned error.
But when running studio64.exe it works.
Of course the !important trick is decisive here, but targeting more specifically may help not only to have your override actually applied (weight criteria can rule over !important) but also to avoid overriding unintended elements.
With the developer tools of your browser, identify the exact value of the offending style attribute; e.g.:
"font-family: arial, helvetica, sans-serif;"
or
"display: block;"
Then, decide which branch of selectors you will override; you can broaden or narrow your choice to fit your needs, e.g.:
p span
or
section.article-into.clearfix p span
Finally, in your custom.css, use the [attribute^=value] selector and the !important declaration:
p span[style^="font-family: arial"] {
font-family: "Times New Roman", Times, serif !important;
}
Note you don't have to quote the whole style attribute value, just enough to unambigously match the string.
Even I faced the same issue - when checked on dashboard I found following Error. As the data was coming through Flume and had interrupted in between due to which may be there was inconsistency in few files.
Caused by: org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.JsonParseException: Unexpected end-of-input within/between OBJECT entries
Running on fewer files it worked. Format consistency was the reason in my case.
Use android.support.v4.app
for FragmentManager & FragmentTransaction in your code, it has worked for me.
DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};
For the 2017 CC release this has been moved (after many years of habit development). Find it now at:
Edit > Code > Apply Source Formatting.
It may be prudent to set up a keyboard shortcut if this is something you'll need regularly.
Edit > Keyboard Shortcuts
Other answers have given very accurate responses and I am not completely sure what exactly was your problem(if it was just due to unknown type in your program then you would have gotten many more clear cut errors along with the one you mentioned) but to add on further information this error is also raised if we add the function type as void while calling the function as you can see further below:
#include<iostream>
#include<vector>
#include<utility>
#include<map>
using namespace std;
void fun(int x);
main()
{
int q=9;
void fun(q); //line no 10
}
void fun(int x)
{
if (x==9)
cout<<"yes";
else
cout<<"no";
}
Error:
C:\Users\ACER\Documents\C++ programs\exp1.cpp|10|error: variable or field 'fun' declared void|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
So as we can see from this example this reason can also result in "variable or field declared void" error.
JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.
Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.
I would recommend you to give a look to the following article:
That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.
Can be done using python XOR operator.
set(temp1) ^ set(temp2)
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
Do a python -VV
in the command line. It should return the version.
You could use %in%
like this:
df[, !(colnames(df) %in% c("x","bar","foo"))]
0. Prerequisite: openssl
should be installed. On Windows, if Git Bash
is installed, try that! Alternate binaries can be found here.
1. Extract .key
from .pem
:
openssl pkey -in cert.pem -out cert.key
2. Extract .crt
from .pem
:
openssl crl2pkcs7 -nocrl -certfile cert.pem | openssl pkcs7 -print_certs -out cert.crt
This stored procedure will provide you with a hierarchical tree of relationship. Based on this article from Technet. It will also optionally provide you a query for reading or deleting all the related data.
IF OBJECT_ID('GetForeignKeyRelations','P') IS NOT NULL
DROP PROC GetForeignKeyRelations
GO
CREATE PROC GetForeignKeyRelations
@Schemaname Sysname = 'dbo'
,@Tablename Sysname
,@WhereClause NVARCHAR(2000) = ''
,@GenerateDeleteScripts bit = 0
,@GenerateSelectScripts bit = 0
AS
SET NOCOUNT ON
DECLARE @fkeytbl TABLE
(
ReferencingObjectid int NULL
,ReferencingSchemaname Sysname NULL
,ReferencingTablename Sysname NULL
,ReferencingColumnname Sysname NULL
,PrimarykeyObjectid int NULL
,PrimarykeySchemaname Sysname NULL
,PrimarykeyTablename Sysname NULL
,PrimarykeyColumnname Sysname NULL
,Hierarchy varchar(max) NULL
,level int NULL
,rnk varchar(max) NULL
,Processed bit default 0 NULL
);
WITH fkey (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
AS
(
SELECT
soc.object_id
,scc.name
,soc.name
,convert(sysname,null)
,convert(int,null)
,convert(sysname,null)
,convert(sysname,null)
,convert(sysname,null)
,CONVERT(VARCHAR(MAX), scc.name + '.' + soc.name ) as Hierarchy
,0 as level
,rnk=convert(varchar(max),soc.object_id)
FROM SYS.objects soc
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
WHERE scc.name =@Schemaname
AND soc.name =@Tablename
UNION ALL
SELECT sop.object_id
,scp.name
,sop.name
,socp.name
,soc.object_id
,scc.name
,soc.name
,socc.name
,CONVERT(VARCHAR(MAX), f.Hierarchy + ' --> ' + scp.name + '.' + sop.name ) as Hierarchy
,f.level+1 as level
,rnk=f.rnk + '-' + convert(varchar(max),sop.object_id)
FROM SYS.foreign_key_columns sfc
JOIN Sys.Objects sop
ON sfc.parent_object_id = sop.object_id
JOIN SYS.columns socp
ON socp.object_id = sop.object_id
AND socp.column_id = sfc.parent_column_id
JOIN sys.schemas scp
ON sop.schema_id = scp.schema_id
JOIN SYS.objects soc
ON sfc.referenced_object_id = soc.object_id
JOIN SYS.columns socc
ON socc.object_id = soc.object_id
AND socc.column_id = sfc.referenced_column_id
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
JOIN fkey f
ON f.ReferencingObjectid = sfc.referenced_object_id
WHERE ISNULL(f.PrimarykeyObjectid,0) <> f.ReferencingObjectid
)
INSERT INTO @fkeytbl
(ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
SELECT ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk
FROM fkey
SELECT F.Relationshiptree
FROM
(
SELECT DISTINCT Replicate('------',Level) + CASE LEVEL WHEN 0 THEN '' ELSE '>' END + ReferencingSchemaname + '.' + ReferencingTablename 'Relationshiptree'
,RNK
FROM @fkeytbl
) F
ORDER BY F.rnk ASC
-------------------------------------------------------------------------------------------------------------------------------
-- Generate the Delete / Select script
-------------------------------------------------------------------------------------------------------------------------------
DECLARE @Sql VARCHAR(MAX)
DECLARE @RnkSql VARCHAR(MAX)
DECLARE @Jointables TABLE
(
ID INT IDENTITY
,Object_id int
)
DECLARE @ProcessTablename SYSNAME
DECLARE @ProcessSchemaName SYSNAME
DECLARE @JoinConditionSQL VARCHAR(MAX)
DECLARE @Rnk VARCHAR(MAX)
DECLARE @OldTablename SYSNAME
IF @GenerateDeleteScripts = 1 or @GenerateSelectScripts = 1
BEGIN
WHILE EXISTS ( SELECT 1
FROM @fkeytbl
WHERE Processed = 0
AND level > 0 )
BEGIN
SELECT @ProcessTablename = ''
SELECT @Sql = ''
SELECT @JoinConditionSQL = ''
SELECT @OldTablename = ''
SELECT TOP 1 @ProcessTablename = ReferencingTablename
,@ProcessSchemaName = ReferencingSchemaname
,@Rnk = RNK
FROM @fkeytbl
WHERE Processed = 0
AND level > 0
ORDER BY level DESC
SELECT @RnkSql ='SELECT ' + REPLACE (@rnk,'-',' UNION ALL SELECT ')
DELETE FROM @Jointables
INSERT INTO @Jointables
EXEC(@RnkSql)
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT [' + @ProcessSchemaName + '].[' + @ProcessTablename + '].*' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
SELECT @JoinConditionSQL = @JoinConditionSQL
+ CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN 'JOIN [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '] ' + CHAR(10) + ' ON '
ELSE ' AND '
END
+ ' [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '].[' + f.PrimarykeyColumnname + '] = [' + f.ReferencingSchemaname + '].[' + f.ReferencingTablename + '].[' + f.ReferencingColumnname + ']' + CHAR(10)
, @OldTablename = CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN f.PrimarykeyTablename
ELSE @OldTablename
END
FROM @fkeytbl f
JOIN @Jointables j
ON f.Referencingobjectid = j.Object_id
WHERE charindex(f.rnk + '-',@Rnk + '-') <> 0
AND F.level > 0
ORDER BY J.ID DESC
SELECT @Sql = @Sql + @JoinConditionSQL
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE (' + @WhereClause + ')'
PRINT @SQL
PRINT CHAR(10)
UPDATE @fkeytbl
SET Processed = 1
WHERE ReferencingTablename = @ProcessTablename
AND rnk = @Rnk
END
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT * FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE ' + @WhereClause
PRINT @SQL
END
SET NOCOUNT OFF
go
You should use the * operator, like foo(*values)
Read the Python doc unpackaging argument lists.
Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z):
return "%d, %d, %d" % (x,y,z)
values = [1,2,3]
# the solution.
foo(*values)
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
One good thing about @LazyCollection(LazyCollectionOption.FALSE)
is that several fields with this annotation can coexist while FetchType.EAGER
cannot, even in the situations where such coexistence is legit.
For example, an Order
may have a list of OrderGroup
(a short one) as well as a list of Promotions
(also short). @LazyCollection(LazyCollectionOption.FALSE)
can be used on both without causing LazyInitializationException
neither MultipleBagFetchException
.
In my case @Fetch
did solve my problem of MultipleBacFetchException
but then causes LazyInitializationException
, the infamous no Session
error.
print 'yes' if 0 < x < 0.5 else 'no'
range()
is for generating arrays of consecutive integers
SBJSON *parser = [[SBJSON alloc] init];
NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];
url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]
NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];
NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];
for(NSDictionary *news in news_array)
{
@try {
[title_arr addObject:[news valueForKey:@"gtitle"]]; //values Add to title array
}
@catch (NSException *exception) {
[title_arr addObject:[NSString stringWithFormat:@""]];
}
Try this one dude if you're using windows:
1.) Search environment variables at your start menu's search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin
If you got an error. Do the number 4.) Click New, then browse the bin folder
Short answer:
x.addEventListener("click", function(e){myfunction(e, param1, param2)});
...
function myfunction(e, param1, param1) {
...
}
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
There is another way:
CMD
(as Administrator)mklink /J C:\Program-Files "C:\Program Files"
(Or in my case mklink /J C:\Program-Files-(x86) "C:\Program Files (x86)"
)Now you can point to C:\Program-Files
(C:\Program-Files-(x86)
).
Go to
Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking
and be sure that
Enable on demand hyperlink style navigation
is checked.
In my case (python) it failed because I had these two lines of code in the file, inherited from an older code
http.client.HTTPConnection._http_vsn = 10
http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'
If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
//Timepicker
$(".timepicker").timepicker({
showInputs: false,
showMeridian: false //24hr mode
});
i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.
//airBnb
compile ('com.airbnb:deeplinkdispatch:3.1.1'){
exclude group:'com.google.code.findbugs'
}
annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
exclude group:'com.google.code.findbugs'
}
The best solution I found regarding this, and I tried it on 330 MB file.
lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
file.seek(lineno * (line_length + 2))
print(file.readline(), end='')
Where line_length is the number of characters in a single line. For example "abcd" has line length 4.
I have added 2 in line length to skip the '\n' character and move to the next character.
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };
Even I too faced similar issue,
fatal error RC1015: cannot open include file 'afxres.h'. from this code
Replacing afxres.h with Winresrc.h and declaring IDC_STATIC as -1 worked for me. (Using visual studio Premium 2012)
//#include "afxres.h"
#include "WinResrc.h"
#define IDC_STATIC -1
Comparison of different approaches
Here is a quick comparison of some of the approaches I've tried with images showing what the give.
Baseline example without trying to set the image dimensions
Just to have a comparison point:
base.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')
run:
./base.py
identify base.png
outputs:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1]
height-only control
I think this is what I'll go with most of the time, as it is simple and scales:
get_size.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size.png',
format='png',
dpi=height/fig.get_size_inches()[1]
)
run:
./get_size.py 431
outputs:
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
and
./get_size.py 1293
outputs:
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
I tend to set just the height because I'm usually most concerned about how much vertical space the image is going to take up in the middle of my text.
plt.savefig(bbox_inches='tight'
changes image size
I always feel that there is too much white space around images, and tended to add bbox_inches='tight'
from:
Removing white space around a saved image in matplotlib
However, that works by cropping the image, and you won't get the desired sizes with it.
Instead, this other approach proposed in the same question seems to work well:
plt.tight_layout(pad=1)
plt.savefig(...
which gives the exact desired height for height equals 431:
Fixed height, set_aspect
, automatically sized width and small margins
Ermmm, set_aspect
messes things up again and prevents plt.tight_layout
from actually removing the margins...
plt.savefig(dpi=h/fig.get_size_inches()[1]
+ width control
If you really need a specific width in addition to height, this seems to work OK:
width.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'width.png',
format='png',
dpi=h/hi
)
run:
./width.py 431 869
output:
width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000
and for a small width:
./width.py 431 869
output:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000
So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100
on the top left.
I managed to work around those with Removing white space around a saved image in matplotlib
plt.tight_layout(pad=1)
which gives:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000
From this, we also see that tight_layout
removes a lot of the empty space at the top of the image, so I just generally always use it.
Fixed magic base height, dpi
on fig.set_size_inches
and plt.savefig(dpi=
scaling
I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245
magic.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'magic.png',
format='png',
dpi=h/magic_height*dpi,
)
run:
./magic.py 431 231
outputs:
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
And to see if it scales nicely:
./magic.py 1291 693
outputs:
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height
parameter or equivalent.
Fixed DPI + set_size_inches
This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.
set_size_inches.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
0,
60.,
'Hello',
# Keep font size fixed independently of DPI.
# https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
'set_size_inches.png',
format='png',
)
run:
./set_size_inches.py 431 231
outputs:
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
so the height is slightly off, and the image:
The pixel sizes are also correct if I make it 3 times larger:
./set_size_inches.py 1291 693
outputs:
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.
In the previous example, we only made the "Hello" text proportional, and it did retain its height between 60 and 80 as we'd expect. But everything for which we didn't do that, looks tiny, including:
SVG
I could not find how to set it for SVG images, my approaches only worked for PNG e.g.:
get_size_svg.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size_svg.svg',
format='svg',
dpi=height/fig.get_size_inches()[1]
)
run:
./get_size_svg.py 431
and the generated output contains:
<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"
and identify says:
get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000
and if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.
But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:
inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png
gives the exact height:
TODO regenerate image, messed up the upload somehow.
I use Inkscape instead of Imagemagick's convert
here because you need to mess with -density
as well to get sharp SVG resizes with ImageMagick:
And setting <img height=""
on the HTML should also just work for the browser.
Tested on matplotlib==3.2.2.
Try:
g = pd.DataFrame(['A','B','A','C','D','D','E'])
# Group by the contents of column 0
gg = g.groupby(0)
# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())
# Add a new column that is the count / total number of elements
histo[1] = histo.astype(np.float)/len(g)
print histo
Output:
0 1
0
A 2 0.285714
B 1 0.142857
C 1 0.142857
D 2 0.285714
E 1 0.142857
If you are using Tomcat 7 and Eclipse, click on the Tomcat server and then goto the modules tab. There you will find the duplicate entry. Remove both the entry and redeploy the application. You are good to go now.
You don't need to use **arr, you can either use:
void do_something(int el, std::vector<int> *arr){
arr->push_back(el);
}
or:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
**arr makes no sense but if you insist using it, do it this way:
void do_something(int el, std::vector<int> **arr){
(*arr)->push_back(el);
}
but again there is no reason to do so...
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
In regards to veggerby's solution, if you are trying to implement it on a VB app, be careful trying to run the supplied code through a translator. The following will work:
Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState
Public Class SessionHeartbeatHttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Session("Heartbeat") = DateTime.Now
End Sub
End Class
Also, instead of calling like heartbeat() function like:
setTimeout("heartbeat()", 300000);
Instead, call it like:
setInterval(function () { heartbeat(); }, 300000);
Number one, setTimeout only fires once whereas setInterval will fire repeatedly. Number two, calling heartbeat() like a string didn't work for me, whereas calling it like an actual function did.
And I can absolutely 100% confirm that this solution will overcome GoDaddy's ridiculous decision to force a 5 minute apppool session in Plesk!
Ignore the files ending with .iws
, and the workspace.xml
and tasks.xml
files in your .gitignore
Reference
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");
When I upgraded Visual Studio to version 15.5.1, .Net Core SDK was upgraded to 2.X, so this error went away. When I run dotnet --info
, I see the following now:
You can use the gcc compiler in linux to link two c file in one output. Suppose you have two c files one is 'main.c' and another is 'support.c'. So the command to link these two is
gcc main.c support.c -o main.out
By this two files will be linked to a single output main.out To run the output the command will be
./main.out
If you are using function in main.c which is declared in support.c file then you should declare it in main also using extern storage class.
You can use this.innerHTML.
<textarea name="message" rows = "10" cols = "100" onfocus="this.innerHTML=''"> Enter your message here... </textarea>
_x000D_
When text area is focused, it basically makes the innerHTML of the textarea an empty string.
One risk of using the keyboard shortcut is that it requires using a non-ASCII encoding. That might be fine, but if your source is loaded by different editors in different locales, you might hit trouble somewhere along the line.
It might be safer to use either ’
or ’
(which are equivalent) as both are ASCII.
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
My vote would be for BBedit's free little brother TextWrangler.
I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList
.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
If you have forked a repository fro Delete your forked copy and fork it again from master.
It looks like, cargo
can have one or more item
. Each item would have a reference to its corresponding cargo
.
From the log, item
object is inserted first and then an attempt is made to update the cargo
object (which does not exist).
I guess what you actually want is cargo
object to be created first and then the item
object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.
There isn't one built in but you could write your own quite easily:
(function($) {
$.fn.invisible = function() {
return this.each(function() {
$(this).css("visibility", "hidden");
});
};
$.fn.visible = function() {
return this.each(function() {
$(this).css("visibility", "visible");
});
};
}(jQuery));
You can then call this like so:
$("#someElem").invisible();
$("#someOther").visible();
Here's a working example.
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use document.referrer
.
To access the user-agent, use navigator.userAgent
.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.
Open Ports Scanner works for me.
This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:
The code snippet is:
$.getJSON({
url: "https://myurl.com/api",
headers: { "Authorization": "Bearer " + user.access_token}
}).then().always( function (data, textStatus) {
$("#txtAPIStatus").html(data.status);
$("#txtAPIValue").html(data.responseText);
});
I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).
There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.
Besides that, you just have to throw your best psychic energies at it.
Include <%@ page isELIgnored="false"%>
on top of your jsp page.
Here's one of my favorite places to use the **
syntax as in Dave Webb's final example:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
\r
= CR (Carriage Return) → Used as a new line character in Mac OS before X\n
= LF (Line Feed) → Used as a new line character in Unix/Mac OS X\r\n
= CR + LF → Used as a new line character in WindowsI have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
Total online memory
Calculate the total online memory using the sys-fs.
totalmem=0;
for mem in /sys/devices/system/memory/memory*; do
[[ "$(cat ${mem}/online)" == "1" ]] \
&& totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes)))));
done
#one-line code
totalmem=0; for mem in /sys/devices/system/memory/memory*; do [[ "$(cat ${mem}/online)" == "1" ]] && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes))))); done
echo ${totalmem} bytes
echo $((totalmem/1024**3)) GB
Example output for 4 GB system:
4294967296 bytes
4 GB
Explanation
/sys/devices/system/memory/block_size_bytes
Number of bytes in a memory block (hex value). Using 0x in front of the value makes sure it's properly handled during the calculation.
/sys/devices/system/memory/memory*
Iterating over all available memory blocks to verify they are online and add the calculated block size to totalmem if they are.
[[ "$(cat ${mem}/online)" == "1" ]] &&
You can change or remove this if you prefer another memory state.
If we are talking about FLYME OS (Meizu) ONLY there are it's own Security app with permissions.
To open it use following intent:
public static void openFlymeSecurityApp(Activity context) {
Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
try {
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Of-cause BuildConfig is your app's BuildConfig.
I'm not sure what you're trying to do: If you added the file via
svn add myfile
you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an
svn commit
If you delete the file before the commit, svn
has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.
So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via
svn delete myfile
svn commit
If you want to undo the add
and just throw the file away, you can to an
svn revert myfile
which tells svn
(in this case) to undo the add-Operation.
EDIT
Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)
Follow these Steps:
1: Enter:
git reflog show
This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back
2: create a branch name with the Sha-1 ID you selected eg: 8c87714
git branch your-branch-name 8c87714
$('body').append($('<div/>', {
id: 'holdy'
}));
Count all files and subfolders, windows style:
dir=/YOUR/PATH;f=$(find $dir -type f | wc -l); d=$(find $dir -mindepth 1 -type d | wc -l); echo "$f Files, $d Folders"
I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.
According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!
I think you should upgrade lastest node version
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.
Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin
.
if(!str.trim()){
console.log('string is empty or only contains spaces');
}
Removing the whitespace from a string can be done using String#trim()
.
To check if a string is null or undefined, one can check if the string itself is falsey, in which case it is null, undefined, or an empty string. This first check is necessary, as attempting to invoke methods on null
or undefined
will result in an error. To check if it contains only spaces, one can check if the string is falsey after trimming, which means that it is an empty string at that point.
if(!str || !str.trim()){
//str is null, undefined, or contains only spaces
}
This can be simplified using the optional chaining operator.
if(!str?.trim()){
//str is null, undefined, or contains only spaces
}
If you are certain that the variable will be a string, only the second check is necessary.
if(!str.trim()){
console.log("str is empty or contains only spaces");
}
In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.
For \d use \p{N} (numbers)
For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)
Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.
List<String> list = Arrays.asList(array);
The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.
What about including the current directory in the search path?
ruby -I. main.rb
look it this piece of code from my project
I'm trying to re-order the list based on a property inside my model,
allEmployees = new List<Employee>(allEmployees.OrderByDescending(employee => employee.Name));
but I faced a problem when a small and capital letters exist
, so to solve it, I used the string comparer.
allEmployees.OrderBy(employee => employee.Name,StringComparer.CurrentCultureIgnoreCase)
I found myself on this page as I was also receiving the Cannot GET/
message. My circumstances differed as I was using express.static()
to target a folder, as has been offered in previous answers, and not a file as the OP was.
What I discovered after some digging through Express' docs is that express.static()
defines its index file as index.html
, whereas my file was named index.htm
.
To tie this to the OP's question, there are two options:
1: Use the code suggested in other answers
app.use(express.static(__dirname));
and then rename default.htm
file to index.html
or
2: Add the index
property when calling express.static()
to direct it to the desired index file:
app.use(express.static(__dirname, { index: 'default.htm' }));
this is pretty useful:
https://github.com/JedWatson/classnames
You can do stuff like
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
or use it like this
var btnClass = classNames('btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
What works for me, let's say you have branch1 and you wanna merge it into branch2.
You open git command line go to root folder of branch2 and type:
git checkout branch1
git pull branch1
git checkout branch2
git merge branch1
git push
If you have comflicts you don't need to do git push, but first solve the conflits and then push.
This isn't as straightforward as opening a plain text file and will require some sort of external module since nothing is built-in to do this. Here are some options:
If possible, you may want to consider exporting the excel spreadsheet as a CSV file and then using the built-in python csv module to read it:
Reinstalling git will solve the problem.
sudo apt-get remove git
sudo apt-get update
sudo apt-get install git
PhantomJS allows you to do this as well
If you looking for a simple way of datetime
to string conversion and can omit the format. You can convert datetime
object to str
and then use array slicing.
In [1]: from datetime import datetime
In [2]: now = datetime.now()
In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'
In [5]: str(now)[:10]
Out[5]: '2019-04-26'
In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'
But note the following thing. If other solutions will rise an AttributeError
when the variable is None
in this case you will receive a 'None'
string.
In [9]: str(None)[:19]
Out[9]: 'None'
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.
The answer is super simple, the type is Date
:
const d: Date = new Date(); // but the type can also be inferred from "new Date()" already
It is the same as with every other object instance :)
For what it's worth, a shorter way to write code to check each command for success is:
command1 || echo "command1 borked it"
command2 || echo "command2 borked it"
It's still tedious but at least it's readable.
$('tr').click(function(){
alert( $('tr').index(this) );
});
For first tr
, it alerts 0. If you want to alert 1, you can add 1 to index.
Ctrl+K, Ctrl+1 and then Ctrl+K, Ctrl+2 will do close to what you want.
The first command collapses level 1 (usually classes), and the second command collapses level 2 (usually methods).
You might even find it useful to skip the first command.
You need to use the proper git URL:
pip install git+https://github.com/jkbr/httpie.git#egg=httpie
Also see the VCS Support section of the pip documentation.
Don’t forget to include the egg=<projectname>
part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.
I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :
First create a function that will trigger when a column is generated :
<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>
Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if(YourColumn == typeof(DateTime))
{
e.Column.ClipboardContentBinding.StringFormat = "d";
}
}
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/
There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.
SELECT sensorID,timestamp,sensorField1,sensorField2
FROM (
SELECT sensorID,timestamp,sensorField1,sensorField2
, ROW_NUMBER() OVER(
PARTITION BY sensorID
ORDER BY timestamp
) AS rn
FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;
I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.
Its Working Properly
EditText et_mobile= (EditText) findViewById(R.id.edittxt);
et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
if (et_mobile.getText().toString().trim().length() == 0) {
CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
}
}
}
});
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:
>>> df[condition]
This will return a slice of your dataframe which you can index using iloc
. Here are your examples:
Get first row where A > 3 (returns row 2)
>>> df[df.A > 3].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
If what you actually want is the row number, rather than using iloc
, it would be df[df.A > 3].index[0]
.
Get first row where A > 4 AND B > 3:
>>> df[(df.A > 4) & (df.B > 3)].iloc[0]
A 5
B 4
C 5
Name: 4, dtype: int64
Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)
>>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:
>>> def series_or_default(X, condition, default_col, ascending=False):
... sliced = X[condition]
... if sliced.shape[0] == 0:
... return X.sort_values(default_col, ascending=ascending).iloc[0]
... return sliced.iloc[0]
>>>
>>> series_or_default(df, df.A > 6, 'A')
A 5
B 4
C 5
Name: 4, dtype: int64
As expected, it returns row 4.
Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>
This picture from developer android explains more about color pallete. You can read more on this link.
Change your method from
public void updateReceiptsList(List<Receipt> newlist) {
receiptlist = newlist;
this.notifyDataSetChanged();
}
To
public void updateReceiptsList(List<Receipt> newlist) {
receiptlist.clear();
receiptlist.addAll(newlist);
this.notifyDataSetChanged();
}
So you keep the same object as your DataSet in your Adapter.
Here is what I did to get a data set that included both the total and the number that met the criteria, within each shipping container. That let me answer the question "How many shipping containers have more than X% items over size 51"
select
Schedule,
PackageNum,
COUNT (UniqueID) as Total,
SUM (
case
when
Size > 51
then
1
else
0
end
) as NumOverSize
from
Inventory
where
customer like '%PEPSI%'
group by
Schedule, PackageNum
This post may help:
http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/
See also How to close a jQuery UI modal dialog by clicking outside the area covered by the box? for explanation of when and how to apply overlay
click or live event depending on how you are using dialog on page.
Not true for the OP, but this error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
The JSON spec requires double quotation marks for strings.
E.g:
JSON.parse(`{"myparam": 'myString'}`)
gives the error, whereas
JSON.parse(`{"myparam": "myString"}`)
does not. Note the quotation marks around myString
.
I use this form for just this sort of thing:
gci . hosts -r | ? {!$_.PSIsContainer}
.
maps to positional parameter Path
and "hosts" maps to positional parameter Filter
. I highly recommend using Filter
over Include
if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include
.
There is no super() in C++. You have to call the Base Constructor explicitly by name.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
you will have to instantiate it before you throw it
throw new RuntimeException(arg0)
PS: Intrestingly enough the Netbeans IDE should have already pointed out that compile time error
If it is MySql you can try
SELECT @n := @n + 1 n,
first_name,
last_name
FROM table1, (SELECT @n := 0) m
ORDER BY first_name, last_name
And for SQLServer
SELECT row_number() OVER (ORDER BY first_name, last_name) n,
first_name,
last_name
FROM table1
If you want exactly 40 spaces before the string then you should just do:
printf(" %s\n", myStr );
If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces):
printf("%40s%s", "", myStr );
If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this:
printf("%40s", myStr);
You can also put "up to" 40 spaces AfTER the string by doing:
printf("%-40s", myStr);
Variables are not defined, but declared.
This is possible duplicate of declare variables in a pl/sql block
But you can look here :
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/fundamentals.htm#i27306
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/overview.htm
UPDATE:
Refer here : How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?
My 2c.. I have used javascript, but found it did things that were not quite expected.
USE the panel's defaultButton attribute/property as many of the above posts suggest. It is reliable (EASY) and works in all the browsers I have tested it on.
You'll need to type cast it.
long i = 100L;
int k = (int) i;
Bear in mind that a long has a bigger range than an int so you might lose data.
If you are talking about the boxed types, then read the documentation.
You could try using the DirectoryEntry class with the IIS path prefix:
using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
{
filePath = de.Properties["Path"].Value;
}
if (!File.Exists(filePath))
return;
var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();
In Java SE you need software to run the program like if you have developed a desktop application and if you want to share the application with other machines all the machines have to install the software for running the application. But in Java EE there is no software needed to install in all the machines. Java EE has the forward capabilities. This is only one simple example. There are lots of differences.
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
In Spanish keyboard it's Ctrl+Shift+º
It seems to change from one keyboard layout to another, so better look for it with Cmd+Shift+P and type "go to bracket" as others suggested.
"AND" does not work in my PHP code.
Server's version maybe?
"&&" works fine.
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>
Here is a client side "sequential guid" solution.
http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate
using System;
using System.Runtime.InteropServices;
namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
public static class Guid
{
/*
Original Reference for Code:
http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html
*/
[DllImport("rpcrt4.dll", SetLastError = true)]
static extern int UuidCreateSequential(out System.Guid guid);
public static System.Guid NewGuid()
{
return CreateSequentialUuid();
}
public static System.Guid CreateSequentialUuid()
{
const int RPC_S_OK = 0;
System.Guid g;
int hr = UuidCreateSequential(out g);
if (hr != RPC_S_OK)
throw new ApplicationException("UuidCreateSequential failed: " + hr);
return g;
}
/*
Text From URL above:
UuidCreateSequential (rpcrt4)
Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
. Summary
Creates a new UUID
C# Signature:
[DllImport("rpcrt4.dll", SetLastError=true)]
static extern int UuidCreateSequential(out Guid guid);
VB Signature:
Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer
User-Defined Types:
None.
Notes:
Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.
CoCreateGuid generates random-looking GUIDs like these:
92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
EBD133A6-6CF3-4ADA-B723-A8177B70D268
B10A35C0-F012-4EC1-9D24-3CC91D2B7122
UuidCreateSequential generates sequential GUIDs like these:
19F287B4-8830-11D9-8BFC-000CF1ADC5B7
19F287B5-8830-11D9-8BFC-000CF1ADC5B7
19F287B6-8830-11D9-8BFC-000CF1ADC5B7
19F287B7-8830-11D9-8BFC-000CF1ADC5B7
19F287B8-8830-11D9-8BFC-000CF1ADC5B7
Here is a summary of the differences in the output of UuidCreateSequential:
The last six bytes reveal your MAC address
Several GUIDs generated in a row are sequential
Tips & Tricks:
Please add some!
Sample Code in C#:
static Guid UuidCreateSequential()
{
const int RPC_S_OK = 0;
Guid g;
int hr = UuidCreateSequential(out g);
if (hr != RPC_S_OK)
throw new ApplicationException
("UuidCreateSequential failed: " + hr);
return g;
}
Sample Code in VB:
Sub Main()
Dim myId As Guid
Dim code As Integer
code = UuidCreateSequential(myId)
If code <> 0 Then
Console.WriteLine("UuidCreateSequential failed: {0}", code)
Else
Console.WriteLine(myId)
End If
End Sub
*/
}
}
Keywords: CreateSequentialUUID SequentialUUID
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
Just..
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 2376921001;
WHILE (i <= 237692200) DO
INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
SET i = i+1;
END WHILE;
END;
//
CALL doWhile();
<?php
session_start();
if($_SESSION['login'] != 'ok')
header('location: /dashboard.php?login=0');
if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
// session inactive more than 10 min
header('location: /logout.php?timeout=1');
}
$_SESSION['last-activity'] = time(); // update last activity time stamp
if(time() - $_SESSION['created'] > 600) {
// session started more than 10 min ago
session_regenerate_id(true); // change session id and invalidate old session
$_SESSION['created'] = time(); // update creation time
}
?>
Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.
For the line below, we have some poorly formed data that can be an NSArray
, an NSDictionary
or (null)
.
NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];
These are the tests that were performed:
NSLog(@"%@", [hits class]);
if ([hits isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
isKindOfClass
worked rather well while isMemberOfClass
didn't.
The RIGHT and WRONG way to set Python 3 as default on a Mac
In this article author discuss three ways of setting default python:
All these ways are working. You decide which is better.
You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:
$('td').click(function(){
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
Check a running example here.
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(key1,value1);
cv.put(key2,value2); /*All values are your updated values, here you are
putting these values in a ContentValues object */
..................
..................
int val=myDB.update(TableName, cv, key_name +"=?", new String[]{value});
if(val>0)
//Successfully Updated
else
//Updation failed
There are new methods added to java.util.Arrays
to convert an array into a Java 8 stream which can then be used for summing etc.
int sum = Arrays.stream(myIntArray)
.sum();
Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.
//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...
int[] result = new int[a.length];
IntStream.range(0, a.length)
.forEach(i -> result[i] = a[i] * b[i]);
EDIT
Commenter @Holger points out you can use the map
method instead of forEach
like this:
int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();
One straight forward way to ensure the object is initialized without any error is to test the object's type instance.
Here is an example :
p = SomeClass(param1=_param1_value)
self.assertTrue(isinstance(p, SomeClass))
Sometimes it's as simple as adding: '-ms-' in front of the style Like -ms-flex-flow: row wrap; to get it to work also.
Just in case the method which name you want to know is a junit test method, then you can use junit TestName rule: https://stackoverflow.com/a/1426730/3076107
tabs: [...data.map((title) { return Text(title);}).toList(), extra_widget],
tabs: data.map((title) { return Text(title);}).toList(),
It's working fine for me
You have to call
setPadding(int left, int top, int right, int bottom)
like so:
your_view.setPadding(0,16,0,0)
What you are trying to use is only the getter.
Android studio shows what padding...()
actually means in java:
padding example
The image shows it only calls getPadding...()
If you want to add a margin to your TextView you will have to LayoutParams:
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
params.setMargins(int left, int top, int right, int bottom)
your_view.layoutParams = params
I was facing the same problem, then in my app.module.ts I updated the file this way,
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
and in the same file (app.module.ts) in my @NgModule imports[]array I wrote this way,
HttpModule,
HttpClientModule
Run the following commands in CMD
choco install powershell
choco upgrade powershell
I believe you are looking for setInterval()
By calling it?
var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx");
Make sure you add a reference to the System.Web assembly.
If you're using the ReSharper plugin, you can do that using the Shift + Alt + L shortcut or navigate via menu as shown.
This error is occur,because the function is not defined. In my case i have called the datepicker function without including the datepicker js file that time I got this error.
For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.
If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.
Go into your project.
install Gradle.
https://docs.gradle.org/current/userguide/installation.html
On a mac: brew install gradle
Then gradle build --stacktrace
There are two solution to solve that problem. First is go to your IIS then click on your apppool, than select integret right click on it and go to advance setting and change identity apppool to local system. This should solve your problem in IIS.
However, if your problem is not solved, then go to web congih just remove integrated security =true
from connection string and just give user id and password.
Then I hope your problem will be solved.
you have to set the tableName you want to your dtimage that is for instance
dtImage.TableName="mydtimage";
if(!ds.Tables.Contains(dtImage.TableName))
ds.Tables.Add(dtImage);
it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage
I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy
And sending just some "ping" message from server to client every x second resolved problem
Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:
$http({
url: '/path/to/your/API',
method: 'POST',
params: {},
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
// TODO when WS success
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'yourfilename.pdf';
document.body.appendChild(a); //create the link "a"
a.click(); //click the link "a"
document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
//TODO when WS error
});
Explanation of the code:
/path/to/your/API
.<a>
.<a>
tag, using the JS click()
function<a>
tag, after its click.There are a lot of good answers, but there is another very minor reason to put this
everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo
resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere()
for the same reason. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
foo
is a variable declared in outer class Hello
.getStringFromSomewhere()
is a method declared in outer class as well.bar
belongs to World
class, and s
is a local variable declared in that method.Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
Here's one generalized from something I just used. I'm posting it since it's a very simple example, and it demonstrates a practical use case along with default arguments:
#include <vector>
template <class T> class Alloc final { /*...*/ };
template <template <class T> class allocator=Alloc> class MyClass final {
public:
std::vector<short,allocator<short>> field0;
std::vector<float,allocator<float>> field1;
};
Trying to answer in simple way:
char * const a; => a is (const) constant (*) pointer of type char {L <- R}. =>( Constant Pointer )
const char * a; => a is (*) pointer to char constant {L <- R}. =>( Pointer to Constant)
Constant Pointer:
pointer is constant !!. i.e, the address it is holding can't be changed. It will be stored in read only memory.
Let's try to change the address of pointer to understand more:
char * const a = &b;
char c;
a = &c; // illegal , you can't change the address. `a` is const at L-value, so can't change. `a` is read-only variable.
It means once constant pointer points some thing it is forever.
pointer a
points only b
.
However you can change the value of b
eg:
char b='a';
char * const a =&b;
printf("\n print a : [%c]\n",*a);
*a = 'c';
printf("\n now print a : [%c]\n",*a);
Pointer to Constant:
Value pointed by the pointer can't be changed.
const char *a;
char b = 'b';
const char * a =&b;
char c;
a=&c; //legal
*a = 'c'; // illegal , *a is pointer to constant can't change!.
I added this in my project just because where I'm using it is a high chance of it being used in loops, in a project hosted online hence I didn't want any crashes if I could manage it. The length fits a column I have. It's C#7
Just a one line:
public static string SubStringN(this string Message, int Len = 499) => !String.IsNullOrEmpty(Message) ? (Message.Length >= Len ? Message.Substring(0, Len) : Message) : "";
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Since everything is an expression, and thus results in a value, you can just use if/else
.
a = if true then 5 else 10
a = if false then 5 else 10
You can see more about expression examples here.
you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
ModeleREP#getTimeSeries()
have to be with @Transient
annotation. That would help.
All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:
<html>
<head>
<script>
function myFunction(){
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>
IEnumerable introduces quite a number of extensions to it which helps you to pass your own delegate and invoking the resultant from the IEnumerable back. Most of them are by nature of type Func
The Func takes an argument T and returns TResult.
In case of
Where - Func : So it takes IEnumerable of T and Returns a bool. The where will ultimately returns the IEnumerable of T's for which Func returns true.
So if you have 1,5,3,6,7 as IEnumerable and you write .where(r => r<5) it will return a new IEnumerable of 1,3.
Any - Func basically is similar in signature but returns true only when any of the criteria returns true for the IEnumerable. In our case, it will return true as there are few elements present with r<5.
Exists - Predicate on the other hand will return true only when any one of the predicate returns true. So in our case if you pass .Exists(r => 5) will return true as 5 is an element present in IEnumerable.
In a Django (1.9.10)/Python 2.7.5 project I have frequent UnicodeDecodeError
exceptions; mainly when I try to feed unicode strings to logging. I made a helper function for arbitrary objects to basically format to 8-bit ascii strings and replacing any characters not in the table to '?'. I think it's not the best solution but since the default encoding is ascii (and i don't want to change it) it will do:
def encode_for_logging(c, encoding='ascii'): if isinstance(c, basestring): return c.encode(encoding, 'replace') elif isinstance(c, Iterable): c_ = [] for v in c: c_.append(encode_for_logging(v, encoding)) return c_ else: return encode_for_logging(unicode(c))`
For a jQuery plugin try this
$.fn.removeClassLike = function(name) {
return this.removeClass(function(index, css) {
return (css.match(new RegExp('\\b(' + name + '\\S*)\\b', 'g')) || []).join(' ');
});
};
or this
$.fn.removeClassLike = function(name) {
var classes = this.attr('class');
if (classes) {
classes = classes.replace(new RegExp('\\b' + name + '\\S*\\s?', 'g'), '').trim();
classes ? this.attr('class', classes) : this.removeAttr('class');
}
return this;
};
Edit: The second approach should be a bit faster because that runs just one regex replace on the whole class string. The first (shorter) uses jQuery's own removeClass method which iterates trough all the existing classnames and tests them for the given regex one by one, so under the hood it does more steps for the same job. However in real life usage the difference is negligible.
From version 4.2, the copyDatabase
is deprecated. From now on we should use: mongodump
and mongorestore
.
Let's say we have a database named: old_name
and we want to rename it to new_name
.
First we have to dump the database:
mongodump --archive="old_name_dump.db" --db=old_name
If you have to authenticate as a user then use:
mongodump -u username --authenticationDatabase admin \
--archive="old_name_dump.db" --db=old_name
Now we have our db dumped as a file named: old_name_dump.db
.
To restore with a new name:
mongorestore --archive="old_name_dump.db" --nsFrom="old_name.*" --nsTo="new_name.*"
Again, if you need to be authenticated add this parameters to the command:
-u username --authenticationDatabase admin
This worked for me:
brew install openssl
cd /usr/local/include
ln -s ../opt/openssl/include/openssl .
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
You can build for source following the official OpenCV tutorial. The crucial part is to set the PYTHON3_EXECUTABLE
, PYTHON_LIBRARY
, PYTHON3_PACKAGES_PATH
and PYTHON3_NUMPY_INCLUDE_DIRS
parameters for python3.6
. Here are all the steps:
Clone the repo
git clone https://github.com/opencv/opencv.git
Create build
directory
cd ~/opencv
mkdir build
cd build
Configure
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local .. \
-D PYTHON_INCLUDE_DIR=/usr/include/python3.6 \
-D PYTHON_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python3.6m \
-D BUILD_NEW_PYTHON_SUPPORT=ON \
-D BUILD_opencv_python3=ON \
-D HAVE_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D PYTHON3_EXECUTABLE=/usr/bin/python3.6 \
-D PYTHON_DEFAULT_EXECUTABLE=/usr/bin/python3.6 \
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
-D PYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages .. \
-D PYTHON3_NUMPY_INCLUDE_DIRS=/home/user/.local/lib/python3.6/site-packages/numpy/core/include/
Build
make -j8
Install libraries
sudo make install
Test
python3
import cv2
If you don't get the error "No module named cv2", then the installation was successful.
Note: If you don't know the path to numpy
for the PYTHON3_NUMPY_INCLUDE_DIRS
parameter, you can find it by executing import numpy
and then numpy.__file__
in a python3 shell.
I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.
If provider & "" <> "" Then
url = url & "&provider=" & provider
End if
This sometimes happen in RStudio. In order to solve it you can attempt to plot to an external window (Windows-only):
windows() ## create window to plot your file
## ... your plotting code here ...
dev.off()
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.
-(void)displayLocalVariable
{
NSString myName = @"ABC";
NSLog(@"My name is = %@", myName);
}
In above method scope of myName variable is limited to displayLocalVariable method, once the method gets finished myName variable which is holding the string "ABC" will get deallocated from the memory.
Now what if we want to hold the myName variable value throughout our view controller life cycle. For this we can create the property named as username which will have Strong reference to the variable myName(see self.username = myName;
in below code), as below,
@interface LoginViewController ()
@property(nonatomic,strong) NSString* username;
@property(nonatomic,weak) NSString* dummyName;
- (void)displayLocalVariable;
@end
@implementation LoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
[self displayLocalVariable];
}
- (void)displayLocalVariable
{
NSString myName = @"ABC";
NSLog(@"My name is = %@", myName);
self.username = myName;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Now in above code you can see myName has been assigned to self.username and self.username is having a strong reference(as we declared in interface using @property) to myName(indirectly it's having Strong reference to "ABC" string). Hence String myName will not get deallocated from memory till self.username is alive.
Now consider assigning myName to dummyName which is a Weak reference, self.dummyName = myName; Unlike Strong reference Weak will hold the myName only till there is Strong reference to myName. See below code to understand Weak reference,
-(void)displayLocalVariable
{
NSString myName = @"ABC";
NSLog(@"My name is = %@", myName);
self.dummyName = myName;
}
In above code there is Weak reference to myName(i.e. self.dummyName is having Weak reference to myName) but there is no Strong reference to myName, hence self.dummyName will not be able to hold the myName value.
Now again consider the below code,
-(void)displayLocalVariable
{
NSString myName = @"ABC";
NSLog(@"My name is = %@", myName);
self.username = myName;
self.dummyName = myName;
}
In above code self.username has a Strong reference to myName, hence self.dummyName will now have a value of myName even after method ends since myName has a Strong reference associated with it.
Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated retain count reaches to 0.
Hope this helps.
As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.
using
directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.
The following example works because the types Foo
and Bar
are both in the same global namespace, Outer
.
Presume the code file Foo.cs:
namespace Outer.Inner
{
class Foo { }
}
And Bar.cs:
namespace Outer
{
using Outer.Inner;
class Bar
{
public Foo foo;
}
}
That may omit the outer namespace in the using
directive, for short:
namespace Outer
{
using Inner;
class Bar
{
public Foo foo;
}
}
Try using
DateTime.ToOADate()
And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.
Hope this helps.
if you want same string output then try below else use without double quotes for proper output
$str = '20130814';
echo date('"F Y"', strtotime($str));
//output : "August 2013"
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
Historically, you would send an AJAX request in the beforeunload
function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
Later came navigator.sendBeacon()
. By using the sendBeacon()
method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.
Unless you are targeting only desktop users, sendBeacon()
should not be used with unload
or beforeunload
since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange
event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.
Here is an example of its usage:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState == 'hidden') {
navigator.sendBeacon("/log.php", analyticsData);
}
});
When the user returns to the page, document.visibilityState
will change to 'visible'
, so you can also handle that event as well.
sendBeacon()
is supported in:
It is NOT currently supported in:
Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
Update:
It might be worth mentioning that sendBeacon()
only sends POST
requests. If you need to send a request using any other method, an alternative would be to use the fetch API
with the keepalive
flag set to true
, which causes it to behave the same way as sendBeacon()
. Browser support for the fetch API is about the same.
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'no-cors',
keepalive: true,
})
Others have answered that export makes the variable available to subshells, and that is correct but merely a side effect. When you export a variable, it puts that variable in the environment of the current shell (ie the shell calls putenv(3)
or setenv(3)
).
The environment of a process is inherited across exec, making the variable visible in subshells.
Edit (with 5 year's perspective): this is a silly answer. The purpose of 'export' is to make variables "be in the environment of subsequently executed commands", whether those commands be subshells or subprocesses. A naive implementation would be to simply put the variable in the environment of the shell, but this would make it impossible to implement export -p
.
I was able to do it with justify-content: space-between
on the container
I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local
, which is executed about last in init phase.
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
By default you use UNICODE so I suggest using faulty's method
int bar = int.Parse(foo.ToString());
Even though the numeric values under are the same for digits and basic Latin chars.
Slightly off topic:
I found this question while looking for a way to format a number as currency, like so:
$100
($50) # negative numbers without '-' and in parens
I ended up doing:
{% if var >= 0 %} ${{ var|stringformat:"d" }}
{% elif var < 0 %} $({{ var|stringformat:"d"|cut:"-" }})
{% endif %}
You could also do, e.g. {{ var|stringformat:"1.2f"|cut:"-" }}
to display as $50.00
(with 2 decimal places if that's what you want.
Perhaps slightly on the hacky side, but maybe someone else will find it useful.
use this code in manifest.xml
<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>
here is how from @ https://productforums.google.com/forum/#!topic/drive/yU_yF9SI_z0/discussion
1- upload ur image
2- right click and chose "get sharable link"
3- copy the link which should look like
4-change the open?
to uc?
and use it like
<img src="https://drive.google.com/uc?id=xxxxx">
http:
or https:
when referencing anything from the web to avoid any issues with ur server.The following query can be used to detemine tablespace and other params:
select df.tablespace_name "Tablespace",
totalusedspace "Used MB",
(df.totalspace - tu.totalusedspace) "Free MB",
df.totalspace "Total MB",
round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
from (select tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from dba_data_files
group by tablespace_name) df,
(select round(sum(bytes)/(1024*1024)) totalusedspace,
tablespace_name
from dba_segments
group by tablespace_name) tu
where df.tablespace_name = tu.tablespace_name
and df.totalspace <> 0;
Source: https://community.oracle.com/message/1832920
For your case if you want to know the partition name and it's size just run this query:
select owner,
segment_name,
partition_name,
segment_type,
bytes / 1024/1024 "MB"
from dba_segments
where owner = <owner_name>;
Way 1 :
You can use Underscore.js
. Import underscore first.
import * as _ from 'underscore';
let SortedObjs = _.sortBy(objs, 'last_nom');
Way 2 : Use compare function.
function compare(first, second) {
if (first.last_nom < second.last_nom)
return -1;
if (first.last_nom > second.last_nom)
return 1;
return 0;
}
objs.sort(compare);
If you want to count all files in the directory - including files in subdirectories, the most pythonic way is:
import os
file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)
We use sum that is faster than explicitly adding the file counts (timings pending)
If you are stuck with a machine where you don't have root access, then it is better to deal with a custom Python installation.
The Anaconda installation worked like a charm:
After installation,
[bash]$ /xxx/devTools/python/anaconda/bin/pip list --format=columns | grep numpy
numpy 1.13.3 numpydoc 0.7.0
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[]
or List
. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.
EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.
Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.
(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)
To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.