In the latest Chrome as of 10/26/2018, the top-rated answer no longer works, here's how it's done:
I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):
UPDATE table SET phone_num = concat('0', phone_num)
I just concated 0 in front of the phone_num
.
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
null and undefined are nothingness, that is,
var a;
var b = null;
Here a
and b
do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
This is kind of a hack, but does seem to work. Below are the steps and an example of modifying a table type. One note is the sp_refreshsqlmodule will fail if the change you made to the table type is a breaking change to that object, typically a procedure.
sp_rename
to rename the table type, I typically just add z to
the beginning of the name.sp_refreshsqlmodule
on it.EXEC sys.sp_rename 'dbo.MyTableType', 'zMyTableType';
GO
CREATE TYPE dbo.MyTableType AS TABLE(
Id INT NOT NULL,
Name VARCHAR(255) NOT NULL
);
GO
DECLARE @Name NVARCHAR(776);
DECLARE REF_CURSOR CURSOR FOR
SELECT referencing_schema_name + '.' + referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.MyTableType', 'TYPE');
OPEN REF_CURSOR;
FETCH NEXT FROM REF_CURSOR INTO @Name;
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC sys.sp_refreshsqlmodule @name = @Name;
FETCH NEXT FROM REF_CURSOR INTO @Name;
END;
CLOSE REF_CURSOR;
DEALLOCATE REF_CURSOR;
GO
DROP TYPE dbo.zMyTableType;
GO
WARNING:
This can be destructive to your database, so you'll want to test this on a development environment first.
You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted
Example:
Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");
JSONObject json= new JSONObject(map);
String result= json.toString();
System.out.print(result);
result:
{'myNumber':100, 'myString':'String'}
Your can also get key from it like
System.out.print(json.get("myNumber"));
result:
100
I recommend you to look at the adbroker package of the oVirt project. It uses Spring-Ldap and the Krb5 JAAS Login module (with GSSAPI) in order to authenticate using Kerberos against Ldap servers (Active-Directory, ipa, rhds, Tivoli-DS). Look for the code at engine\backend\manager\modules\bll\src\main\java\org\ovirt\engine\core\bll\adbroker
You can use git to clone the repository or browse using the gerrit link
Return function is not working in all the cases. I tried this:
<button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>
It didnt work for me.
I tried to return false inside the function and it worked for me.
function Reset()
{
.
.
.
return false;
}
var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"
This will enable appending to file using StreamWriter
using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}
This is default mode, not append to file and create a new file.
using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}
Anyhow if you want to check if the file exists and then do other things,you can use
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{...}
The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.
select * from ttt.table_name;
or if table name in all attached databases is unique
select * from my_unique_table_name;
But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential
normally you would use sqlite-command-line in a script
You need a special type of function known as a table valued function. Below is a somewhat long-winded example that builds a date dimension for a data warehouse. Note the returns
clause that defines a table structure. You can insert anything into the table variable (@DateHierarchy
in this case) that you want, including building a temporary table and copying the contents into it.
if object_id ('ods.uf_DateHierarchy') is not null
drop function ods.uf_DateHierarchy
go
create function ods.uf_DateHierarchy (
@DateFrom datetime
,@DateTo datetime
) returns @DateHierarchy table (
DateKey datetime
,DisplayDate varchar (20)
,SemanticDate datetime
,MonthKey int
,DisplayMonth varchar (10)
,FirstDayOfMonth datetime
,QuarterKey int
,DisplayQuarter varchar (10)
,FirstDayOfQuarter datetime
,YearKey int
,DisplayYear varchar (10)
,FirstDayOfYear datetime
) as begin
declare @year int
,@quarter int
,@month int
,@day int
,@m1ofqtr int
,@DisplayDate varchar (20)
,@DisplayQuarter varchar (10)
,@DisplayMonth varchar (10)
,@DisplayYear varchar (10)
,@today datetime
,@MonthKey int
,@QuarterKey int
,@YearKey int
,@SemanticDate datetime
,@FirstOfMonth datetime
,@FirstOfQuarter datetime
,@FirstOfYear datetime
,@MStr varchar (2)
,@QStr varchar (2)
,@Ystr varchar (4)
,@DStr varchar (2)
,@DateStr varchar (10)
-- === Previous ===================================================
-- Special placeholder date of 1/1/1800 used to denote 'previous'
-- so that naive date calculations sort and compare in a sensible
-- order.
--
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'1800-01-01'
,'Previous'
,'1800-01-01'
,180001
,'Prev'
,'1800-01-01'
,18001
,'Prev'
,'1800-01-01'
,1800
,'Prev'
,'1800-01-01'
)
-- === Calendar Dates =============================================
-- These are generated from the date range specified in the input
-- parameters.
--
set @today = @Datefrom
while @today <= @DateTo begin
set @year = datepart (yyyy, @today)
set @month = datepart (mm, @today)
set @day = datepart (dd, @today)
set @quarter = case when @month in (1,2,3) then 1
when @month in (4,5,6) then 2
when @month in (7,8,9) then 3
when @month in (10,11,12) then 4
end
set @m1ofqtr = @quarter * 3 - 2
set @DisplayDate = left (convert (varchar, @today, 113), 11)
set @SemanticDate = @today
set @MonthKey = @year * 100 + @month
set @DisplayMonth = substring (convert (varchar, @today, 113), 4, 8)
set @Mstr = right ('0' + convert (varchar, @month), 2)
set @Dstr = right ('0' + convert (varchar, @day), 2)
set @Ystr = convert (varchar, @year)
set @DateStr = @Ystr + '-' + @Mstr + '-01'
set @FirstOfMonth = convert (datetime, @DateStr, 120)
set @QuarterKey = @year * 10 + @quarter
set @DisplayQuarter = 'Q' + convert (varchar, @quarter) + ' ' +
convert (varchar, @year)
set @QStr = right ('0' + convert (varchar, @m1ofqtr), 2)
set @DateStr = @Ystr + '-' + @Qstr + '-01'
set @FirstOfQuarter = convert (datetime, @DateStr, 120)
set @YearKey = @year
set @DisplayYear = convert (varchar, @year)
set @DateStr = @Ystr + '-01-01'
set @FirstOfYear = convert (datetime, @DateStr)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
@today
,@DisplayDate
,@SemanticDate
,@Monthkey
,@DisplayMonth
,@FirstOfMonth
,@QuarterKey
,@DisplayQuarter
,@FirstOfQuarter
,@YearKey
,@DisplayYear
,@FirstOfYear
)
set @today = dateadd (dd, 1, @today)
end
-- === Specials ===================================================
-- 'Ongoing', 'Error' and 'Not Recorded' set two years apart to
-- avoid accidental collisions on 'Next Year' calculations.
--
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9000-01-01'
,'Ongoing'
,'9000-01-01'
,900001
,'Ong.'
,'9000-01-01'
,90001
,'Ong.'
,'9000-01-01'
,9000
,'Ong.'
,'9000-01-01'
)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9100-01-01'
,'Error'
,null
,910001
,'Error'
,null
,91001
,'Error'
,null
,9100
,'Err'
,null
)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9200-01-01'
,'Not Recorded'
,null
,920001
,'N/R'
,null
,92001
,'N/R'
,null
,9200
,'N/R'
,null
)
return
end
go
NSLocalizedString()
(and variants thereof) access the "AppleLanguages" key in NSUserDefaults
to determine what the user's settings for preferred languages are. This returns an array of language codes, with the first one being the one set by the user for their phone, and the subsequent ones used as fallbacks if a resource is not available in the preferred language. (on the desktop, the user can specify multiple languages with a custom ordering in System Preferences)
You can override the global setting for your own application if you wish by using the setObject:forKey: method to set your own language list. This will take precedence over the globally set value and be returned to any code in your application that is performing localization. The code for this would look something like:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
This would make German the preferred language for your application, with English and French as fallbacks. You would want to call this sometime early in your application's startup. You can read more about language/locale preferences here: Internationalization Programming Topics: Getting the Current Language and Locale
false != 'false'
For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:
var result = ValidateForm();
if(result == false) {
...
}
I added a new project to my solution and started getting this.
The reason? The project I brought in was targeting a different .NET framework (4.6 and my other two were 4.5.2).
If all the above doesn't work. Try to update your Android studio version. Steps: 1. In Android Studio, select File > Settings (or Android Studio > Preference on Mac). 2. In the left pane, select Appearance & Behavior > System Settings > Updates. 3. Be sure that Automatically check for updates is checked, and then select a channel from the drop-down list. 4. Click OK.
I don't know if I am late or out of scope but in my opinion I could do it like:
String orgName = "anyParamValue";
Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");
q.setParameter("orgName", orgName);
The listings package is quite nice and very flexible (e.g. different sizes for comments and code).
I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !
Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.
Went a step further...I thought this was cool...When I instead do this in Expts.py:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.
If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.
Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
Also check this answer from here: Cannot manually edit applicationhost.config
The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.
So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.
How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.
First of all i will say Nice Thaught to develop such app.
Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.
Well i am not sure about it but still have give some view so you can get idea of it.
All the Best. :))
I suggest a custom alias on you .gitconfig
.
You have to way to do:
1) With git command:
git config --global alias.check-file <command>
2) Editing ~/.gitconfig
and add this line on alias section:
[alias]
check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi; }; f"
Once launched command (1) or saved file (2), on your workspace you can test it:
$ git check-file
$ Filename missing
$ git check-file README.md
$ File tracked
$ git check-file foo
$ File not tracked
A quick example:
List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });
// To iterate over it.
foreach (List<string> subList in myList)
{
foreach (string item in subList)
{
Console.WriteLine(item);
}
}
Is that what you were looking for? Or are you trying to create a new class
that extends List<T>
that has a member that is a `List'?
I've found the following "cheat" to work very neatly and error-free
> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary
Et voila!
This solution works for me since OS 4.4. To make it work on all devices I added a workaround for older devices. This ensures that always the safest solution is used.
Manifest.xml:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml:
<paths>
<files-path name="app_directory" path="directory/"/>
</paths>
Java:
public static void sendFile(Context context) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String dirpath = context.getFilesDir() + File.separator + "directory";
File file = new File(dirpath + File.separator + "file.txt");
Uri uri = FileProvider.getUriForFile(context, "com.package.name.fileprovider", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Workaround for Android bug.
// grantUriPermission also needed for KITKAT,
// see https://code.google.com/p/android/issues/detail?id=76683
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, attachmentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
}
}
public static void revokeFileReadPermission(Context context) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
String dirpath = context.getFilesDir() + File.separator + "directory";
File file = new File(dirpath + File.separator + "file.txt");
Uri uri = FileProvider.getUriForFile(context, "com.package.name.fileprovider", file);
context.revokeUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
The permission is revoked with revokeFileReadPermission() in the onResume and onDestroy() methods of the Fragment or the Activity.
In ActivityOne,
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("data", somedata);
startActivity(intent);
In ActivityTwo,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[ _x000D_
[ _x000D_
{ _x000D_
"b":"0.110547334",_x000D_
"cost":"0.000000",_x000D_
"w":"1.998889"_x000D_
}_x000D_
],_x000D_
[ _x000D_
{ _x000D_
"x":0,_x000D_
"y":0_x000D_
},_x000D_
{ _x000D_
"x":1,_x000D_
"y":2_x000D_
},_x000D_
{ _x000D_
"x":2,_x000D_
"y":4_x000D_
},_x000D_
{ _x000D_
"x":3,_x000D_
"y":6_x000D_
},_x000D_
{ _x000D_
"x":4,_x000D_
"y":8_x000D_
},_x000D_
{ _x000D_
"x":5,_x000D_
"y":10_x000D_
},_x000D_
{ _x000D_
"x":6,_x000D_
"y":12_x000D_
},_x000D_
{ _x000D_
"x":7,_x000D_
"y":14_x000D_
},_x000D_
{ _x000D_
"x":8,_x000D_
"y":16_x000D_
},_x000D_
{ _x000D_
"x":9,_x000D_
"y":18_x000D_
},_x000D_
{ _x000D_
"x":10,_x000D_
"y":20_x000D_
},_x000D_
{ _x000D_
"x":11,_x000D_
"y":22_x000D_
},_x000D_
{ _x000D_
"x":12,_x000D_
"y":24_x000D_
},_x000D_
{ _x000D_
"x":13,_x000D_
"y":26_x000D_
},_x000D_
{ _x000D_
"x":14,_x000D_
"y":28_x000D_
},_x000D_
{ _x000D_
"x":15,_x000D_
"y":30_x000D_
},_x000D_
{ _x000D_
"x":16,_x000D_
"y":32_x000D_
},_x000D_
{ _x000D_
"x":17,_x000D_
"y":34_x000D_
},_x000D_
{ _x000D_
"x":18,_x000D_
"y":36_x000D_
},_x000D_
{ _x000D_
"x":19,_x000D_
"y":38_x000D_
},_x000D_
{ _x000D_
"x":20,_x000D_
"y":40_x000D_
},_x000D_
{ _x000D_
"x":21,_x000D_
"y":42_x000D_
},_x000D_
{ _x000D_
"x":22,_x000D_
"y":44_x000D_
},_x000D_
{ _x000D_
"x":23,_x000D_
"y":46_x000D_
},_x000D_
{ _x000D_
"x":24,_x000D_
"y":48_x000D_
},_x000D_
{ _x000D_
"x":25,_x000D_
"y":50_x000D_
},_x000D_
{ _x000D_
"x":26,_x000D_
"y":52_x000D_
},_x000D_
{ _x000D_
"x":27,_x000D_
"y":54_x000D_
},_x000D_
{ _x000D_
"x":28,_x000D_
"y":56_x000D_
},_x000D_
{ _x000D_
"x":29,_x000D_
"y":58_x000D_
},_x000D_
{ _x000D_
"x":30,_x000D_
"y":60_x000D_
},_x000D_
{ _x000D_
"x":31,_x000D_
"y":62_x000D_
},_x000D_
{ _x000D_
"x":32,_x000D_
"y":64_x000D_
},_x000D_
{ _x000D_
"x":33,_x000D_
"y":66_x000D_
},_x000D_
{ _x000D_
"x":34,_x000D_
"y":68_x000D_
},_x000D_
{ _x000D_
"x":35,_x000D_
"y":70_x000D_
},_x000D_
{ _x000D_
"x":36,_x000D_
"y":72_x000D_
},_x000D_
{ _x000D_
"x":37,_x000D_
"y":74_x000D_
},_x000D_
{ _x000D_
"x":38,_x000D_
"y":76_x000D_
},_x000D_
{ _x000D_
"x":39,_x000D_
"y":78_x000D_
},_x000D_
{ _x000D_
"x":40,_x000D_
"y":80_x000D_
},_x000D_
{ _x000D_
"x":41,_x000D_
"y":82_x000D_
},_x000D_
{ _x000D_
"x":42,_x000D_
"y":84_x000D_
},_x000D_
{ _x000D_
"x":43,_x000D_
"y":86_x000D_
},_x000D_
{ _x000D_
"x":44,_x000D_
"y":88_x000D_
},_x000D_
{ _x000D_
"x":45,_x000D_
"y":90_x000D_
},_x000D_
{ _x000D_
"x":46,_x000D_
"y":92_x000D_
},_x000D_
{ _x000D_
"x":47,_x000D_
"y":94_x000D_
},_x000D_
{ _x000D_
"x":48,_x000D_
"y":96_x000D_
},_x000D_
{ _x000D_
"x":49,_x000D_
"y":98_x000D_
},_x000D_
{ _x000D_
"x":50,_x000D_
"y":100_x000D_
},_x000D_
{ _x000D_
"x":51,_x000D_
"y":102_x000D_
},_x000D_
{ _x000D_
"x":52,_x000D_
"y":104_x000D_
},_x000D_
{ _x000D_
"x":53,_x000D_
"y":106_x000D_
},_x000D_
{ _x000D_
"x":54,_x000D_
"y":108_x000D_
},_x000D_
{ _x000D_
"x":55,_x000D_
"y":110_x000D_
},_x000D_
{ _x000D_
"x":56,_x000D_
"y":112_x000D_
},_x000D_
{ _x000D_
"x":57,_x000D_
"y":114_x000D_
},_x000D_
{ _x000D_
"x":58,_x000D_
"y":116_x000D_
},_x000D_
{ _x000D_
"x":59,_x000D_
"y":118_x000D_
},_x000D_
{ _x000D_
"x":60,_x000D_
"y":120_x000D_
},_x000D_
{ _x000D_
"x":61,_x000D_
"y":122_x000D_
},_x000D_
{ _x000D_
"x":62,_x000D_
"y":124_x000D_
},_x000D_
{ _x000D_
"x":63,_x000D_
"y":126_x000D_
},_x000D_
{ _x000D_
"x":64,_x000D_
"y":128_x000D_
},_x000D_
{ _x000D_
"x":65,_x000D_
"y":130_x000D_
},_x000D_
{ _x000D_
"x":66,_x000D_
"y":132_x000D_
},_x000D_
{ _x000D_
"x":67,_x000D_
"y":134_x000D_
},_x000D_
{ _x000D_
"x":68,_x000D_
"y":136_x000D_
},_x000D_
{ _x000D_
"x":69,_x000D_
"y":138_x000D_
},_x000D_
{ _x000D_
"x":70,_x000D_
"y":140_x000D_
},_x000D_
{ _x000D_
"x":71,_x000D_
"y":142_x000D_
},_x000D_
{ _x000D_
"x":72,_x000D_
"y":144_x000D_
},_x000D_
{ _x000D_
"x":73,_x000D_
"y":146_x000D_
},_x000D_
{ _x000D_
"x":74,_x000D_
"y":148_x000D_
},_x000D_
{ _x000D_
"x":75,_x000D_
"y":150_x000D_
},_x000D_
{ _x000D_
"x":76,_x000D_
"y":152_x000D_
},_x000D_
{ _x000D_
"x":77,_x000D_
"y":154_x000D_
},_x000D_
{ _x000D_
"x":78,_x000D_
"y":156_x000D_
},_x000D_
{ _x000D_
"x":79,_x000D_
"y":158_x000D_
},_x000D_
{ _x000D_
"x":80,_x000D_
"y":160_x000D_
},_x000D_
{ _x000D_
"x":81,_x000D_
"y":162_x000D_
},_x000D_
{ _x000D_
"x":82,_x000D_
"y":164_x000D_
},_x000D_
{ _x000D_
"x":83,_x000D_
"y":166_x000D_
},_x000D_
{ _x000D_
"x":84,_x000D_
"y":168_x000D_
},_x000D_
{ _x000D_
"x":85,_x000D_
"y":170_x000D_
},_x000D_
{ _x000D_
"x":86,_x000D_
"y":172_x000D_
},_x000D_
{ _x000D_
"x":87,_x000D_
"y":174_x000D_
},_x000D_
{ _x000D_
"x":88,_x000D_
"y":176_x000D_
},_x000D_
{ _x000D_
"x":89,_x000D_
"y":178_x000D_
},_x000D_
{ _x000D_
"x":90,_x000D_
"y":180_x000D_
},_x000D_
{ _x000D_
"x":91,_x000D_
"y":182_x000D_
},_x000D_
{ _x000D_
"x":92,_x000D_
"y":184_x000D_
},_x000D_
{ _x000D_
"x":93,_x000D_
"y":186_x000D_
},_x000D_
{ _x000D_
"x":94,_x000D_
"y":188_x000D_
},_x000D_
{ _x000D_
"x":95,_x000D_
"y":190_x000D_
},_x000D_
{ _x000D_
"x":96,_x000D_
"y":192_x000D_
},_x000D_
{ _x000D_
"x":97,_x000D_
"y":194_x000D_
},_x000D_
{ _x000D_
"x":98,_x000D_
"y":196_x000D_
},_x000D_
{ _x000D_
"x":99,_x000D_
"y":198_x000D_
}_x000D_
]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
console.info(ch);_x000D_
_x000D_
scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
code sample - https://codepen.io/nagasai/pen/GGzZVB
You can use FontAwesome "content" values and apply as follow by css. These apply "chevron right/left" icons.
.custom-slick .slick-prev:before {
content: "?";
font-family: 'FontAwesome';
font-size: 22px;
}
.custom-slick .slick-next:before {
content: "?";
font-family: 'FontAwesome';
font-size: 22px;
}
parameter?: type
is a shorthand for parameter: type | undefined
import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')
this requires Python Imaging Library
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
Actually you can do it with sink()
:
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
hence do:
file.show("outfile.txt")
# hello
# world
Check this code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IllegalAccessException {
String username ;
String password;
String yes_0r_no;
String scann;
String passscan;
Scanner scan = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Username:");
username = name.next().toLowerCase();
Scanner pass = new Scanner(System.in);
System.out.println("Password:");
password = pass.next().toLowerCase();
System.out.println("You are logged in");
Scanner ask = new Scanner(System.in);
System.out.println("Do you want to check this or not(yes or no) :");
yes_0r_no = ask.next().toLowerCase();
while (true){
if (yes_0r_no.equals("yes")){
System.out.println("Username:");
scann = scan.next().toLowerCase();
if (scann == username) {
continue;
}
System.out.println("Password");
passscan = scanner.next().toLowerCase();
if (passscan.equals(password)) {
System.out.println("You are logged in");
break;
}if (!password.equals(passscan)) {
throw new IllegalAccessException();
}
}
if (yes_0r_no.equals("no"))
break ;
}
}
}
The best solution I found when dealing with Typescript classes and json objects: add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $.extend( this, jsonData). $.extend allows keeping the javascript prototypes while adding the json object's properties.
export class Foo
{
Name: string;
getName(): string { return this.Name };
constructor( jsonFoo: any )
{
$.extend( this, jsonFoo);
}
}
In your ajax callback, translate your jsons in a your typescript object like this:
onNewFoo( jsonFoos : any[] )
{
let receviedFoos = $.map( jsonFoos, (json) => { return new Foo( json ); } );
// then call a method:
let firstFooName = receviedFoos[0].GetName();
}
If you don't add the constructor, juste call in your ajax callback:
let newFoo = new Foo();
$.extend( newFoo, jsonData);
let name = newFoo.GetName()
...but the constructor will be useful if you want to convert the children json object too. See my detailed answer here.
Depending on your version of linux it may be called mail. To quote @David above:
mail -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt
or also:
cat message.txt | mail -s "Backup" -a mysqldbbackup.sql [email protected]
I know it's late but still
If by any chance you run into windows saved text file with \r\n
instead of \n
, you might get confused by the output if your command has sth after read line as argument. So do remove \r
, for example:
cat file | tr -d '\r' | xargs -L 1 -i echo do_sth_with_{}_as_line
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
Yes, you can detect by this method in appDelegate:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
/* your Code*/
}
For local Notification:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
/* your Code*/
}
Yesterday I made this class. Take it, it's for all API Levels
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;
import de.lochmann.nsafirewall.R;
public class MyClipboardManager {
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText(
context.getResources().getString(
R.string.message), text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
@SuppressLint("NewApi")
public String readFromClipboard(Context context) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
} else {
ClipboardManager clipboard = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
// Gets a content resolver instance
ContentResolver cr = context.getContentResolver();
// Gets the clipboard data from the clipboard
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
String text = null;
String title = null;
// Gets the first item from the clipboard data
ClipData.Item item = clip.getItemAt(0);
// Tries to get the item's contents as a URI pointing to a note
Uri uri = item.getUri();
// If the contents of the clipboard wasn't a reference to a
// note, then
// this converts whatever it is to text.
if (text == null) {
text = coerceToText(context, item).toString();
}
return text;
}
}
return "";
}
@SuppressLint("NewApi")
public CharSequence coerceToText(Context context, ClipData.Item item) {
// If this Item has an explicit textual value, simply return that.
CharSequence text = item.getText();
if (text != null) {
return text;
}
// If this Item has a URI value, try using that.
Uri uri = item.getUri();
if (uri != null) {
// First see if the URI can be opened as a plain text stream
// (of any sub-type). If so, this is the best textual
// representation for it.
FileInputStream stream = null;
try {
// Ask for a stream of the desired type.
AssetFileDescriptor descr = context.getContentResolver()
.openTypedAssetFileDescriptor(uri, "text/*", null);
stream = descr.createInputStream();
InputStreamReader reader = new InputStreamReader(stream,
"UTF-8");
// Got it... copy the stream into a local string and return it.
StringBuilder builder = new StringBuilder(128);
char[] buffer = new char[8192];
int len;
while ((len = reader.read(buffer)) > 0) {
builder.append(buffer, 0, len);
}
return builder.toString();
} catch (FileNotFoundException e) {
// Unable to open content URI as text... not really an
// error, just something to ignore.
} catch (IOException e) {
// Something bad has happened.
Log.w("ClippedData", "Failure loading text", e);
return e.toString();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
// If we couldn't open the URI as a stream, then the URI itself
// probably serves fairly well as a textual representation.
return uri.toString();
}
// Finally, if all we have is an Intent, then we can just turn that
// into text. Not the most user-friendly thing, but it's something.
Intent intent = item.getIntent();
if (intent != null) {
return intent.toUri(Intent.URI_INTENT_SCHEME);
}
// Shouldn't get here, but just in case...
return "";
}
}
Checkout the branch for which you would like to squash all the commits into one commit. Let's say it's called feature_branch
.
git checkout feature_branch
Do a soft reset of your origin/feature_branch
with your local main
branch (depending on your needs, you can reset with origin/main as well). This will reset all the extra commits in your feature_branch
, but without changing any of your file changes locally.
git reset --soft main
Add all of the changes in your git repo directory, to the new commit that is going to be created. And commit the same with a message.
git add -A && git commit -m "commit message goes here"
I am using Windows 10 and korean version of Visual studio. I wanted to change from korean to english. I downloaded the english language pack but the error message appeared as "compatibility mode is on..." the only solution to this issue is to rename the Language pack setup file name with its original name, that is to say vs_langpack.exe . And boom the issue is solved.
Hope it is helpful.
Thanks.
A funny way to do this is
>>> np.array([True, False, False]) + 0
np.array([1, 0, 0])
It's greatly simple than you think. When the button is focussed, apply the outline
property, like this:
button:focus {
outline: 0 !important;
}
But when I use none
value, it doesn't work for me.
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
From wiki.answers.com:
The term declaration means (in C) that you are telling the compiler about type, size and in case of function declaration, type and size of its parameters of any variable, or user defined type or function in your program. No space is reserved in memory for any variable in case of declaration. However compiler knows how much space to reserve in case a variable of this type is created.
for example, following are all declarations:
extern int a;
struct _tagExample { int a; int b; };
int myFunc (int a, int b);
Definition on the other hand means that in additions to all the things that declaration does, space is also reserved in memory. You can say "DEFINITION = DECLARATION + SPACE RESERVATION" following are examples of definition:
int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;
see Answers.
Another:
>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
... print(fmt%d)
...
0: 10
1: 11
2: 12
Yet another form:
>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)
That method is nice since the individual elements in tuples produced by enumerate can be modified such as:
>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
...
1^3: 1
2^4: 16
3^5: 243
Of course, don't forget you can get a slice from this like so:
>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
...
1: 11
ALTER TABLE `table_name` AUTO_INCREMENT=1
Try,
apt-cache policy libgtk2.0-0 libgtk-3-0
or,
dpkg -l libgtk2.0-0 libgtk-3-0
Try this :
import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
print 'No Data!'
else:
for rows in json_object['team']:
print 'Team ID:' + rows['team_id']
print 'Team Name:' + rows['team_name']
print 'Team URL:' + rows['team_icon_url']
The Replace string function will do that.
You can try this:
<a href="link.html">
<input type="button" value="Visit Page" />
</a>
This will create button inside a link and it works on any browser
I tried the solution xcode-select --install
but it don't help me, I update from Sierra to High and happened this, my solution:
sudo xcode-select --reset
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
It's calling the files included in that particular bundle which is declared inside the BundleConfig
class in the App_Start
folder.
In that particular case The call to @Styles.Render("~/Content/css")
is calling "~/Content/site.css".
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
~mypage.aspx?strID=x&strName=y&strDate=z
For swift 2.0 and above do this
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.userInteractionEnabled = true
}
func tappedMe()
{
print("Tapped on Image")
}
Use a TreeMap with a custom comparator.
class MyComparator implements Comparator<String>
{
public int compare(String o1,String o2)
{
// Your logic for comparing the key strings
}
}
TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());
As you add new elements, they will be automatically sorted.
In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.
Simplest ways to mock an HttpServletRequest
:
Create an anonymous subclass:
HttpServletRequest mock = new HttpServletRequest ()
{
private final Map<String, String[]> params = /* whatever */
public Map<String, String[]> getParameterMap()
{
return params;
}
public String getParameter(String name)
{
String[] matches = params.get(name);
if (matches == null || matches.length == 0) return null;
return matches[0];
}
// TODO *many* methods to implement here
};
Use jMock, Mockito, or some other general-purpose mocking framework:
HttpServletRequest mock = context.mock(HttpServletRequest.class); // jMock
HttpServletRequest mock2 = Mockito.mock(HttpServletRequest.class); // Mockito
Use HttpUnit's ServletUnit and don't mock the request at all.
If you are using phpmyadmin then this feature is already there.
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
For floating point numbers there is a standard (IEEE754): floats are 32 bit and doubles are 64. This is a hardware standard, not a C++ standard, so compilers could theoretically define float and double to some other size, but in practice I've never seen an architecture that used anything different.
I found this article
/// <summary>
/// Creates a new Image containing the same image only rotated
/// </summary>
/// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
/// <param name=""offset"">The position to rotate from.
/// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
/// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
/// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/">
/// is null.</see>
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
//create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
//Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
//rotate the image
g.RotateTransform(angle);
//move the image back
g.TranslateTransform(-offset.X, -offset.Y);
//draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
The last part of the error message you quoted states:
...with ("checkPermission") or explicitly handle a potential "SecurityException"
A much quicker/simpler way of checking if you have permissions is to surround your code with try { ... } catch (SecurityException e) { [insert error handling code here] }
. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.
Well, if you have to read file line by line to work with each line, you can use
with open('Path/to/file', 'r') as f:
s = f.readline()
while s:
# do whatever you want to
s = f.readline()
Or even better way:
with open('Path/to/file') as f:
for line in f:
# do whatever you want to
=IF(A2="Y","Male",IF(A2="N","Female",""))
Another case that could cause this error is
>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index
Using the actual shape will fix it.
>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>
I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.
EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:
* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor
G'day,
As a corollary to this question, communicate your interpretations of the log levels and make sure that all people on a project are aligned in their interpretation of the levels.
It's painful to see a vast variety of log messages where the severities and the selected log levels are inconsistent.
Provide examples if possible of the different logging levels. And be consistent in the info to be logged in a message.
HTH
I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.
It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD
I also add a small interface, hope someone else find it useful!
I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/
Zookeeper is just a Java process and when you start a Zookeeper instance it runs a org.apache.zookeeper.server.quorum.QuorumPeerMain
class. So you can check for a running Zookeeper like this:
jps -l | grep zookeeper
or even like this:
jps | grep Quorum
upd:
regarding this: will hostname be the hostname of my box??
- the answer is yes.
A very simple way to read an external script into an sqlite database in python is using executescript()
:
import sqlite3
conn = sqlite3.connect('csc455_HW3.db')
with open('ZooDatabase.sql', 'r') as sql_file:
conn.executescript(sql_file.read())
conn.close()
substring
(MDN) takes parameters as (from, to)
.
substr
(MDN) takes parameters as (from, length)
.
Update: MDN considers substr
legacy.
alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"
You can remember substring
(with an i) takes indices, as does yet another string extraction method, slice (with an i).
When starting from 0 you can use either method.
Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.
module.exports = Component
should become export default Component
.
CommonJS uses module.exports
as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports
, exoprts
or exprots
). There are no runtime or compile-time checks to tell you that you've messed up.
If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component
then it will give you a compile error to let you know.
In your case, you can simplify the Speaker component.
import React from 'react';
export default React.createClass({
render() {
return (
<h1>Speaker</h1>
)
}
});
After not much success with any of the answers available here so far.
My solution:
I downloaded the jar file manually and then installed the dependency by using Apache Maven install:install-file
plugin, see more details here
A Full Example:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.4</version>
</dependency>
Download jar file from here
Install it by using the following command:
mvn -X install:install-file " -DgroupId=commons-net" "-DartifactId=commons-net" "-Dversion=3.4" "-Dpackaging=jar" "-Dfile={your_full_downloads_path}/commons-net-3.4.jar"
Maven->Update Project
You could inspect the available apache2 modules:
$ ls /usr/lib/apache2/modules/
Or try to enable the php module, if you have the appropriate access:
$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
Redirect the page on itself and display the counter value on button click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Request.RawUrl.ToString()); // redirect on itself
Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
}
Poco Foundation library has a very convenient format function, which supports std::string in both the format string and the values:
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)
childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];
Here's a simple explanation. You need to transfer 100 bucks from account A to account B. You can either do:
accountA -= 100;
accountB += 100;
or
accountB += 100;
accountA -= 100;
If something goes wrong between the first and the second operation in the pair you have a problem - either 100 bucks have disappeared, or they have appeared out of nowhere.
A transaction is a mechanism that allows you to mark a group of operations and execute them in such a way that either they all execute (commit), or the system state will be as if they have not started to execute at all (rollback).
beginTransaction;
accountB += 100;
accountA -= 100;
commitTransaction;
will either transfer 100 bucks or leave both accounts in the initial state.
Maybe this could be the best way to start a service and check the result
Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:
@ECHO OFF
REM Put whatever your Batch may do before trying to start the service
net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error
REM Put Whatever you want in case Service was not running and start correctly
GOTO ContinueWithBatch
:AlreadyRunning
REM Put Whatever you want in case Service was already running
GOTO ContinueWithBatch
:Error
REM Put Whatever you want in case Service fail to start
GOTO ContinueWithBatch
:ContinueWithBatch
REM Put whatever else your Batch may do
Another thing is to check for its state without changing it, for that there is a much more simple way to do it, just run:
net start
As that, without parameters it will show a list with all services that are started...
So a simple grep or find after it on a pipe would fit...
Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:
@ECHO OFF
REM Put here any code to be run before check for Service
SET TemporalFile=TemporalFile.TXT
NET START | FIND /N "NameOfSercive" > %TemporalFile%
SET CountLines=0
FOR /F %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
IF 0==%CountLines% GOTO ServiceIsNotRunning
REM Put here any code to be run if Service Is Running
GOTO ContinueWithBatch
:ServiceIsNotRunning
REM Put here any code to be run if Service Is Not Running
GOTO ContinueWithBatch
:ContinueWithBatch
DEL -P %TemporalFile% 2>nul
SET TemporalFile=
REM Put here any code to be run after check for Service
Hope this can help!! It is what i normally use.
In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).
Usually this problem arises when the Child elements of a Parent Div are floated. Here is the Latest Solution of the problem:
In your CSS file write the following class called .clearfix along with the pseudo selector :after
.clearfix:after {
content: "";
display: table;
clear: both;
}
Then, in your HTML, add the .clearfix class to your parent Div. For example:
<div class="clearfix">
<div></div>
<div></div>
</div>
It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "". Also, overflow: auto; might solve the problem but it causes other problems like showing the scroll-bar and is not recommended.
Source: Blog of Lisa Catalano and Chris Coyier
using ssh from java should not be as hard as jsch makes it. you might be better off with sshj.
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher, using WMIC.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Output example:
datestamp: "20200828"
timestamp: "085513"
fullstamp: "2020-08-28_08-55-13"
Press any key to continue . . .
You can copy it into an array and then sort it.
Copying into array O(n),
sorting O(nlgn) (if you use a fast algorithm like merge sort ),
copying back to linked list O(n) if necessary,
so it is gonna be O(nlgn).
note that if you do not know the number of elements in the linked list you won't know the size of array. If you are coding in java you can use an Arraylist for example.
First, add a data conversion block into your data flow diagram.
Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.
Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.
Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).
Download php5.dll (http://windows.php.net/download/) and copy it to apache/bin folder. That solved it for me (Win 7 64 bit apache 32 bit)
EDIT: Start with the non-thread safe version.
this.setState({abc: {xyz: 'new value'}});
will NOT work, as state.abc
will be entirely overwritten, not merged.
This works for me:
this.setState((previousState) => {
previousState.abc.xyz = 'blurg';
return previousState;
});
Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html
Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:
const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);
int charset[256] = {0};
int charcount[256] = {0};
for (i = 0; i < 20; i++)
{
for(int c = 0; c < 256; c++)
{
if(string[i] == charset[c])
{
charcount[c]++;
}
}
}
charcount will store the occurence of any character in the string.
Just follow the below commands. This has worked for me.
Uninstall your mongo completely from your system:
sudo service mongod stop
sudo apt-get purge mongodb-org
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb
Now reinstall mongodb using following commands:
sudo apt update
sudo apt install -y mongodb**
Note: The database server is automatically started after installation.
Next, let's verify that the server is running and works correctly.
sudo systemctl status mongodb
You'll see this output:
mongodb.service - An object/document-oriented database
Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2018-05-26 07:48:04 UTC; 2min 17s ago
Docs: man:mongod(1)
Main PID: 2312 (mongod)
Tasks: 23 (limit: 1153)
CGroup: /system.slice/mongodb.service
+-2312 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf**
Without Linq:
Ascending:
li.Sort();
Descending:
li.Sort();
li.Reverse();
In Eclipse Preferences, Go to Java->Compiler->Errors/Warnings->Generic types and check the Ignore unavoidable generic type problems
check-box.
This satisfies the intent of the question, i.e.
I'd like to avoid Eclipse warnings...
if not the spirit.
This should work for you:
Dim oShell
Dim iValue
Set oShell = CreateObject("WScript.Shell")
iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")
This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.
It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.
The relevant section is:
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
A different point is that the first sentence is parsed as:
scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)
Whereas the second example is parsed as:
scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)
So if you are using macros, you should take care.
Besides, ++
for two lists is calling :::
but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.
Micro-Benchmarks after warming up.
scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46
As Daniel C. Sobrai said, you can append the content of any collection to a list using ++
, whereas with :::
you can only concatenate lists.
You should use below regex which have tested all possible email combination
function validate(email) {
var reg = "^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$";
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Invalid Email Address');
return (false);
}
}
Bonus tip if you're using this in Input tag than you can directly add the regex in that tag example
<input type="text"
name="email"
class="form-control"
placeholder="Email"
required
pattern="^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"/>
Above you can see two attribute required & pattern in
required make sure it input block have data @time of submit
&
pattern make sure it input tag validate based in pattern(regex) @time of submit
For more info you can go throw doc
Try this one :
var time = new Date().toJSON();
MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.
This is documented in the 'R Installation and Administration' manual that came with your installation.
On my Linux box:
R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"
[3] "/usr/lib/R/library"
R>
meaning that the default path is the first of these. You can override that via an argument to both install.packages()
(from inside R) or R CMD INSTALL
(outside R).
You can also override by setting the R_LIBS_USER variable.
The standard colormaps also all have reversed versions. They have the same names with _r
tacked on to the end. (Documentation here.)
SomeBaseClass.__init__(self)
means to call SomeBaseClass
's __init__
. while
super(Child, self).__init__()
means to call a bound __init__
from the parent class that follows Child
in the instance's Method Resolution Order (MRO).
If the instance is a subclass of Child, there may be a different parent that comes next in the MRO.
When you write a class, you want other classes to be able to use it. super()
makes it easier for other classes to use the class you're writing.
As Bob Martin says, a good architecture allows you to postpone decision making as long as possible.
super()
can enable that sort of architecture.
When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an __init__
that comes after this __init__
based on the ordering of the classes for method resolution.
Without super
you would likely hard-code the parent of the class you're writing (like the example does). This would mean that you would not call the next __init__
in the MRO, and you would thus not get to reuse the code in it.
If you're writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super
is one thing that allows greater flexibility for users of the code.
This works in Python 2 and 3:
super(Child, self).__init__()
This only works in Python 3:
super().__init__()
It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self
for an instance method or cls
for a class method - but could be other names) and finding the class (e.g. Child
) in the free variables (it is looked up with the name __class__
as a free closure variable in the method).
I prefer to demonstrate the cross-compatible way of using super
, but if you are only using Python 3, you can call it with no arguments.
What does it give you? For single inheritance, the examples from the question are practically identical from a static analysis point of view. However, using super
gives you a layer of indirection with forward compatibility.
Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when.
You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases - if the bases change in a class you inherit from (say a mixin is added) you'd change nothing in this class. Particularly in Python 2, getting the arguments to super
and the correct method arguments right can be difficult. If you know you're using super
correctly with single inheritance, that makes debugging less difficult going forward.
Other people can use your code and inject parents into the method resolution:
class SomeBaseClass(object):
def __init__(self):
print('SomeBaseClass.__init__(self) called')
class UnsuperChild(SomeBaseClass):
def __init__(self):
print('UnsuperChild.__init__(self) called')
SomeBaseClass.__init__(self)
class SuperChild(SomeBaseClass):
def __init__(self):
print('SuperChild.__init__(self) called')
super(SuperChild, self).__init__()
Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):
class InjectMe(SomeBaseClass):
def __init__(self):
print('InjectMe.__init__(self) called')
super(InjectMe, self).__init__()
class UnsuperInjector(UnsuperChild, InjectMe): pass
class SuperInjector(SuperChild, InjectMe): pass
Using the un-super child fails to inject the dependency because the child you're using has hard-coded the method to be called after its own:
>>> o = UnsuperInjector()
UnsuperChild.__init__(self) called
SomeBaseClass.__init__(self) called
However, the class with the child that uses super
can correctly inject the dependency:
>>> o2 = SuperInjector()
SuperChild.__init__(self) called
InjectMe.__init__(self) called
SomeBaseClass.__init__(self) called
Why in the world would this be useful?
Python linearizes a complicated inheritance tree via the C3 linearization algorithm to create a Method Resolution Order (MRO).
We want methods to be looked up in that order.
For a method defined in a parent to find the next one in that order without super
, it would have to
The
UnsuperChild
should not have access toInjectMe
. Why isn't the conclusion "Always avoid usingsuper
"? What am I missing here?
The UnsuperChild
does not have access to InjectMe
. It is the UnsuperInjector
that has access to InjectMe
- and yet cannot call that class's method from the method it inherits from UnsuperChild
.
Both Child classes intend to call a method by the same name that comes next in the MRO, which might be another class it was not aware of when it was created.
The one without super
hard-codes its parent's method - thus is has restricted the behavior of its method, and subclasses cannot inject functionality in the call chain.
The one with super
has greater flexibility. The call chain for the methods can be intercepted and functionality injected.
You may not need that functionality, but subclassers of your code may.
Always use super
to reference the parent class instead of hard-coding it.
What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.
Not using super
can put unnecessary constraints on users of your code.
How about something like
package main
import (
"fmt"
"time"
)
func schedule(what func(), delay time.Duration) chan bool {
stop := make(chan bool)
go func() {
for {
what()
select {
case <-time.After(delay):
case <-stop:
return
}
}
}()
return stop
}
func main() {
ping := func() { fmt.Println("#") }
stop := schedule(ping, 5*time.Millisecond)
time.Sleep(25 * time.Millisecond)
stop <- true
time.Sleep(25 * time.Millisecond)
fmt.Println("Done")
}
You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.
import pyodbc
class MS_DB():
""" Collection of helper methods to query the MS SQL Server database.
"""
def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
self.username = username
self._password = password
self.host = host
self.port = str(port)
self.db = initial_db
conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
self.host + ';PORT='+ self.port +';DATABASE='+ \
self.db +';UID='+ self.username +';PWD='+ \
self._password +';'
print('Connected to DB:', conn_str)
self._connection = pyodbc.connect(conn_str)
pyodbc.pooling = False
def __repr__(self):
return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"
def __str__(self):
return f"MS-SQLServer Module for STP on {self.host}"
def __del__(self):
self._connection.close()
print("Connection closed.")
@contextmanager
def cursor(self, commit: bool = False):
"""
A context manager style of using a DB cursor for database operations.
This function should be used for any database queries or operations that
need to be done.
:param commit:
A boolean value that says whether to commit any database changes to the database. Defaults to False.
:type commit: bool
"""
cursor = self._connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
print("DatabaseError {} ".format(err))
cursor.rollback()
raise err
else:
if commit:
cursor.commit()
finally:
cursor.close()
ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
cursor.execute("SELECT @@version;")
print(cur.fetchall())
I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.
What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer
and java.util.Observable
A very unique solution for this problem is using git log:
git log -p -M --follow --stat -- path/to/your/file
As explained by Andre here
for (let i = 1; i <= 5; i++) {_x000D_
for (let j = 1; j <= i; j++) {_x000D_
document.write('*');_x000D_
}_x000D_
document.write('<br />');_x000D_
}
_x000D_
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Global events are also deprecated.
Here's a patch, which fixes the browser and event issues:
--- jquery.fancybox-1.3.4.js.orig 2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js 2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@
titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),
- isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+ isIE = !+"\v1",
+
+ isIE6 = isIE && window.XMLHttpRequest === undefined,
/*
* Private methods
@@ -322,7 +324,7 @@
loading.hide();
if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
- $.event.trigger('fancybox-cancel');
+ $('.fancybox-inline-tmp').trigger('fancybox-cancel');
busy = false;
return;
@@ -389,7 +391,7 @@
content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
};
- $.event.trigger('fancybox-change');
+ $('.fancybox-inline-tmp').trigger('fancybox-change');
content
.empty()
@@ -612,7 +614,7 @@
}
if (currentOpts.type == 'iframe') {
- $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+ $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
}
wrap.show();
@@ -912,7 +914,7 @@
busy = true;
- $.event.trigger('fancybox-cancel');
+ $('.fancybox-inline-tmp').trigger('fancybox-cancel');
_abort();
@@ -957,7 +959,7 @@
title.empty().hide();
wrap.hide();
- $.event.trigger('fancybox-cleanup');
+ $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');
content.empty();
For me, on windows 10, I had unknowingly installed multiple python versions (One from PyCharm IDE and another from Windows store). I uninstalled the one from windows Store and just to be thorough, uninstalled numpy pip uninstall numpy
and then installed it again pip install numpy
. It worked in the terminal in PyCharm and also in command prompt.
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :
, so use
>>> '{0:08b}'.format(1)
'00000001'
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
3 things you have to do:
in php.ini
of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate)
post_max_size=500M
upload_max_filesize=500M
memory_limit=900M
or set other values.
Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.
Remote server?
increase max_execution_time
as well, as it will take time to upload the file.
NGINX installation?
you will have to add: client_max_body_size 912M;
in /etc/nginx/nginx.conf
to the http{...}
block
Another option is to use diffutil . It will compare the original list against the new list and use the new list as the update if there is a change.
Basically, we can use DiffUtil to compare the old data vs new data and let it call notifyItemRangeRemoved, and notifyItemRangeChanged and notifyItemRangeInserted on your behalf.
A quick example of using diffUtil instead of notifyDataSetChanged:
DiffResult diffResult = DiffUtil
.calculateDiff(new MyDiffUtilCB(getItems(), items));
//any clear up on memory here and then
diffResult.dispatchUpdatesTo(this);
//and then, if necessary
items.clear()
items.addAll(newItems)
I do the calculateDiff work off the main thread in case it's a big list.
In my case error caused next. I've tried to execute commands globally i.e outside of any target.
UPD. To run command globally one must be properly formed. For example command
ln -sf ../../user/curl/$SRC_NAME ./$SRC_NAME
would become:
$(shell ln -sf ../../user/curl/$(SRC_NAME) ./$(SRC_NAME))
bool vExist = false;
int vSelectValue = 1;
List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);
IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
vExist = true;
}
Put your duration time in the non-hover selection:
li a {
background-color: #111;
transition:1s;
}
li a:hover {
padding:19px;
}
I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras
source, no less...)
The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)
Here is an example:
log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log
BTW the ${instanceId}
bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure()
, as follow:
p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);
You can try this as well, it is easy to implement
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
Change the text to which standard time you want to change.
Use TimeZone
feature of C# to implement.
Set the height for the parent element.
SELECT substring(commaSeparatedTags,0,charindex(',',commaSeparatedTags))
will give you the first tag. You can proceed similarly to get the second one and so on by combining substring and charindex one layer deeper each time. That's an immediate solution but it works only with very few tags as the query grows very quickly in size and becomes unreadable. Move on to functions then, as outlined in other, more sophisticated answers to this post.
In my case I've to set Execute concurrent builds if necessary
in job's General settings.
I would just use a value in the querystring to pass the required information to the next page.
Now there is already no need to use JSON.stringify
explicitly. Just execute this line of code
$.cookie.json = true;
After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.
var user = { name: "name", age: 25 }
$.cookie('user', user);
...
var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);
But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".
I couldn't seem to find the location in the application reference file in my case...
Multidimensional arrays into an object. this code is used for conversion of Bing search API try and catch method.
try {
// Perform the Web request and get the JSON response
$context = stream_context_create($options);
$results = file_get_contents($url . "?cc=" . $country . "&category=" . $type, false, $context);
$results = json_decode($results);
return response()->json($results);
} catch (\Exception $e) {
$results = array('value' => array(
(object) array(
"name" => "Unable to Retrive News",
"url" => "http://www.sample.com/",
"image" => (object) array("thumbnail" => (object) array("contentUrl" => "")),
"publishedAt" => "",
"description" => "")
)
);
$results = (object) $results;
return response()->json($results);
}
Just as a addition. You can find the Catalina Paths in
->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS
In the VM Arguments the Paths are listed and changeable
I had the same issue while doing a git pull and as stated above, it was because of a program that was holding those files and was not allowing a git pull. Closing the program helped. Usually, the IDE (like Eclipse) from where the files are being checked-in will be holding it in the background. Closing the same and re-running git pull solved the problem for me.
Node.js is available as a snap package in all currently supported versions of Ubuntu. Specific to Node.js, developers can choose from one or more of the currently supported releases and get regular automatic updates directly from NodeSource. Node.js versions 6, 8, 9, 10, 11, 13 and 14 are currently available, with the Snap Store being updated within hours or minutes of a Node.js release.
Node.js can be installed with a single command, for example:
sudo snap install node --classic --channel 11/stable
The node snap can be accessed by the command node
, for example:
$ node -v v11.5.0
An up-to-date version of npm will installed as part of the node snap. npm should be run outside of the node repl, in your normal shell. After installing the node snap run the following command to enable npm update checking:
sudo chown -R $USER:$(id -gn $USER) /home/<b>your-username</b>/.config
Replace your-username
in the above command with your own username. Then run npm -v
to check if the version of npm is up-to-date. As an example I checked that npm was up-to-date, checked the version of an already installed package named yarn with the command npm list yarn
and then updated the existing yarn package to the latest version with the command npm update yarn
Users can switch between versions of Node.js at any time without needing to involve additional tools like nvm (Node Version Manager), for example:
sudo snap refresh node --channel=11/stable
Users can test bleeding-edge versions of Node.js that can be installed from the latest edge channel which is currently tracking Node.js version 12 by switching with:
sudo snap switch node --edge
This approach is only recommended for those users who are willing to participate in testing and bug reporting upstream.
Release LTS Status Codename LTS Start Maintenance Start Maintenance End 6.x Active Boron 2016-10-18 April 2018 April 2019 7.x No LTS 8.x Active Carbon 2017-10-31 April 2019 December 2019 9.x No LTS 10.x Active Dubnium October 2018 April 2020 April 2021 11.x No LTS 2019-04-01 2019-06-30 12.x 2019-10-22 2021-04-01 2022-04-01 13.x No LTS 2020-04-20 2020-06-01 14.x Current Fermium 2020-10-20 2021-10-20 2023-04-30
I know it's somewhat later, but this could be useful to people arriving here from searches. Anyway, here's some JavaScript that relies on the fact that only prime factors need to be tested, so the earlier primes generated by the code are re-used as test factors for later ones. Of course, all even and mod 5 values are filtered out first. The result will be in the array P, and this code can crunch 10 million primes in under 1.5 seconds on an i7 PC (or 100 million in about 20). Rewritten in C it should be very fast.
var P = [1, 2], j, k, l = 3
for (k = 3 ; k < 10000000 ; k += 2)
{
loop: if (++l < 5)
{
for (j = 2 ; P[j] <= Math.sqrt(k) ; ++j)
if (k % P[j] == 0) break loop
P[P.length] = k
}
else l = 0
}
It echoes the data used in your request for any of these types:
There is an open source Javascript library that offers something related : mobile-bookmark-bubble
The Mobile Bookmark Bubble is a JavaScript library that adds a promo bubble to the bottom of your mobile web application, inviting users to bookmark the app to their device's home screen. The library uses HTML5 local storage to track whether the promo has been displayed already, to avoid constantly nagging users.
The current implementation of this library specifically targets Mobile Safari, the web browser used on iPhone and iPad devices.
Less no longer evaluates expression inside calc
by default since v3.00
.
Original answer (Less v1.x...2.x
):
Do this:
body { width: calc(~"100% - 250px - 1.5em"); }
In Less 1.4.0 we will have a strictMaths
option which requires all Less calculations to be within brackets, so the calc
will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.
public void ChargingArraySelect()
{
int loop = 0;
int registros = 0;
OdbcConnection conn = WebApiConfig.conn();
OdbcCommand query = conn.CreateCommand();
query.CommandText = "select dataA, DataB, dataC, DataD FROM table where dataA = 'xpto'";
try
{
conn.Open();
OdbcDataReader dr = query.ExecuteReader();
//take the number the registers, to use into next step
registros = dr.RecordsAffected;
//calls an array to be populated
Global.arrayTest = new string[registros, 4];
while (dr.Read())
{
if (loop < registros)
{
Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
}
loop++;
}
}
}
//Declaration the Globais Array in Global Classs
private static string[] uso_internoArray1;
public static string[] arrayTest
{
get { return uso_internoArray1; }
set { uso_internoArray1 = value; }
}
Some websites with m3u streaming cannot be downloaded in a single youtube-dl
step, you can try something like this :
$ URL=https://www.arte.tv/fr/videos/078132-001-A/cosmos-une-odyssee-a-travers-l-univers/
$ youtube-dl -F $URL | grep m3u
HLS_XQ_2 m3u8 1280x720 VA-STA, Allemand 2200k
HLS_XQ_1 m3u8 1280x720 VF-STF, Français 2200k
$ CHOSEN_FORMAT=HLS_XQ_1
$ youtube-dl -F "$(youtube-dl -gf $CHOSEN_FORMAT)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[info] Available formats for master:
format code extension resolution note
61 mp4 audio only 61k , mp4a.40.2
419 mp4 384x216 419k , avc1.66.30, mp4a.40.2
923 mp4 640x360 923k , avc1.77.30, mp4a.40.2
1737 mp4 720x406 1737k , avc1.77.30, mp4a.40.2
2521 mp4 1280x720 2521k , avc1.77.30, mp4a.40.2 (best)
$ youtube-dl --hls-prefer-native -f 1737 "$(youtube-dl -gf $CHOSEN_FORMAT $URL)" -o "$(youtube-dl -f $CHOSEN_FORMAT --get-filename $URL)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 257
[download] Destination: Cosmos_une_odyssee_a_travers_l_univers__HLS_XQ_1__078132-001-A.mp4
[download] 0.9% of ~731.27MiB at 624.95KiB/s ETA 13:13
....
The self
keyword in Python is analogous to this
keyword in C++ / Java / C#.
In Python 2 it is done implicitly by the compiler (yes Python does compilation internally). It's just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:
class Pump():
//member variable
account_holder
balance_amount
// constructor
def __init__(self,ah,bal):
| self.account_holder = ah
| self.balance_amount = bal
def getPumps(self):
| print("The details of your account are:"+self.account_number + self.balance_amount)
//object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()
Try this, should work.
val list = List(1,2,4,2,4,7,3,2,4)
list.count(_==2)
It will return 3
After searching for a long time this is what worked for me:
File file = new File(getPath(uri));
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
In Ember.js you can use inline if helper in if block helper. It can replace ||
logical operator, for example:
{{#if (if firstCondition firstCondition secondCondition)}}
(firstCondition || (or) secondCondition) === true
{{/if}}
Though this question has an accepted answer, still I would like to share my project structure for RESTful services.
src/main/java
+- com
+- example
+- Application.java
+- ApplicationConstants.java
+- configuration
| +- ApplicationConfiguration.java
+- controller
| +- ApplicationController.java
+- dao
| +- impl
| | +- ApplicationDaoImpl.java
| +- ApplicationDao.java
+- dto
| +- ApplicationDto.java
+- service
| +- impl
| | +- ApplicationServiceImpl.java
| +- ApplicationService.java
+- util
| +- ApplicationUtils.java
+- validation
| +- impl
| | +- ApplicationValidationImpl.java
| +- ApplicationValidation.java
Short but simple explanation:
I the worst case you would need to visit all the vertex and edge hence the time complexity in the worst case is O(V+E)
SELECT * FROM Header WHERE userID LIKE '%' + CHAR(39) + '%'
The accepted solution works great, but IMO lacks an explanation as to why it works. The example below is boiled down to the basics and separates the important CSS from the non-relevant styling CSS. As a bonus, I've also included a detailed explanation of how CSS positioning works.
TLDR; if you only want the code, scroll down to The Result.
There are two separate, sibling, elements and the goal is to position the second element (with an id
of infoi
), so it appears within the previous element (the one with a class
of navi
). The HTML structure cannot be changed.
To achieve the desired result we're going to move, or position, the second element, which we'll call #infoi
so it appears within the first element, which we'll call .navi
. Specifically, we want #infoi
to be positioned in the top-right corner of .navi
.
CSS has several properties for positioning elements. By default, all elements are position: static
. This means the element will be positioned according to its order in the HTML structure, with few exceptions.
The other position
values are relative
, absolute
, sticky
, and fixed
. By setting an element's position
to one of these other values it's now possible to use a combination of the following four properties to position the element:
top
right
bottom
left
In other words, by setting position: absolute
, we can add top: 100px
to position the element 100 pixels from the top of the page. Conversely, if we set bottom: 100px
the element would be positioned 100 pixels from the bottom of the page.
Here's where many CSS newcomers get lost - position: absolute
has a frame of reference. In the example above, the frame of reference is the body
element. position: absolute
with top: 100px
means the element is positioned 100 pixels from the top of the body
element.
The position frame of reference, or position context, can be altered by setting the position
of a parent element to any value other than position: static
. That is, we can create a new position context by giving a parent element:
position: relative;
position: absolute;
position: sticky;
position: fixed;
For example, if a <div class="parent">
element is given position: relative
, any child elements use the <div class="parent">
as their position context. If a child element were given position: absolute
and top: 100px
, the element would be positioned 100 pixels from the top of the <div class="parent">
element, because the <div class="parent">
is now the position context.
The other factor to be aware of is stack order - or how elements are stacked in the z-direction. The must-know here is the stack order of elements are, by default, defined by the reverse of their order in the HTML structure. Consider the following example:
<body>
<div>Bottom</div>
<div>Top</div>
</body>
In this example, if the two <div>
elements were positioned in the same place on the page, the <div>Top</div>
element would cover the <div>Bottom</div>
element. Since <div>Top</div>
comes after <div>Bottom</div>
in the HTML structure it has a higher stacking order.
div {_x000D_
position: absolute;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
}_x000D_
_x000D_
#bottom {_x000D_
top: 0;_x000D_
left: 0;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
#top {_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
background-color: red;_x000D_
}
_x000D_
<div id="bottom">Bottom</div>_x000D_
<div id="top">Top</div>
_x000D_
The stacking order can be changed with CSS using the z-index
or order
properties.
We can ignore the stacking order in this issue as the natural HTML structure of the elements means the element we want to appear on top
comes after the other element.
So, back to the problem at hand - we'll use position context to solve this issue.
As stated above, our goal is to position the #infoi
element so it appears within the .navi
element. To do this, we'll wrap the .navi
and #infoi
elements in a new element <div class="wrapper">
so we can create a new position context.
<div class="wrapper">
<div class="navi"></div>
<div id="infoi"></div>
</div>
Then create a new position context by giving .wrapper
a position: relative
.
.wrapper {
position: relative;
}
With this new position context, we can position #infoi
within .wrapper
. First, give #infoi
a position: absolute
, allowing us to position #infoi
absolutely in .wrapper
.
Then add top: 0
and right: 0
to position the #infoi
element in the top-right corner. Remember, because the #infoi
element is using .wrapper
as its position context, it will be in the top-right of the .wrapper
element.
#infoi {
position: absolute;
top: 0;
right: 0;
}
Because .wrapper
is merely a container for .navi
, positioning #infoi
in the top-right corner of .wrapper
gives the effect of being positioned in the top-right corner of .navi
.
And there we have it, #infoi
now appears to be in the top-right corner of .navi
.
The example below is boiled down to the basics, and contains some minimal styling.
/*_x000D_
* position: relative gives a new position context_x000D_
*/_x000D_
.wrapper {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
/*_x000D_
* The .navi properties are for styling only_x000D_
* These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
background-color: #eaeaea;_x000D_
height: 40px;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* Position the #infoi element in the top-right_x000D_
* of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
_x000D_
/*_x000D_
* Styling only, the below can be changed or removed_x000D_
* depending on your use case_x000D_
*/_x000D_
height: 20px;_x000D_
padding: 10px 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
<img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an alternate solution using CSS Grid to position the .navi
element with the #infoi
element in the far right. I've used the verbose grid
properties to make it as clear as possible.
:root {_x000D_
--columns: 12;_x000D_
}_x000D_
_x000D_
/*_x000D_
* Setup the wrapper as a Grid element, with 12 columns, 1 row_x000D_
*/_x000D_
.wrapper {_x000D_
display: grid;_x000D_
grid-template-columns: repeat(var(--columns), 1fr);_x000D_
grid-template-rows: 40px;_x000D_
}_x000D_
_x000D_
/*_x000D_
* Position the .navi element to span all columns_x000D_
*/_x000D_
.navi {_x000D_
grid-column-start: 1;_x000D_
grid-column-end: span var(--columns);_x000D_
grid-row-start: 1;_x000D_
grid-row-end: 2;_x000D_
_x000D_
/*_x000D_
* Styling only, the below can be changed or removed_x000D_
* depending on your use case_x000D_
*/_x000D_
background-color: #eaeaea;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* Position the #infoi element in the last column, and center it_x000D_
*/_x000D_
#infoi {_x000D_
grid-column-start: var(--columns);_x000D_
grid-column-end: span 1;_x000D_
grid-row-start: 1;_x000D_
place-self: center;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
<img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>_x000D_
</div>
_x000D_
In the case we can't edit any HTML, meaning we can't add a wrapper element, we can still achieve the desired effect.
Instead of using position: absolute
on the #infoi
element, we'll use position: relative
. This allows us to reposition the #infoi
element from its default position below the .navi
element. With position: relative
we can use a negative top
value to move it up from its default position, and a left
value of 100%
minus a few pixels, using left: calc(100% - 52px)
, to position it near the right-side.
/*_x000D_
* The .navi properties are for styling only_x000D_
* These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
background-color: #eaeaea;_x000D_
height: 40px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* Position the #infoi element in the top-right_x000D_
* of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
top: -40px;_x000D_
left: calc(100% - 52px);_x000D_
_x000D_
/*_x000D_
* Styling only, the below can be changed or removed_x000D_
* depending on your use case_x000D_
*/_x000D_
height: 20px;_x000D_
padding: 10px 10px;_x000D_
}
_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
<img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>
_x000D_
there is a way you can pass more than one parameter. You can pass "to" as object instead of string.
// your route setup
<Route path="/category/:catId" component={Category} / >
// your link creation
const newTo = {
pathname: "/category/595212758daa6810cbba4104",
param1: "Par1"
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>
// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104
this.props.location.param1 // this is Par1
This supplemental answer shows the effect of changing the line spacing.
You can set the multiplier and/or extra spacing with
textView.setLineSpacing(float add, float mult)
Or you can get the values with
int lineHeight = textView.getLineHeight();
float add = tvSampleText.getLineSpacingExtra(); // API 16+
float mult = tvSampleText.getLineSpacingMultiplier(); // API 16+
where the formula is
lineHeight = fontMetricsLineHeight * mult + add
The default multiplier is 1
and the default extra spacing is 0
.
It looks like you can simply do:
SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';
Test case:
CREATE TABLE your_table (id int, some_column varchar(10));
INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);
Result:
SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';
id
----------
1
2
5
With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.
See the following code for more details.
To make an image gray:
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
}
To give a sepia look:
img {
-webkit-filter: sepia(100%);
-moz-filter: sepia(100%);
}
To adjust brightness:
img {
-webkit-filter: brightness(50%);
-moz-filter: brightness(50%);
}
To adjust contrast:
img {
-webkit-filter: contrast(200%);
-moz-filter: contrast(200%);
}
To Blur an image:
img {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
}
I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...
Push Data
import android.content.Intent;
...
Intent intent =
new Intent(
this,
MyActivity.class );
intent.putExtra( "paramName", "paramValue" );
startActivity( intent );
The above code might be inside the main activity
. "MyActivity.class
" is the second Activity
we want to launch; it must be explicitly included in your AndroidManifest.xml
file.
<activity android:name=".MyActivity" />
Pull Data
import android.os.Bundle;
...
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String myParam = extras.getString("paramName");
}
else
{
//..oops!
}
In this example, the above code would be inside your MyActivity.java
file.
Gotchas
This method can only pass strings
. So let's say you need to pass an ArrayList
to your ListActivity
; a possible workaround is to pass a comma-separated-string and then split it on the other side.
Alternative Solutions
Use SharedPreferences
Updated for modern versions of .NET per @1c1cle's suggestion in a comment:
<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>
Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.
Something to be aware of is that if you set that readonly
value to false
, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that readonly
attribute in.
Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):
<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>
Recursion version:
def int_digits(n):
return [n] if n<10 else int_digits(n/10)+[n%10]
This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates
which is more suitable than distinct
for certain queries.
Suppose you have this DataFrame:
+-------+-------------+
|country| continent|
+-------+-------------+
| china| asia|
| brazil|south america|
| france| europe|
| china| asia|
+-------+-------------+
Here's how to take all the distinct countries and run a transformation:
df
.select("country")
.distinct
.withColumn("country", concat(col("country"), lit(" is fun!")))
.show()
+--------------+
| country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+
You can use dropDuplicates
instead of distinct
if you don't want to lose the continent
information:
df
.dropDuplicates("country")
.withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
.show(false)
+-------+-------------+------------------------------------+
|country|continent |description |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe |france is a country in europe |
|china |asia |china is a country in asia |
+-------+-------------+------------------------------------+
See here for more information about filtering DataFrames and here for more information on dropping duplicates.
Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.
git branch | grep "*" | sed "s/* //" | awk '{printf $0}' | pbcopy
To directly copy the result to the pasteboard. Thanks to @olivier-refalo for the start…
For Play 2.2.x on Windows with a distributable tar file I created a file in the distributable root directory called: {PROJECT_NAME}_config.txt and added:
-Dhttp.port=8080
Where {PROJECT_NAME} should be replaced with the name of your project. Then started the {PROJECT_NAME}.bat script as usual in the bin\ directory.
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
I use a function to store cookies with a custom expire time in days:
// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
This might be of some help: http://www.webmasterworld.com/forum83/200.htm
A relevant quote:
Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.
The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.
html, body { margin:0; padding:0; height:100%; }
This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.
The recommended way to do this would be with String.Format
:
string name = "Scott";
string output = String.Format("Hello {0}", name);
However, I wrote a small open-source library called SmartFormat that extends String.Format
so that it can use named placeholders (via reflection). So, you could do:
string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
Hope you like it!
I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html
I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {
// assuming that everything is correct and there is no exception being thrown
// output string {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
// now we need to remove the double quotes (as it will create problem and
// if double quotes aren't removed then this JSON string is useless)
// The output string : {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
// The required string : {"d":{username:"hi",email:"[email protected]",password:"123"}"}
// For security reasons the d is added (indicating the return "data")
// so actually we need to convert data.d into series of objects
// Inbuilt function "JSON.Parse" will return streams of objects
// JSON String : "{"username":"hi","email":"[email protected]","password":"123"}"
console.log(data); // output : Object {d="{"username":"hi","email":"[email protected]","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"[email protected]","password":"123"} (accessing what's stored in "d")
console.log(data.d[0]); // output : { (just accessing the first element of array of "strings")
var content = JSON.parse(data.d); // output : Object {username:"hi",email:"[email protected]",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}
A build, as Makefile understands it, consists of a lot of targets. For example, to build a project you might need
If you implemented this workflow with makefile, you could make each of the targets separately. For example, if you wrote
make file1.o
it would only build that file, if necessary.
The name of all
is not fixed. It's just a conventional name; all
target denotes that if you invoke it, make will build all what's needed to make a complete build. This is usually a dummy target, which doesn't create any files, but merely depends on the other files. For the example above, building all necessary is building executables, the other files being pulled in as dependencies. So in the makefile it looks like this:
all: executable1 executable2
all
target is usually the first in the makefile, since if you just write make
in command line, without specifying the target, it will build the first target. And you expect it to be all
.
all
is usually also a .PHONY
target. Learn more here.
According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.
I've listed a few options below that might be helpful to you:
With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..
You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.
Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.
<input type="number" formnovalidate />
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name
. You can also do it by assigning the variable to None
a = 10
print a
del a
print a ## throws an error here because it's been deleted already.
The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del
has no real effect, since those names would have been deleted as they went out of scope anyway.
This method take String as a argument and return the Character Array
/**
* @param sourceString
* :String as argument
* @return CharcterArray
*/
public static Character[] toCharacterArray(String sourceString) {
char[] charArrays = new char[sourceString.length()];
charArrays = sourceString.toCharArray();
Character[] characterArray = new Character[charArrays.length];
for (int i = 0; i < charArrays.length; i++) {
characterArray[i] = charArrays[i];
}
return characterArray;
}
The reason you're seeing that error is because document.getElementsByName
returns a NodeList
of elements. And a NodeList
of elements does not have a .value
property.
Use this instead:
document.getElementsByName("acc")[0].value
Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.
If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.
Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:
$ date
If the date and/or time is incorrect, try to update using:
$ sudo ntpdate -u time.nist.gov
Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.
The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.
Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.
You are using incorrect overload. You should use this overload
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
And the correct code would be
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Note that extra parameter at the end.
For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object
overload that you are trying to use.
There are two events on client side as given below.
1. window.onbeforeunload (calls on Browser/tab Close & Page Load)
2. window.onload (calls on Page Load)
On server Side
public JsonResult TestAjax( string IsRefresh)
{
JsonResult result = new JsonResult();
return result = Json("Called", JsonRequestBehavior.AllowGet);
}
On Client Side
<script type="text/javascript">_x000D_
window.onbeforeunload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: { IsRefresh: 'Close' }_x000D_
});_x000D_
};_x000D_
_x000D_
window.onload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: {IsRefresh:'Load'}_x000D_
});_x000D_
};_x000D_
</script>
_x000D_
On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".
On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.
If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.
How about;
function keyValue(key, value){
this.Key = key;
this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
this.Key = newKey;
this.Value = newValue;
};
array[1].updateTo("xxx", "999");
I enabled logging using this code:
http://blogs.msdn.com/b/dgorti/archive/2005/09/18/471003.aspx
The log was in the bin/debug folder (I was in Debug mode for my console app). You need to add the security protocol type as SSL 3
I received an algorithm mismatch in the log. Here is my new code:
// You must change the URL to point to your Web server.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
// Skip validation of SSL/TLS certificate
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
WebResponse respon = req.GetResponse();
Stream res = respon.GetResponseStream();
string ret = "";
byte[] buffer = new byte[1048];
int read = 0;
while ((read = res.Read(buffer, 0, buffer.Length)) > 0)
{
Console.Write(Encoding.ASCII.GetString(buffer, 0, read));
ret += Encoding.ASCII.GetString(buffer, 0, read);
}
return ret;
Works in SQL server
Declare @GivenDate datetime
SET @GivenDate = GETDATE()
Select DATEADD(MM,DATEDIFF(MM, 0, @GivenDate),0) --First day of the month
Select DATEADD(MM,DATEDIFF(MM, -1, @GivenDate),-1) --Last day of the month
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
Need To Two Or More Parameters Passing Throw view To Controller Use This Syntax... Try.. It.
var id=0,Num=254;var str='Sample';
var Url = '@Url.Action("ViewNameAtController", "Controller", new RouteValueDictionary(new { id= "id", Num= "Num", Str= "str" }))'.replace("id", encodeURIComponent(id));
Url = Url.replace("Num", encodeURIComponent(Num));
Url = Url.replace("Str", encodeURIComponent(str));
Url = Url.replace(/&/g, "&");
window.location.href = Url;
Not specific to the question, but for folks who need the same kind of functionality expanded for clarity from previous answers:
# create some variables
str="someFileName.foo"
find=".foo"
replace=".bar"
# notice the the str isn't prefixed with $
# this is just how this feature works :/
result=${str//$find/$replace}
echo $result
# result is: someFileName.bar
str="someFileName.sally"
find=".foo"
replace=".bar"
result=${str//$find/$replace}
echo $result
# result is: someFileName.sally because ".foo" was not found
I got same problem recently where
$(window).mousewheel
was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}
The first part is similar to Constantine, you can get the boolean of which rows are empty*:
In [21]: ne = (df1 != df2).any(1)
In [22]: ne
Out[22]:
0 False
1 True
2 True
dtype: bool
Then we can see which entries have changed:
In [23]: ne_stacked = (df1 != df2).stack()
In [24]: changed = ne_stacked[ne_stacked]
In [25]: changed.index.names = ['id', 'col']
In [26]: changed
Out[26]:
id col
1 score True
2 isEnrolled True
Comment True
dtype: bool
Here the first entry is the index and the second the columns which has been changed.
In [27]: difference_locations = np.where(df1 != df2)
In [28]: changed_from = df1.values[difference_locations]
In [29]: changed_to = df2.values[difference_locations]
In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
from to
id col
1 score 1.11 1.21
2 isEnrolled True False
Comment None On vacation
* Note: it's important that df1
and df2
share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using df1.index & df2.index
, but I think I'll leave that as an exercise.
The simplest (not the best or ideal) solution I found was to use react-native-dotenv. You simply add the "react-native-dotenv" preset to your .babelrc
file at the project root like so:
{
"presets": ["react-native", "react-native-dotenv"]
}
Create a .env
file and add properties:
echo "SOMETHING=anything" > .env
Then in your project (JS):
import { SOMETHING } from 'react-native-dotenv'
console.log(SOMETHING) // "anything"
You can use the following command to
kill -9 $(ps aux | grep 'process' | grep -v 'grep' | awk '{print $2}')
The current spec of the CSS 3 Lists module does specify the ::marker
pseudo-element which would do exactly what you want; FF has been tested
to not support ::marker
and I doubt that either Safari or Opera has it.
IE, of course, does not support it.
So right now, the only way to do this is to use an image with list-style-image
.
I guess you could wrap the contents of an li
with a span
and then you could set the color of each, but that seems a little hackish to me.
char* str = "blablabla";
You should not modify this string at all. It resides in implementation defined read only region. Modifying it causes Undefined Behavior.
You need a char array not a string literal.
Good Read:
What is the difference between char a[] = "string"; and char *p = "string";
If you have installed Git for Windows, you should have Git Bash installed, since that comes with Git.
Use the split
command in Git Bash to split a file:
into files of size 500MB each: split myLargeFile.txt -b 500m
into files with 10000 lines each: split myLargeFile.txt -l 10000
Tips:
If you don't have Git/Git Bash, download at https://git-scm.com/download
If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe
I always like examples though...
Example:
You can see in this image that the files generated by split
are named xaa
, xab
, xac
, etc.
These names are made up of a prefix and a suffix, which you can specify. Since I didn't specify what I want the prefix or suffix to look like, the prefix defaulted to x
, and the suffix defaulted to a two-character alphabetical enumeration.
Another Example:
This example demonstrates
MySlice
(instead of the default x
),-d
flag for using numerical suffixes (instead of aa
, ab
, ac
, etc...),-a 5
to tell it I want the suffixes to be 5 digits long:Please remove call to trustSrc
function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}.
Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview
src
url. Have a look on the following code.
Before:
Javascript
scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;
Html
<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"
But for security reason they are recommending following method
Javascript
var baseUrl = "page";
scope.getIframeSrc = function() {
// One should think about their particular case and sanitize accordingly
var qs = ["a", "b"].map(function(value, name) {
return encodeURIComponent(name) + "=" +
encodeURIComponent(value);
}).join("&");
// `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
return baseUrl + "?" + qs;
};
Html
<iframe src="{{getIframeSrc()}}">
Let's benchmark the three solutions proposed:
# use rbind
f1 <- function(n){
df <- data.frame(x = numeric(), y = character())
for(i in 1:n){
df <- rbind(df, data.frame(x = i, y = toString(i)))
}
df
}
# use list
f2 <- function(n){
df <- data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
for(i in 1:n){
df[i,] <- list(i, toString(i))
}
df
}
# pre-allocate space
f3 <- function(n){
df <- data.frame(x = numeric(1000), y = character(1000), stringsAsFactors = FALSE)
for(i in 1:n){
df$x[i] <- i
df$y[i] <- toString(i)
}
df
}
system.time(f1(1000))
# user system elapsed
# 1.33 0.00 1.32
system.time(f2(1000))
# user system elapsed
# 0.19 0.00 0.19
system.time(f3(1000))
# user system elapsed
# 0.14 0.00 0.14
The best solution is to pre-allocate space (as intended in R). The next-best solution is to use list
, and the worst solution (at least based on these timing results) appears to be rbind
.
Maybe this post is old, but I came across it and used the "wrong" usage. The best way to find a keyword is using .contains
, example:
if ( d.contains("hello")) {
System.out.println("I found the keyword");
}
It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.
String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"
Please note that for file path there's java.nio.file.Path#relativize
since Java 1.7, as pointed out by @Jirka Meluzin in the other answer.
In case the Fluttertoast package given so far doesnt work...
Then I will suggest you try toast.
It has no frills and no ceremony.
It just works.
I noticed a bug within the example given within its Readme though:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
While the method requires a context. So do well to add 'context' like this:
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
There is a chance that this would have been fixed by the time you checked though, I already submitted a PR.
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)