Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)
SET @C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
WHILE ( @fs_e <> -1)
BEGIN
exec('Select * from ' + @Table)
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
END
Actually the color TextView is:
android:textColor="@android:color/tab_indicator_text"
or
#808080
You can do this thing using performSegueWithIdentifier
function.
Syntax :
func performSegueWithIdentifier(identifier: String, sender: AnyObject?)
Example :
performSegueWithIdentifier("homeScreenVC", sender: nil)
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
Having 2 files like you suggested would be the easiest solution.
For instance:
(.. your html ..)
<form action="script.php" method="get">
<input type="submit" value="Run me now!">
</form>
(...)
<?php
echo "Hello world!"; // Your code here
?>
<?php
if (!empty($_GET['act'])) {
echo "Hello world!"; //Your code here
} else {
?>
(.. your html ..)
<form action="index.php" method="get">
<input type="hidden" name="act" value="run">
<input type="submit" value="Run me now!">
</form>
<?php
}
?>
I had this problem on my ubuntu.
I just ran adb from sdk/platform-tools
instead of pre-installed version on my system and it worked fine.
1.->
for accessing object member variables and methods via pointer
to object
Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();
2..
for accessing object member variables and methods via object instance
Foo foo;
foo.member_var = 10;
foo.member_func();
3.::
for accessing static variables and methods of a class/struct
or namespace
. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)
int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
Completly removing style, not only set to NULL
document.getElementById("id").removeAttribute("style")
Add below method in your activity class.Here browser is nothing but your webview object.
Now you can view web contain page wise easily.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
browser.goBack();
return true;
}
return false;
}
I saw Veer's answer. I think it's right, but it did not I work for me. Maybe I am using .NET 4 and am using 64x OS so kindly check this.
You may put in setup or check it in start-up of your application:
private void Form1_Load(object sender, EventArgs e)
{
var appName = Process.GetCurrentProcess().ProcessName + ".exe";
SetIE8KeyforWebBrowserControl(appName);
}
private void SetIE8KeyforWebBrowserControl(string appName)
{
RegistryKey Regkey = null;
try
{
// For 64 bit machine
if (Environment.Is64BitOperatingSystem)
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
else //For 32 bit machine
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
// If the path is not correct or
// if the user haven't priviledges to access the registry
if (Regkey == null)
{
MessageBox.Show("Application Settings Failed - Address Not found");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
// Check if key is already present
if (FindAppkey == "8000")
{
MessageBox.Show("Required Application Settings Present");
Regkey.Close();
return;
}
// If a key is not present add the key, Key value 8000 (decimal)
if (string.IsNullOrEmpty(FindAppkey))
Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);
// Check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName));
if (FindAppkey == "8000")
MessageBox.Show("Application Settings Applied Successfully");
else
MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
}
catch (Exception ex)
{
MessageBox.Show("Application Settings Failed");
MessageBox.Show(ex.Message);
}
finally
{
// Close the Registry
if (Regkey != null)
Regkey.Close();
}
}
You may find messagebox.show, just for testing.
Keys are as the following:
11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the
!DOCTYPE
directive.11000 (0x2AF8) - Internet Explorer 11. Webpages containing standards-based
!DOCTYPE
directives are displayed in IE11 edge mode. Default value for IE11.10001 (0x2711)- Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the
!DOCTYPE
directive.10000 (0x2710)- Internet Explorer 10. Webpages containing standards-based
!DOCTYPE
directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the
!DOCTYPE
directive.9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based
!DOCTYPE
directives are displayed in IE9 mode.8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the
!DOCTYPE
directive.8000 (0x1F40) - Webpages containing standards-based
!DOCTYPE
directives are displayed in IE8 mode.7000 (0x1B58) - Webpages containing standards-based
!DOCTYPE
directives are displayed in IE7 Standards mode.
Reference: MSDN: Internet Feature Controls
I saw applications like Skype use 10001. I do not know.
NOTE
The setup application will change the registry. You may need to add a line in the Manifest File to avoid errors due to permissions of change in registry:
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
UPDATE 1
This is a class will get the latest version of IE on windows and make changes as should be;
public class WebBrowserHelper
{
public static int GetEmbVersion()
{
int ieVer = GetBrowserVersion();
if (ieVer > 9)
return ieVer * 1000 + 1;
if (ieVer > 7)
return ieVer * 1111;
return 7000;
} // End Function GetEmbVersion
public static void FixBrowserVersion()
{
string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
FixBrowserVersion(appName);
}
public static void FixBrowserVersion(string appName)
{
FixBrowserVersion(appName, GetEmbVersion());
} // End Sub FixBrowserVersion
// FixBrowserVersion("<YourAppName>", 9000);
public static void FixBrowserVersion(string appName, int ieVer)
{
FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
} // End Sub FixBrowserVersion
private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
{
try
{
//For 64 bit Machine
if (Environment.Is64BitOperatingSystem)
Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
else //For 32 bit Machine
Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
}
catch (Exception)
{
// some config will hit access rights exceptions
// this is why we try with both LOCAL_MACHINE and CURRENT_USER
}
} // End Sub FixBrowserVersion_Internal
public static int GetBrowserVersion()
{
// string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
string[] ls = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };
int maxVer = 0;
for (int i = 0; i < ls.Length; ++i)
{
object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
string strVal = System.Convert.ToString(objVal);
if (strVal != null)
{
int iPos = strVal.IndexOf('.');
if (iPos > 0)
strVal = strVal.Substring(0, iPos);
int res = 0;
if (int.TryParse(strVal, out res))
maxVer = Math.Max(maxVer, res);
} // End if (strVal != null)
} // Next i
return maxVer;
} // End Function GetBrowserVersion
}
using of class as followed
WebBrowserHelper.FixBrowserVersion();
WebBrowserHelper.FixBrowserVersion("SomeAppName");
WebBrowserHelper.FixBrowserVersion("SomeAppName",intIeVer);
you may face a problem for in comparability of windows 10, may due to your website itself you may need to add this meta tag
<meta http-equiv="X-UA-Compatible" content="IE=11" >
Enjoy :)
:-) Sunday | 0 -> Sun
|
Monday | 1 -> Mon
Tuesday | 2 -> Tue
Wednesday | 3 -> Wed
Thursday | 4 -> Thu
Friday | 5 -> Fri
Saturday | 6 -> Sat
|
:-) Sunday | 7 -> Sun
As you can see above, and as said before, the numbers 0
and 7
are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.
Examples of Number or Abbreviation Use
15 09 * * 5,6,0 command
15 09 * * 5,6,7 command
15 09 * * 5-7 command
15 09 * * Fri,Sat,Sun command
The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.
In Detail
Having two numbers 0
and 7
for Sunday can be useful for writing weekday ranges starting with 0
or ending with 7
. So you can write ranges starting with Sunday or ending with it, like 0-2
or 5-7
for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.
I guess this is a better way to view a stored procedure's code:
sp_helptext <name of your sp>
I had a similar problem going through a tutorial.
# git mv README README.markdown
fatal: bad source, source=README, destination=README.markdown
I included the filetype in the source file:
# git mv README.rdoc README.markdown
and it worked perfectly. Don't forget to commit the changes with i.e.:
# git commit -a -m "Improved the README"
Sometimes it is simple little things like that, that piss us off. LOL
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
In case you use yarn
:
yarn config set strict-ssl false
Provide the following in the search dialog:
Find What: ^$\r\n
Replace With: (Leave it empty)
Click Replace All
Use ng-show
and toggle the value of a show
scope variable in the ng-click
handler.
Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/
<ul class="procedures">
<li ng-repeat="procedure in procedures">
<h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="show">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.
Sub CleanTheTable()
Application.ScreenUpdating = False
Sheets("Data").Select
ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
'Remove the filters if one exists.
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
'Clear all lines but the first one in the table leaving formulas for the next go round.
With Worksheets("Data").ListObjects("TestTable")
.Range.AutoFilter
On Error Resume Next
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ActiveWindow.SmallScroll Down:=-10000
End With
Application.ScreenUpdating = True
End Sub
#include<stdio.h>
int main ( ) {
printf( "hello " );
fprintf( stderr, "HELP!" );
printf( " world\n" );
return 0;
}
$ ./a.exe
HELP!hello world
$ ./a.exe 2> tmp1
hello world
$ ./a.exe 1> tmp1
HELP!$
stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.
Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.
You could also use clip-path
to clip (hide) all overflowing edges but the one you want to show:
.shadow {
box-shadow: 0 4px 4px black;
clip-path: polygon(0 0, 100% 0, 100% 200%, 0 200%);
}
See clip-path (MDN). The arguments to polygon
are the top-left point, the top-right point, the bottom-right point, and the bottom-left point. By setting the bottom edge to 200%
(or whatever number bigger than 100%
) you constrain your overflow to only the bottom edge.
Examples:
.shadow {
box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
}
.shadow-top {
clip-path: polygon(0% -20%, 100% -20%, 100% 100%, 0% 100%);
}
.shadow-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 100%, 0% 100%);
}
.shadow-bottom {
clip-path: polygon(0% 0%, 100% 0%, 100% 120%, 0% 120%);
}
.shadow-left {
clip-path: polygon(-20% 0%, 100% 0%, 100% 100%, -20% 100%);
}
.shadow-bottom-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 120%, 0% 120%);
}
/* layout for example */
.box {
display: inline-block;
vertical-align: top;
background: #338484;
color: #fff;
width: 4em;
height: 2em;
margin: 1em;
padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow shadow-all">all</div>
<div class="box shadow shadow-top">top</div>
<div class="box shadow shadow-right">right</div>
<div class="box shadow shadow-bottom">bottom</div>
<div class="box shadow shadow-left">left</div>
<div class="box shadow shadow-bottom-right">bottom right</div>
_x000D_
Try using this.
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate >= CONVERT(DATE, GETDATE())
You can use myDict.has_key(keyname)
as well to validate if the key exists.
This would work only on versions lower than 3.1. has_key
has been removed from Python 3.1. You should use the in
operator if you are using Python 3.1
note - Lepl is no longer maintained or supported.
RFC 3696 defines "best practices" for URL validation - http://www.faqs.org/rfcs/rfc3696.html
The latest release of Lepl (a Python parser library) includes an implementation of RFC 3696. You would use it something like:
from lepl.apps.rfc3696 import Email, HttpUrl
# compile the validators (do once at start of program)
valid_email = Email()
valid_http_url = HttpUrl()
# use the validators (as often as you like)
if valid_email(some_email):
# email is ok
else:
# email is bad
if valid_http_url(some_url):
# url is ok
else:
# url is bad
Although the validators are defined in Lepl, which is a recursive descent parser, they are largely compiled internally to regular expressions. That combines the best of both worlds - a (relatively) easy to read definition that can be checked against RFC 3696 and an efficient implementation. There's a post on my blog showing how this simplifies the parser - http://www.acooke.org/cute/LEPLOptimi0.html
Lepl is available at http://www.acooke.org/lepl and the RFC 3696 module is documented at http://www.acooke.org/lepl/rfc3696.html
This is completely new in this release, so may contain bugs. Please contact me if you have any problems and I will fix them ASAP. Thanks.
Run the next command:
adb kill-server
adb start-server
Is possible that drawn the next messages DeviceMonitor]Connection attempts: 1 DeviceMonitor]Connection attempts:2
TRY THIS:
Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:
SELECT DATEADD(dd, -30,
CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21)
AS DATETIME))
#For Unable to 'apt update' my Ubuntu 19.04
The repositories for older releases that are not supported (like 11.04, 11.10 and 13.04) get moved to an archive server. There are repositories available at http://old-releases.ubuntu.com.
first break up this file
cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo sed -i -re 's/([a-z]{2}.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
then
sudo apt-get update && sudo apt-get dist-upgrade
If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:
<input type="text" name="email" id="email"/>
and then I would retrieve the value with JavaScript:
var email = document.getElementById('email').value;
From there, you can do additional processing on the value of 'email'.
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
if overwriteFlag:
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want to overwrite the previous line, or
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I have used this in the past:
html
January<span class="right">2014</span>
Css
.right {
margin-left:100%;
}
Reference - Turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore,Microsoft recommend that you do not work around this problem by turning off the option.
take a list of string as like
List<string> colValListForValidation = new List<string>();
and match string before the task. it will help you bcz all merge cells will have same value
I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-web </artifactId>
<version> 1.2.0.RELEASE </version>
</dependency>
Using zsh
:
a=(*(/N)); echo ${#a}
The N
is a nullglob, /
makes it match directories, #
counts. It will neatly cope with spaces in directory names as well as returning 0
if there are no directories.
One fairly simple alternative is to invoke PowerShell via a shortcut. There is a shortcut property labeled "Start in" that says what directory(folder) to use when the shortcut is invoked.
If the Start In box is blank, it means use the current directory.
When you first create a shortcut to PowerShell in the usual way, the start in box specifies the home directory. If you blank out the start in box, you now have a shortcut to powershell that opens PS in the current directory, whatever that is.
If you now copy this shortcut to the target directory, and use explorer to invoke it, you'll start a PS that's pointed at the target directory.
There's already an accepted answer to this question, but I offer this as another way.
Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD%
or PUSHD
/POPD
, or for /f
nonsense -- just plain old batch functions. -- The directory & file don't even have to exist.
CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%
ECHO "%BLAH%"
:: ========== FUNCTIONS ==========
EXIT /B
:NORMALIZEPATH
SET RETVAL=%~f1
EXIT /B
The idea behind StandardScaler
is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).
With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:
Sub Pause()
WScript.Echo ("Press Enter to continue")
z = WScript.StdIn.ReadLine()
End Sub
More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx
The at
command exists specifically for this purpose (unlike cron
which is intended for scheduling recurring tasks).
at $(cat file) </path/to/script
To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
Advanced way to check the exact word, that we need to find in a long string:
import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock"
for m in re.finditer(r"\bof\b", text):
if m.group(0):
print "Present"
else:
print "Absent"
Have you tried to correct the syntax like this?:
create or replace procedure temp_proc AS
begin
DBMS_OUTPUT.PUT_LINE('Test');
end;
private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Do code here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
Toast toast = Toast.makeText(
getActivity(),
"An error is occurred due to some problem",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
s.length() - s.replaceAll(" ", "").length()
returns you number of spaces.
There are more ways. For example"
int spaceCount = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
etc., etc.
In your case you tried to split string using \t
- TAB. You will get right result if you use " "
instead. Using \s
may be confusing since it matches all whitepsaces - regular spaces and TABs.
As a supplement to the question and above answers there is also an important difference between plt.subplots()
and plt.subplot()
, notice the missing 's'
at the end.
One can use plt.subplots()
to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.
# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)
Whereas, you can use plt.subplot()
if you want to add the subplots separately. It returns only the axis of one subplot.
fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1)
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)
However, plt.subplots()
is preferred because it gives you easier options to directly customize your whole figure
# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)
whereas, with plt.subplot()
, one will have to specify individually for each axis which can become cumbersome.
There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features
Features:
The Python documentation does explain it.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
For mysql 5.7.21 I use the following and works fine:
CREATE TABLE Posts
(
modified_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()
This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
For the allowed characters you can use
^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$
to validate a complete string that should consist of only allowed characters. Note that -
is at the end (because otherwise it'd be a range) and a few characters are escaped.
For the invalid characters you can use
[<>'"/;`%]
to check for them.
To combine both into a single regex you can use
^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])
but you'd need a regex engine that allows lookahead.
:hover
is a pseudoclass, so you can put your CSS declarations there:
a:hover {
color: #f00;
}
You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:
.some-class,
a:hover {
color: #f00;
}
First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert
if(tv.tv_usec<10)
{
printf("00000");
}
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
printf("0000");
}
and so on...
If the activity created by yourself, you can try this in the Activity:
@Override
public void setRequestedOrientation(int requestedOrientation) {
try {
super.setRequestedOrientation(requestedOrientation);
} catch (IllegalStateException e) {
// Only fullscreen activities can request orientation
e.printStackTrace();
}
}
This should be the easiest solution.
Here is the Koltin style, I use this in my project and it works very well:
this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
val x = event.x
val y = event.y
when(event.action) {
MotionEvent.ACTION_DOWN -> {
Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
}
MotionEvent.ACTION_MOVE -> {
Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
}
MotionEvent.ACTION_UP -> {
Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
}
}
return@OnTouchListener true
})
To fix this problem, you must edit your php.ini (or extensions.ini) file and comment-out the extensions that are already compiled-in. For example, after editing, your ini file may look like the lines below:
;extension=pcre.so
;extension=spl.so
Source: http://www.somacon.com/p520.php
If you want to check all of your input matches,
>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
if you want to check at least one match,
>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
If you want to run a script to a database:
mysql -u user -p data_base_name_here < db.sql
Collation can be set at various levels:
So you could have a Case Sensitive Column in a Case Insensitive database. I have not yet come across a situation where a business case could be made for case sensitivity of a single column of data, but I suppose there could be.
Check Server Collation
SELECT SERVERPROPERTY('COLLATION')
Check Database Collation
SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;
Check Column Collation
select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
Hmm.
POSIX pthread_exit
description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:
After a thread has terminated, the result of access to local (auto) variables of the thread is
undefined. Thus, references to local variables of the exiting thread should not be used for
the pthread_exit() value_ptr parameter value.
Which seems contrary to the idea that local main() thread variables will remain accessible.
That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:
{type(str()): do_something_with_a_string,
type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()
A bit more concise and pythonic wouldn't you say?
Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:
{str: do_something_with_a_string,
dict: do_something_with_a_dict}.get(type(x), errorhandler)()
Just define <body onload="aFunction()">
that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }
.
We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.
After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..
So, Do:
1) open the gunicorn configuration file
2) set the TIMEOUT to what ever you need - the value is in seconds
NUM_WORKERS=3
TIMEOUT=120
exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE
Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.
I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.
First of all you should avoid to put css in your html tags. Like align="center"
.
Put stuff like that in your css since it is much clearer and won't deprecate that fast.
If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.
Example css:
@media screen and (min-width: 100px) and (max-width: 199px)
{
.button
{
width: 25px;
}
}
@media screen and (min-width: 200px) and (max-width: 299px)
{
.button
{
width: 50px;
}
}
You can use any css you want inside a media query.
http://www.w3.org/TR/css3-mediaqueries/
Bind any html input
<input id="element-to-bind" type="text">
define two functions:
function bindValue(objectToBind) {
var elemToBind = document.getElementById(objectToBind.id)
elemToBind.addEventListener("change", function() {
objectToBind.value = this.value;
})
}
function proxify(id) {
var handler = {
set: function(target, key, value, receiver) {
target[key] = value;
document.getElementById(target.id).value = value;
return Reflect.set(target, key, value);
},
}
return new Proxy({id: id}, handler);
}
use the functions:
var myObject = proxify('element-to-bind')
bindValue(myObject);
Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:
<Directory ..>
...
AllowOverride None
...
</Directory>
Should be changed to
AllowOverride All
And you'll be able to change directives in .htaccess files.
As of Django 1.2, you can use exists()
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists
if some_queryset.filter(pk=entity_id).exists():
print("Entry contained in queryset")
It supports lists, but not as a separate data structure (ignoring arrays for the moment).
The for
loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:
for i in 1 2 3; do
echo "$i"
done
or via parameter expansion:
listVar="1 2 3"
for i in $listVar; do
echo "$i"
done
or command substitution:
for i in $(echo 1; echo 2; echo 3); do
echo "$i"
done
An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:
array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do # The quotes are necessary here
echo "$i"
done
list='"item 1" "item 2" "item 3"'
for i in $list; do
echo $i
done
for i in "$list"; do
echo $i
done
for i in ${array[@]}; do
echo $i
done
I added it to a function on document ready. If there is no submit button on the form (all of my Jquery Dialog Forms don't have submit buttons), append it.
$(document).ready(function (){
addHiddenSubmitButtonsSoICanHitEnter();
});
function addHiddenSubmitButtonsSoICanHitEnter(){
var hiddenSubmit = "<input type='submit' style='position: absolute; left: -9999px; width: 1px; height: 1px;' tabindex='-1'/>";
$("form").each(function(i,el){
if($(this).find(":submit").length==0)
$(this).append(hiddenSubmit);
});
}
After reading Byte Commander's answer, I want to introduce a tiny possible improvement:
You can generate a regexp that will match either n
words, as long as your n
is predetermined. For instance, if I want to match between 1 and 3 words, the regexp:
^([A-Z]+)(?:,([A-Z]+))?(?:,([A-Z]+))?$
will match the next sentences, with one, two or three capturing groups.
HELLO,LITTLE,WORLD
HELLO,WORLD
HELLO
You can see a fully detailed explanation about this regular expression on Regex101.
As I said, it is pretty easy to generate this regexp for any groups you want using your favorite language. Since I'm not much of a swift guy, here's a ruby example:
def make_regexp(group_regexp, count: 3, delimiter: ",")
regexp_str = "^(#{group_regexp})"
(count - 1).times.each do
regexp_str += "(?:#{delimiter}(#{group_regexp}))?"
end
regexp_str += "$"
return regexp_str
end
puts make_regexp("[A-Z]+")
That being said, I'd suggest not using regular expression in that case, there are many other great tools from a simple split
to some tokenization patterns depending on your needs. IMHO, a regular expression is not one of them. For instance in ruby I'd use something like str.split(",")
or str.scan(/[A-Z]+/)
The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.
Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.
I find it much easier to "extend" via assigning in a bigger matrix. E.g.
import numpy as np
p = np.array([[1,2], [3,4]])
g = np.array(range(20))
g.shape = (4,5)
g[0:2, 0:2] = p
Here are the arrays:
p
array([[1, 2],
[3, 4]])
g
:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
and the resulting g
after assignment:
array([[ 1, 2, 2, 3, 4],
[ 3, 4, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
To avoid possible overlapping of execution, use a locking mechanism as described in that thread.
SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.
You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.
If the table was already created, and you were lazy enough not to specify the columns in the fields names input, then all you have to do is to select the empty columns at right to the file content and delete them.
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
You can do it by making form and displaying it using ShowDialogBox....
Form.ShowDialog Method
- Shows the form as a modal dialog box.
Example:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
Replace Your JS with
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Source link
public class DeleteFile {
public static void main(String[] args) {
String path="D:\test";
File file = new File(path);
File[] files = file.listFiles();
for (File f:files)
{if (f.isFile() && f.exists)
{ f.delete();
system.out.println("successfully deleted");
}else{
system.out.println("cant delete a file due to open or error");
} } }}
Find from root path find / -name "index.html"
Find from current path find . -name "index.html"
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:
alt + n
alt + e
;
(that's a semicolon)C:\Python27
windows key + r
to bring up the run dialog. Type in python
and press enter.Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class
git reset --hard
make changes, then do
git add -A
git commit --amend --no-edit
or
git add -A
git commit --amend -m "commit_message"
and then
git push origin master --force
--force will rewrite that commit you've reseted to in the first step.
Don't do this, because you're about to go against the whole idea of VCS systems and git in particular. The only good method is to create new and delete unneeded branch. See git help branch
for info.
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
In my case the problem was that GNOME keyring was holding an invalid passphrase for the ssh key to be used. After spending indecent amount of time troubleshooting this issue I ran seahorse
and found the entry to hold empty string. I can only guess that it was caused by mistyping the passphrase at first use some time earlier, and then probably cancelling the requester or so in order to fall back to command line. Updating the entry with correct passphrase immediately solved the problem. Deleting that entry (from "login" keyring) and reentering passphrase at that first prompt (and checking the appropriate checkbox) solves this too. Now agent gets the correct passphrase from the unlocked at login keyring named "login" and neither asks for passphrase nor "refuses operation" anymore. Of course YMMV.
I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!
::before
and ::after
pseudo-elementsSnappySnippet is open source, and you can find the code on GitHub.
Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.
At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules()
, however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.
Then, I've started from something that @CollectiveCognition suggested - getComputedStyle()
. However, I really wanted to separate CSS form HTML instead of inlining all styles.
The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.
Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle()
returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>
. The logic here was that there are no style sheets in an empty <iframe>
, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.
Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px
and then border-color: black;
, border-width: 1px
itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.
The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit-
prefixed properties that I've never hear of (-webkit-app-region
? -webkit-text-emphasis-position
?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin
, -webkit-perspective-origin
etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.
The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li>
with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...}
I got #LI_1, #LI_2 {...}
.
Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML
property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML
needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style
, data-ng-repeat
etc.).
Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.
…or a shorter try:
library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
Typically, I would suggest that you use the <optgroup>
option, as that gives some nice styling and indenting to the element.
The HTML element creates a grouping of options within a element. (Source: MDN Web Docs:
<optgroup>
.
But, since an <optgroup>
cannot be a selected value, you can make an <option selected disabled>
and then stylize it with CSS so that it behaves like an <optgroup>
....
.optionGroup {
font-weight: bold;
font-style: italic;
}
_x000D_
<select>
<option class="optionGroup" selected disabled>Choose one</option>
<option value="sydney" class="optionChild"> Sydney</option>
<option value="melbourne" class="optionChild"> Melbourne</option>
<option value="cromwell" class="optionChild"> Cromwell</option>
<option value="queenstown" class="optionChild"> Queenstown</option>
</select>
_x000D_
The current answers are outdated. You should be able to use #error version
(at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:
error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.
Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.
The way to do this is to set the EnableHeadersVisualStyles
flag for the data grid view to False
, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor
property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
If you do not set the EnableHeadersVisualStyles
flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
Let's polyfill:
if(!AbortController){
class AbortController {
constructor() {
this.aborted = false;
this.signal = this.signal.bind(this);
}
signal(abortFn, scope) {
if (this.aborted) {
abortFn.apply(scope, { name: 'AbortError' });
this.aborted = false;
} else {
this.abortFn = abortFn.bind(scope);
}
}
abort() {
if (this.abortFn) {
this.abortFn({ reason: 'canceled' });
this.aborted = false;
} else {
this.aborted = true;
}
}
}
const originalFetch = window.fetch;
const customFetch = (url, options) => {
const { signal } = options || {};
return new Promise((resolve, reject) => {
if (signal) {
signal(reject, this);
}
originalFetch(url, options)
.then(resolve)
.catch(reject);
});
};
window.fetch = customFetch;
}
Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
Try this:
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
[edit]
// With explicit casting
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos, yPos, width, height);
g.fillRect(
(int)r.getX(),
(int)r.getY(),
(int)r.getWidth(),
(int)r.getHeight()
);
}
i use this piece of code to stop execution:
throw new FatalError("!! Stop JS !!");
you will get a console error though but it works good for me.
XAMPP - Port 80 in use by “Unable to open process” with PID 4! 12
run the comment in cmd tasklist
and find which the PID and process name related to this now open window task manager
you can also open window task manager by using CTRL+ALT+DEL
now click on the process tab and find the name which using PID and right click on that and end process
now again restart the xampp
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
DDL is Data Definition Language : Specification notation for defining the database schema. It works on Schema level.
DDL commands are:
create,drop,alter,rename
For example:
create table account (
account_number char(10),
balance integer);
DML is Data Manipulation Language .It is used for accessing and manipulating the data.
DML commands are:
select,insert,delete,update,call
For example :
update account set balance = 1000 where account_number = 01;
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
You can also use string.match().
var string1 = "aBc";
var match = string1.match(/AbC/i);
if(match) {
}
See this solution: Bootstrap TouchCarousel. A drop-in perfection for Twitter Bootstrap's Carousel (v3) to enable gestures on touch devices. http://ixisio.github.io/bootstrap-touch-carousel/
This will be helpful for some people:
From MySQL command line:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.
Therefore, the first thing to do is to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.
Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.
FLUSH PRIVILEGES;
Your changes will now be in effect.
For more information: http://dev.mysql.com/doc/refman/5.6/en/grant.html
If you are not comfortable with the command line then you can use a client like MySQL workbench, Navicat or SQLyog
Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)
So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:
git log path/to/file
If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch
option:
git log -p path/to/file
Or, if you prefer the graphical view of gitk
gitk path/to/file
You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.
Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:
# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit
(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add
to add it to the index in preparation for committing.)
If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git
can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
Here is a working example, the red links can't be right clicked anymore.
$("ul.someLinks1 a").each(function(i, obj) {_x000D_
_x000D_
$(obj).on("contextmenu",function(){_x000D_
return false;_x000D_
}); _x000D_
_x000D_
$(obj).css("color", "red");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul class="someLinks1">_x000D_
<li><a href="www.google.de">google</a></li>_x000D_
<li><a href="www.stackoverflow.de">stackoverflow</a></li>_x000D_
<li><a href="www.test.de">test</a></li>_x000D_
</ul>_x000D_
_x000D_
<ul class="someLinks2">_x000D_
<li><a href="www.foobar.de">foobar</a></li>_x000D_
<li><a href="www.foo.de">foo</a></li>_x000D_
<li><a href="www.bar.de">bar</a></li>_x000D_
</ul>
_x000D_
It happened for me after my backup software changed the permission to my user directory. I opened it in File Explorer, it prompted me to set permissions and it fixed the issue.
FYI: Android has a special directory under "\User\.android" If you can't access it, it won't prompt you.
As a bare minimum:
tsconfig:
"lib": [
"es2015"
]
and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
http://jsfiddle.net/LRD5x/30/ A simple solution.
HTML
<form ng-submit="sendForm($event)" ng-class={submitted:submitted}>
JS
$scope.sendForm = function($event) {
$event.preventDefault()
$scope.submitted = true
};
CSS
.submitted input.ng-invalid:not(:focus) {
background-color: #FA787E;
}
input.ng-invalid ~ .alert{
display:none;
}
.submitted input.ng-invalid ~ .alert{
display:block;
}
you need only set default value to parameters(you do not need the Route attribute):
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }
put this code in your html header:
<style type="text/css">
html {
overflow: auto;
}
</style>
This is also possible:
a {
all: unset;
}
unset: This keyword indicates to change all the properties applying to the element or the element's parent to their parent value if they are inheritable or to their initial value if not. unicode-bidi and direction values are not affected.
Source: Mozilla description of all
Try:
String.Format("{0:0.00}", Convert.ToDecimal(totalPrice));
Before importing just make sure you have max_allowed_pack value set some thing large else you will get an error: Error 2006 MySQL server gone away.
Then try the command: mysql -u root -p database_name < file.sql
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
Simple approach is close window on saveComand Implementation. Use below code to close window.
Application.Current.Windows[1].Close();
It will close the child window.
var input = "12342";
var output = input.Substring(0, input.Length - 1);
or
var output = input.Remove(input.Length - 1);
Simplest is to use Match
If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
' String is in range
I received a similar error message once, in my case it was because my pandas dataframe contained NULLs. I will recommend to try & handle this in pandas before converting to spark (this resolved the issue in my case).
For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/
On a Mac:
brew install swaks
swaks --to [email protected] --server smtp.example.com
While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.
Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:
home = System.getenv('HOME')
It helps to keep in mind that anything that works in pure Java will work in Gradle too.
This could help, by the way:
The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.
http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.
This is how to do it using Java 8+ :
boolean isJohnAlive = list.stream().anyMatch(o -> o.getName().equals("John"));
Unlike innerText
, though, innerHTML
lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText
retrieves and sets the content of the tag as plain text, whereas innerHTML
retrieves and sets the content in HTML format.
The idiomatic way to do this in Python is to use rstrip('\n'):
for line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\n'
line = line.rstrip('\n')
process(line)
Each of the other alternatives has a gotcha:
It cross-browser compliant and can perform a binary search if your data is sorted.
_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array. Uses the native indexOf function unless it's missing. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search.
//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
alert('true');
}else{
alert('false');
}
//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
alert('true');
}else{
alert('false');
}
declare @hash nvarchar(50)
--declare @hash varchar(50)
set @hash = '1111111-2;20190110143334;001' -- result a5cd84bfc56e245bbf81210f05b7f65f
declare @value varbinary(max);
set @value = convert(varbinary(max),@hash);
select
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '1111111-2;20190110143334;001')),3,32) as 'OK'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @hash)),3,32) as 'ERROR_01'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',convert(varbinary(max),@hash))),3,32) as 'ERROR_02'
,SUBSTRING(sys.fn_sqlvarbasetostr(sys.fn_repl_hash_binary(convert(varbinary(max),@hash))),3,32)
,SUBSTRING(sys.fn_sqlvarbasetostr(master.sys.fn_repl_hash_binary(@value)),3,32)
Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.
Given "foo.csv" as follows:
FirstColumn,SecondColumn
asdf,1234
qwer,5678
Use DictReader like this:
import csv
with open('foo.csv') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
print(row['FirstColumn']) # Access by column header instead of column number
print(row['SecondColumn'])
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
For older versions of jQuery
jQuery().jquery (or)
jQuery().fn.jquery
For newer versions of jQuery
$().jquery (or)
$().fn.jquery
memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:
(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
If you don't yet have the distinguished name, you can search for it with:
(&(objectCategory=group)(cn=myCustomGroup))
and return the attribute distinguishedName
. Case may matter.
I'd recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.
This code belongs in file.js:
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
alert('Hello World! -' + _args[0]);
}
};
}());
And in your html file:
<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["somevalue", 1, "controlId"]);
MYLIBRARY.helloWorld();
</script>
I think you both are right. The later answer works fine but its like setting a global option so you have to do the following:
$.ajaxSetup({
async: false
});
//ajax call here
$.ajaxSetup({
async: true
});
Add only 
 for breaking line, no need to write any CSS or javascript.
textarea{_x000D_
width:300px;_x000D_
height:100px;_x000D_
_x000D_
}
_x000D_
<textarea placeholder='This is a line this 
should be a new line'></textarea>_x000D_
_x000D_
<textarea placeholder=' This is a line _x000D_
_x000D_
should this be a new line?'></textarea>
_x000D_
Comparing as lower or as upper case? (common enough issue)
Both below will return 0 with strcicmpL("A", "a")
and strcicmpU("A", "a")
.
Yet strcicmpL("A", "_")
and strcicmpU("A", "_")
can return different signed results as '_'
is often between the upper and lower case letters.
This affects the sort order when used with qsort(..., ..., ..., strcicmp)
. Non-standard library C functions like the commonly available stricmp()
or strcasecmp()
tend to be well defined and favor comparing via lowercase. Yet variations exist.
int strcicmpL(char const *a, char const *b) {
while (*b) {
int d = tolower(*a) - tolower(*b);
if (d) {
return d;
}
a++;
b++;
}
return tolower(*a);
}
int strcicmpU(char const *a, char const *b) {
while (*b) {
int d = toupper(*a) - toupper(*b);
if (d) {
return d;
}
a++;
b++;
}
return toupper(*a);
}
char
can have a negative value. (not rare)
touppper(int)
and tolower(int)
are specified for unsigned char
values and the negative EOF
. Further, strcmp()
returns results as if each char
was converted to unsigned char
, regardless if char
is signed or unsigned.
tolower(*a); // Potential UB
tolower((unsigned char) *a); // Correct (Almost - see following)
char
can have a negative value and not 2's complement. (rare)
The above does not handle -0
nor other negative values properly as the bit pattern should be interpreted as unsigned char
. To properly handle all integer encodings, change the pointer type first.
// tolower((unsigned char) *a);
tolower(*(const unsigned char *)a); // Correct
Locale (less common)
Although character sets using ASCII code (0-127) are ubiquitous, the remainder codes tend to have locale specific issues. So strcasecmp("\xE4", "a")
might return a 0 on one system and non-zero on another.
Unicode (the way of the future)
If a solution needs to handle more than ASCII consider a unicode_strcicmp()
. As C lib does not provide such a function, a pre-coded function from some alternate library is recommended. Writing your own unicode_strcicmp()
is a daunting task.
Do all letters map one lower to one upper? (pedantic)
[A-Z] maps one-to-one with [a-z], yet various locales map various lower case chracters to one upper and visa-versa. Further, some uppercase characters may lack a lower case equivalent and again, visa-versa.
This obliges code to covert through both tolower()
and tolower()
.
int d = tolower(toupper(*a)) - tolower(toupper(*b));
Again, potential different results for sorting if code did tolower(toupper(*a))
vs. toupper(tolower(*a))
.
Portability
@B. Nadolson recommends to avoid rolling your own strcicmp()
and this is reasonable, except when code needs high equivalent portable functionality.
Below is an approach that even performed faster than some system provided functions. It does a single compare per loop rather than two by using 2 different tables that differ with '\0'
. Your results may vary.
static unsigned char low1[UCHAR_MAX + 1] = {
0, 1, 2, 3, ...
'@', 'a', 'b', 'c', ... 'z', `[`, ... // @ABC... Z[...
'`', 'a', 'b', 'c', ... 'z', `{`, ... // `abc... z{...
}
static unsigned char low2[UCHAR_MAX + 1] = {
// v--- Not zero, but A which matches none in `low1[]`
'A', 1, 2, 3, ...
'@', 'a', 'b', 'c', ... 'z', `[`, ...
'`', 'a', 'b', 'c', ... 'z', `{`, ...
}
int strcicmp_ch(char const *a, char const *b) {
// compare using tables that differ slightly.
while (low1[*(const unsigned char *)a] == low2[*(const unsigned char *)b]) {
a++;
b++;
}
// Either strings differ or null character detected.
// Perform subtraction using same table.
return (low1[*(const unsigned char *)a] - low1[*(const unsigned char *)b]);
}
&&
and ||
take scalar inputs and short-circuit always. |
and &
take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.
See these doc pages for more information.
I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.
For custom images you created yourself, you can do without the plugin:
Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.
It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.
Use break;
to escape the first loop:
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
break;
}
If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:
boolean breakFlag = false;
while (!breakFlag)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
breakFlag = true;
break;
}
}
}
Or, if you want to just exit the function completely from within the nested loop, put in a return;
instead of a break;
.
But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while
guards.
I've tried to create a utils class for this, so any activity or fragment can implement this to be simpler.
The code was written with Kotlin & has Java-interop as well.
I'm using coroutine to delay and reset the flag variable. But you can modify it to your needs.
Additional files: SafeToast.kt
lateinit var toast: Toast
fun Context.safeToast(msg: String, length: Int = Toast.LENGTH_LONG, action: (Context) -> Toast = default) {
toast = SafeToast.makeText(this@safeToast, msg, length).apply {
// do anything new here
action(this@safeToast)
show()
}
}
fun Context.toastSpammable(msg: String) {
cancel()
safeToast(msg, Toast.LENGTH_SHORT)
}
fun Fragment.toastSpammable(msg: String) {
cancel()
requireContext().safeToast(msg, Toast.LENGTH_SHORT)
}
private val default: (Context) -> Toast = { it -> SafeToast.makeText(it, "", Toast.LENGTH_LONG) }
private fun cancel() {
if (::toast.isInitialized) toast.cancel()
}
ActivityUtils.kt
@file:JvmMultifileClass
@file:JvmName("ActivityUtils")
package your.company.com
import android.app.Activity
import your.company.com.R
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private var backButtonPressedTwice = false
fun Activity.onBackPressedTwiceFinish() {
onBackPressedTwiceFinish(getString(R.string.msg_back_pressed_to_exit), 2000)
}
fun Activity.onBackPressedTwiceFinish(@StringRes message: Int, time: Long) {
onBackPressedTwiceFinish(getString(message), time)
}
fun Activity.onBackPressedTwiceFinish(message: String, time: Long) {
if (backButtonPressedTwice) {
onBackPressed()
} else {
backButtonPressedTwice = true
toastSpammable(message)
GlobalScope.launch {
delay(time)
backButtonPressedTwice = false
}
}
}
Usage in Kotlin
// ActivityA.kt
override fun onBackPressed() {
onBackPressedTwiceFinish()
}
Usage in Java
@Override
public void onBackPressed() {
ActivityUtils.onBackPressedTwiceFinish()
}
This code was inspired by @webserveis here
jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.
to know more about this take a look at the How to internationalize your pages using JQuery?
OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.
There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.
@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.
That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.
The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.
Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:
It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)
It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)
The result using initialized data:
The result using uninitialized data (this is what Mysticial tested):
And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:
Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.
I have fumbled around sometime to reach these considerations:
1- If my application access the database, why the test should not? What if there is something wrong with data access? The tests must know it beforehand and alert myself about the problem.
2- The Repository Pattern is somewhat hard and time consuming.
So I came up with this approach, that I don't think is the best, but fulfilled my expectations:
Use TransactionScope in the tests methods to avoid changes in the database.
To do it it's necessary:
1- Install the EntityFramework into the Test Project. 2- Put the connection string into the app.config file of Test Project. 3- Reference the dll System.Transactions in Test Project.
The unique side effect is that identity seed will increment when trying to insert, even when the transaction is aborted. But since the tests are made against a development database, this should be no problem.
Sample code:
[TestClass]
public class NameValueTest
{
[TestMethod]
public void Edit()
{
NameValueController controller = new NameValueController();
using(var ts = new TransactionScope()) {
Assert.IsNotNull(controller.Edit(new Models.NameValue()
{
NameValueId = 1,
name1 = "1",
name2 = "2",
name3 = "3",
name4 = "4"
}));
//no complete, automatically abort
//ts.Complete();
}
}
[TestMethod]
public void Create()
{
NameValueController controller = new NameValueController();
using (var ts = new TransactionScope())
{
Assert.IsNotNull(controller.Create(new Models.NameValue()
{
name1 = "1",
name2 = "2",
name3 = "3",
name4 = "4"
}));
//no complete, automatically abort
//ts.Complete();
}
}
}
Or just :
var a:Int = 3
var b:Int = 3
println(pow(Double(a),Double(b)))
In my case a misplaced session.clear()
was causing this problem.
Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80>
and </VirtualHost>
After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane
<VirtualHost *:80>
##ServerAdmin [email protected]
DocumentRoot "C:/xampp/htdocs/www"
ServerName example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
Be sure to create the www folder under htdocs
. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html
or index.php
file and place in the www
folder, then go to your browser and test it out localhost/
... Note: if your server is serving php files over html then remember to add localhost/index.html
if the html file is the one you choose to use for this test.
Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add
<VirtualHost *:80>
##ServerAdmin [email protected]
DocumentRoot "C:/xampp/htdocs"
ServerName htdocs.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
LocalDate
.parse( "2021-01-23" )
.isBefore(
LocalDate.now(
ZoneId.of( "Africa/Tunis" )
)
)
… or:
try
{
org.threeten.extra.LocalDateRange range =
LocalDateRange.of(
LocalDate.of( "2021-01-23" ) ,
LocalDate.of( "2021-02-21" )
)
;
if( range.isAfter(
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
) { … }
else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
// Handle error where end is before start.
}
The other answers ignore the crucial issue of time zone.
The other answers use outmoded classes.
The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.
LocalDate
For date-only values, without time-of-day and without time zone, use the LocalDate
class.
LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );
Be aware that while LocalDate
does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.
If all you have is an offset-from-UTC, use ZoneOffset
. If you have a full time zone (continent/region), then use ZoneId
. If you want UTC, use the handy constant ZoneOffset.UTC
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Comparing is easy with isEqual
, isBefore
, and isAfter
methods.
boolean invalidInterval = stop.isBefore( start );
We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.
// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;
LocalDateRange
If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.
ThreeTen-Extra includes an LocalDateRange
class with handy methods such as abuts
, contains
, encloses
, overlaps
, and so on.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator
), there is pyplot.locator_params
,
pyplot.locator_params(nbins=4)
You can specify specific axis in this method as mentioned below, default is both:
# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)
Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:
yourstring = "L" + yourstring + "LL"
Note that you can also create a string with n L
s by using multiplication:
m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)
This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.
You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:
%reset
or menu->restart terminal
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.
If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.
For enable, the generic looks to be the following:
update-rc.d <service> enable
Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers
I had many zombi-jobs, so I used the following script:
for(int x = 1000; x < 1813; x = x + 1) {
Jenkins .instance.getItemByFullName("JOBNAME/BRANCH")
.getBuildByNumber(x)
.finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build"))
}
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;
EDIT: So I was asked to explain what's happening when you do:
int arr[10] = {0, 5, 3, 64};
you create an array with 10 elements and you allocate values for the first 4 elements of the array.
Also keep in mind that arr
starts at index arr[0]
and ends at index arr[9]
- 10 elements
arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;
after that the array contains garbage values / zeroes because you didn't allocated any other values
But you could still allocate 6 more values so when you do
arr[4] = 5;
you allocate the value 5 to the fifth element of the array.
You could do this until you allocate values for the last index of the arr
that is arr[9]
;
Sorry if my explanation is choppy, but I have never been good at explaining things.
This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)
function reply_click(e) {
console.log(e.target.id);
}
_x000D_
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
_x000D_
I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath
Here is an example function:
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
Short version of the same function
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
Output examples
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
Usage
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
You can install and use the pip-autoremove utility to remove a package plus unused dependencies.
# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y
I also searched this answer. Equivalent of command+N on Mac OS for Windows is ctr + alt + insert which @manyways already answered. If you searching this in settings it is in Settings > IDE Settings > Keymap, Other > New ...
You can use disabled attribute to disable the textbox.
document.getElementById('color').disabled = true;
Or how about this?
with some_birthdays as
(
select date '1968-06-09' d from dual union all
select date '1970-06-10' from dual union all
select date '1972-06-11' from dual union all
select date '1974-12-11' from dual union all
select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;
Following is the simple query will list N rows from M+1th row of the table. Replace M and N with your preferred numbers.
Select Top N B.PrimaryKeyColumn from
(SELECT
top M PrimaryKeyColumn
FROM
MyTable
) A right outer join MyTable B
on
A.PrimaryKeyColumn = B.PrimaryKeyColumn
where
A.PrimaryKeyColumn IS NULL
Please let me know whether this is usefull for your situation.
Just use the std::
qualifier in front of string
in your header files.
In fact, you should use it for istream
and ostream
also - and then you will need #include <iostream>
at the top of your header file to make it more self contained.
@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error
Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid']
instead of $objData->token
You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here
This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6
To change dir
foo:
$(MAKE) -C mydir
multi:
$(MAKE) -C / -C my-custom-dir ## Equivalent to /my-custom-dir
You can use following code to clear command line console:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
For further references visit: http://techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html
On Windows (OpenJDK11, Maven 3.6.0, SUREFIRE 3.0.0-M1) I got that root cause:
# Created at 2018-11-14T14:28:15.629
OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000006c7500000, 522190848, 0) failed; error='The paging file is too small for this operation to complete' (DOS error/errno=1455)
and resolved by increasing the paging file size, e.g like this.
Please try adding the double quotes git commit -m "initial commit". This will solve your problem.
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
here is the solution for similar problem which i was facing while extracting name from user profile facebook json object
$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name ;
PostgreSql is very advanced when related to logging techniques
Logs are stored in Installationfolder/data/pg_log folder
. While log settings are placed in postgresql.conf
file.
Log format is usually set as stderr
. But CSV log format is recommended. In order to enable CSV format change in
log_destination = 'stderr,csvlog'
logging_collector = on
In order to log all queries, very usefull for new installations, set min. execution time for a query
log_min_duration_statement = 0
In order to view active Queries on your database, use
SELECT * FROM pg_stat_activity
To log specific queries set query type
log_statement = 'all' # none, ddl, mod, all
For more information on Logging queries see PostgreSql Log.
Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.
Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).
I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.
Happy hacking!
Consider two class-typed variables:
class Boo { ... };
Boo b0; // mutable object
const Boo b1; // non-mutable object
Now you are able to call any member function of Boo
on b0
, but only const
-qualified member functions on b1
.
You can loop through the columns collection of the datatable.
VB
Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
Console.WriteLine(column.ColumnName)
Next
C#
DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}
Hope this helps!
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().
FYI, it's not terribly difficult to make a list that has a push method:
>>> class StackList(list):
... def push(self, item):
... self.append(item)
...
>>> x = StackList([1,2,3])
>>> x
[1, 2, 3]
>>> x.push(4)
>>> x
[1, 2, 3, 4]
A stack is a somewhat abstract datatype. The idea of "pushing" and "popping" are largely independent of how the stack is actually implemented. For example, you could theoretically implement a stack like this (although I don't know why you would):
l = [1,2,3]
l.insert(0, 1)
l.pop(0)
...and I haven't gotten into using linked lists to implement a stack.
You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).
Take a look at the following link for more information.
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
English definition:
In HTML context:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
Let's take the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
class
is reserved keyword in JS). But actually 2 properties, classList
and className
.Using jQuery function
var valFileDownloadPath = 'http//:'+'your url';
window.open(valFileDownloadPath , '_blank');
This can be done in [N + log(N) - 2] time, which is slightly better than the loose upper bound of 2N (which can be thought of O(N) too).
The trick is to use binary recursive calls and "tennis tournament" algorithm. The winner (the largest number) will emerge after all the 'matches' (takes N-1 time), but if we record the 'players' of all the matches, and among them, group all the players that the winner has beaten, the second largest number will be the largest number in this group, i.e. the 'losers' group.
The size of this 'losers' group is log(N), and again, we can revoke the binary recursive calls to find the largest among the losers, which will take [log(N) - 1] time. Actually, we can just linearly scan the losers group to get the answer too, the time budget is the same.
Below is a sample python code:
def largest(L):
global paris
if len(L) == 1:
return L[0]
else:
left = largest(L[:len(L)//2])
right = largest(L[len(L)//2:])
pairs.append((left, right))
return max(left, right)
def second_largest(L):
global pairs
biggest = largest(L)
second_L = [min(item) for item in pairs if biggest in item]
return biggest, largest(second_L)
if __name__ == "__main__":
pairs = []
# test array
L = [2,-2,10,5,4,3,1,2,90,-98,53,45,23,56,432]
if len(L) == 0:
first, second = None, None
elif len(L) == 1:
first, second = L[0], None
else:
first, second = second_largest(L)
print('The largest number is: ' + str(first))
print('The 2nd largest number is: ' + str(second))
In modern browsers, it should be like
try() {
if (!$("#element").size()) {
window.requestAnimationFrame(try);
} else {
// do your stuff
}
};
componentDidMount(){
this.try();
}
You're done!
I think the following should work:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
In this case, the Content-type: application/json
header is automatically added.
In Swift 4.2 and Xcode 10
let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)
//To display multiple lines in label
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping
lbl.sizeToFit()//If required
yourView.addSubview(lbl)
You could use PyMouse. To get the screen size just use the screen_size()
attribute:
from pymouse import PyMouse
m = PyMouse()
a = m.screen_size()
a
will return a tuple, (X, Y)
, where X
is the horizontal position and Y
is the vertical position.
As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just use
d.
No you can't, respectively, not really, as manual of extends
keyword says:
An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.
However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.
You CAN extend one class, with another and another with another and so on...
So pretty simple example on this would be:
class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...
As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.
...And finally example with some output:
class A{
function a_hi(){
echo "I am a of A".PHP_EOL."<br>".PHP_EOL;
}
}
class B extends A{
function b_hi(){
echo "I am b of B".PHP_EOL."<br>".PHP_EOL;
}
}
class C extends B{
function c_hi(){
echo "I am c of C".PHP_EOL."<br>".PHP_EOL;
}
}
$myTestInstance = new C();
$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();
Which outputs
I am a of A
I am b of B
I am c of C
You can initialize a Dictionary
(and other collections) inline. Each member is contained with braces:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
See Microsoft Docs for details.
Variables are comprised of fields and non-fields.
Fields can be either:
Non-fields can be either:
In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.
Basic Example (excuse me for my syntax, I am just a beginner)
Class {
//fields
method1 {
//non-fields
}
}