You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
one easy way by using Pandas: (here I want to use mean normalization)
normalized_df=(df-df.mean())/df.std()
to use min-max normalization:
normalized_df=(df-df.min())/(df.max()-df.min())
Edit: To address some concerns, need to say that Pandas automatically applies colomn-wise function in the code above.
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
Another useful option in IDEA to switch off or keep checked if you really need that:
Preferences -> Code Style -> Detect and use existing file indents for editing
if your team is going to switch to tab formatting with existing code written with spaces, uncheck that
you can get all product information from following code
$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);
$product_data["id"]=$_product->getId();
$product_data["name"]=$_product->getName();
$product_data["short_description"]=$_product->getShortDescription();
$product_data["description"]=$_product->getDescription();
$product_data["price"]=$_product->getPrice();
$product_data["special price"]=$_product->getFinalPrice();
$product_data["image"]=$_product->getThumbnailUrl();
$product_data["model"]=$_product->getSku();
$product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId) ->load($_product->getId());
$product_data["rating"]=($summaryData['rating_summary']*5)/100;
$product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');
if($_product->isSalable() ==1)
$product_data["in_stock"]=1;
else
$product_data["in_stock"]=0;
echo "<pre>";
print_r($product_data);
//echo "</pre>";
If you want to work on Android 4.4 and above, try this. I refer to Harpreet's answer and this link. Android and the transparent status bar
First, call setStatusBarColored method in Activity's onCreate method(I put it in a util class). I use a image here, you can change it to use a color.
public static void setStatusBarColored(Activity context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Window w = context.getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
int statusBarHeight = getStatusBarHeight(context);
View view = new View(context);
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.getLayoutParams().height = statusBarHeight;
((ViewGroup) w.getDecorView()).addView(view);
view.setBackground(context.getResources().getDrawable(R.drawable.navibg));
}
}
public static int getStatusBarHeight(Activity context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
The color of the status bar has been changed, but the navi bar is cut off, so we need to set the margin or offset of the navi bar in the onCreate method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, (int)(this.getResources().getDimension(R.dimen.navibar_height)));
layoutParams.setMargins(0, Utils.getStatusBarHeight(this), 0, 0);
this.findViewById(R.id.linear_navi).setLayoutParams(layoutParams);
}
Then the status bar will look like this.
This setting needs to be set:
SET SERVEROUTPUT ON
The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.
The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.
The code he wrote would better as:
func Exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
But I suggest this instead:
func Exists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
There are two ways-
whoami
or
echo $USER
if some one is using AppCompatEditText then you need to set inputType="textMultiLine" here is the code you can copy
<androidx.appcompat.widget.AppCompatEditText
android:padding="@dimen/_8sdp"
android:id="@+id/etNote"
android:minLines="6"
android:singleLine="false"
android:lines="8"
android:scrollbars="vertical"
android:background="@drawable/rounded_border"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_25sdp"
android:layout_marginTop="32dp"
android:layout_marginEnd="@dimen/_25sdp"
android:autofillHints=""
android:gravity="start|top"
android:inputType="textMultiLine"
/>
for background
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/_5sdp"/>
<stroke android:width="1dp" android:color="#C8C8C8"/>
</shape>
This will help you get all deleted files between commits without specifying the path, useful if there are a lot of files deleted.
git diff --name-only --diff-filter=D $commit~1 $commit | xargs git checkout $commit~1
It's a shortening for this:
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
And |
is a bit-wise OR.
IBAction func button(_ sender: UIButton) {
if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
..............
}
}
X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting
X-XSS-Protection: 0
I know it's old question but it still in first 10 links in google.
It is not very efficient to save rows one-by-one because it cause database call in the loop and you better avoid that, especially when you need to insert huge portions of data.
It's better (and significantly faster) to use batch insert.
INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
('s1', 'supplier1', 1.111),
('s2', 'supplier2', '2.222')
You can build such a query manually and than do Model.connection.execute(RAW SQL STRING)
(not recomended)
or use gem activerecord-import
(it was first released on 11 Aug 2010) in this case just put data in array rows
and call Model.import rows
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}
IQueryable is faster than IEnumerable if we are dealing with huge amounts of data from database because,IQueryable gets only required data from database where as IEnumerable gets all the data regardless of the necessity from the database
You can do it in a number of ways.
IF EXISTS(select * from ....)
begin
-- select * from ....
end
else
-- do something
Or you can use IF NOT EXISTS , @@ROW_COUNT
like
select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end
I found a similar error when i tried to access the bigquery from google.cloud.
from google.cloud import bigquery
Error was resolved after i install the google.cloud from conda-forge community.
conda install -c conda-forge google-cloud-bigquery
The Shared Source Device Emulator contains buildable source code to a PocketPC/Smartphone emulator (Requires Visual Studio, runs on Windows). I worked on V1 and V2 of the binary release.
It tackles many emulation issues: - efficient address translation from guest virtual to guest physical to host virtual - JIT compilation of guest code - simulation of peripheral devices such as network adapters, touchscreen and audio - UI integration, for host keyboard and mouse - save/restore of state, for simulation of resume from low-power mode
If you are using SQL Server 2012 and above, you can use FORMATMESSAGE
. eg.
DECLARE @s NVARCHAR(50) = 'World';
DECLARE @d INT = 123;
SELECT FORMATMESSAGE('Hello %s, %d', @s, @d)
-- RETURNS 'Hello World, 123'
More examples from MSDN: FORMATMESSAGE
SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);
SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Hello %s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
NOTES:
FORMATMESSAGE
comes up as a (harmless) errorIn your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
From Start | Run open a command window. Assuming your environmental variables are set correctly start with the following:
C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.
SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]
PL/SQL procedure successfully completed.
SQL>quit
then open browser and use 3010 port.
public void excelRead(string sheetName)
{
Excel.Application appExl = new Excel.Application();
Excel.Workbook workbook = null;
try
{
string methodName = "";
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
//Opening Excel file(myData.xlsx)
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(sheetName, Missing.Value, ReadOnly: false);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
int rCnt1 = 0;
int cCnt1 = 0;
for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++)
{
for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++)
{
if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y")
{
methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2;
Type metdType = this.GetType();
MethodInfo mthInfo = metdType.GetMethod(methodName);
if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum")
{
StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 3].Value2);
StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2);
object[] mParam1 = new object[] { StaticVariable.intParam1, StaticVariable.intParam2 };
object result = mthInfo.Invoke(this, mParam1);
StaticVariable.intOutParam1 = Convert.ToInt32(result);
NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty;
}
else
{
object[] mParam = new object[] { };
mthInfo.Invoke(this, mParam);
NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = StaticVariable.outParam1 != "" ? StaticVariable.outParam1 : String.Empty;
NwSheet.Cells[rCnt1, cCnt1 + 6].Value2 = StaticVariable.outParam2 != "" ? StaticVariable.outParam2 : String.Empty;
}
NwSheet.Cells[rCnt1, cCnt1 + 1].Value2 = StaticVariable.resultOut;
NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = StaticVariable.resultDescription;
}
else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "N")
{
MessageBox.Show("Result is No");
}
else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "EOF")
{
MessageBox.Show("End of File");
}
}
}
workbook.Save();
workbook.Close(true, Missing.Value, Missing.Value);
appExl.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ShtRange);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(NwSheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExl);
}
catch (Exception)
{
workbook.Close(true, Missing.Value, Missing.Value);
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.CleanupUnusedObjectsInCurrentContext();
}
}
//code for reading excel data in datatable
public void testExcel(string sheetName)
{
try
{
MessageBox.Show(sheetName);
foreach(Process p in Process.GetProcessesByName("EXCEL"))
{
p.Kill();
}
//string fileName = "E:\\inputSheet";
Excel.Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
// creat a Application object
oXL = new Excel.Application();
// get WorkBook object
oWB = oXL.Workbooks.Open(sheetName);
// get WorkSheet object
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
System.Data.DataTable dt = new System.Data.DataTable();
//DataSet ds = new DataSet();
//ds.Tables.Add(dt);
DataRow dr;
StringBuilder sb = new StringBuilder();
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
// get data columns
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j];
string strValue = oRng.Text.ToString();
dt.Columns.Add(strValue, System.Type.GetType("System.String"));
}
//string colString = sb.ToString().Trim();
//string[] colArray = colString.Split(':');
// get data in cell
for (int i = 2; i <= iValue; i++)
{
dr = dt.NewRow();
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
string strValue = oRng.Text.ToString();
dr[j - 1] = strValue;
}
dt.Rows.Add(dr);
}
if(StaticVariable.dtExcel != null)
{
StaticVariable.dtExcel.Clear();
StaticVariable.dtExcel = dt.Copy();
}
else
StaticVariable.dtExcel = dt.Copy();
oWB.Close(true, Missing.Value, Missing.Value);
oXL.Quit();
MessageBox.Show(sheetName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
//code for class initialize
public static void startTesting(TestContext context)
{
Playback.Initialize();
ReadExcel myClassObj = new ReadExcel();
string sheetName="";
StreamReader sr = new StreamReader(@"E:\SaveSheetName.txt");
sheetName = sr.ReadLine();
sr.Close();
myClassObj.excelRead(sheetName);
myClassObj.testExcel(sheetName);
}
//code for test initalize
public void runValidatonTest()
{
DataTable dtFinal = StaticVariable.dtExcel.Copy();
for (int i = 0; i < dtFinal.Rows.Count; i++)
{
if (TestContext.TestName == dtFinal.Rows[i][2].ToString() && dtFinal.Rows[i][3].ToString() == "Y" && dtFinal.Rows[i][4].ToString() == "TRUE")
{
MessageBox.Show(TestContext.TestName);
MessageBox.Show(dtFinal.Rows[i][2].ToString());
StaticVariable.runValidateResult = "true";
break;
}
}
//StaticVariable.dtExcel = dtFinal.Copy();
}
Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:
set list=A B C D
A list of values separated by space may be easily processed by for
command:
(for %%a in (%list%) do (
echo %%a
echo/
)) > theFile.txt
You may also create an array this way:
setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D) do (
set vector[!n!]=%%a
set /A n+=1
)
and show the array elements this way:
(for /L %%i in (0,1,3) do (
echo !vector[%%i]!
echo/
)) > theFile.txt
For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script
ATTENTION! You must know that all characters included in set
command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:
set list = "A B C D"
create a variable called list
(list-space) with the value "A B C D"
(space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set
commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:
set "list=A B C D"
PS - You should NOT use ECHO.
in order to left blank lines! An alternative is ECHO/
. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774
Bear in mind that 0
is a special case of parameter numbers inside a batch file, where 0
means this file as given on the command line.
So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0
or %~0
usage:
myfile
myfile.bat
mydir\myfile.bat
c:\mydir\myfile.bat
"c:\mydir\myfile.bat"
All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0
strips the quotes from the last example, whereas %0
does not.
Because these all give different results, %0
and %~0
are very unlikely to be what you actually want to use.
Here's a batch file to illustrate:
@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SETLOCAL
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully Constructed name: %drv%%pth%%fname%%ext%
@ENDLOCAL
pause
The first way
Needs root
Use kill
:
adb shell ps
=> Will list all running processes on the device and their process ids
adb shell kill <PID>
=> Instead of <PID>
use process id of your application
The second way
In Eclipse open DDMS
perspective.
In Devices
view you will find all running processes.
Choose the process and click on Stop
.
The third way
It will kill only background process of an application.
adb shell am kill [options] <PACKAGE>
=> Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:
--user | all | current: Specify user whose processes to kill; all users if not specified.
The fourth way
Needs root
adb shell pm disable <PACKAGE>
=> Disable the given package or component (written as "package/class").
The fifth way
Note that run-as is only supported for apps that are signed with debug keys.
run-as <package-name> kill <pid>
The sixth way
Introduced in Honeycomb
adb shell am force-stop <PACKAGE>
=> Force stop everything associated with (the app's package name).
P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.
I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.
Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.
I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.
I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
{
FullScreen fullScreen = new FullScreen();
if (fullScreenMode == FullScreenMode.No) // FullScreenMode is an enum
{
fullScreen.EnterFullScreenMode(this);
fullScreenMode = FullScreenMode.Yes;
}
else
{
fullScreen.LeaveFullScreenMode(this);
fullScreenMode = FullScreenMode.No;
}
}
I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)
The title of the question leads people here, so I decided to answer that question for everyone else since the OP's described case was so limited.
I finally settled on writing a function.
0
in case of non-int:int(){ printf '%d' ${1:-} 2>/dev/null || :; }
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
If you want to get a non-zero status code on non-int, remove the ||:
(aka or true
) but leave the ;
# Wrapped in parens to call a subprocess and not `set` options in the main bash process
# In other words, you can literally copy-paste this code block into your shell to test
( set -eu;
tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" )
test(){ echo; type int; for test in "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }
int(){ printf '%d' ${1:-} 2>/dev/null||:; };
test
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
test
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
test
int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }
test
# unexpected inconsistent results from `bc`
int(){ bc<<<"${1:-}" 2>/dev/null||:; }
test
)
int is a function
int ()
{
printf '%d' ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '0' from '6foo'
got '0' from 'bar7'
got '0' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
expr 0 + ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '' from 'bar7'
got '' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
expr ${1:-} : '[^0-9]*\([0-9]*\)' 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null) || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
bc <<< "${1:-}" 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '0' from 'bar7'
got '' from 'foo8.9bar'
got '0' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
I got sent down this rabbit hole because the accepted answer is not compatible with set -o nounset
(aka set -u
)
# This works
$ ( number="3"; string="foo"; echo $((number)) $((string)); )
3 0
# This doesn't
$ ( set -u; number="3"; string="foo"; echo $((number)) $((string)); )
-bash: foo: unbound variable
You need to do two additional things after following the link that you have mentioned in your post:
One have to map the changed login cridentials in phpmyadmin's config.inc.php
and second, you need to restart your web and mysql servers..
php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php
and in that file put your current mysql password at line
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here
UPDATE:
In scikit-learn 0.22, there's a new feature to plot the confusion matrix directly.
See the documentation: sklearn.metrics.plot_confusion_matrix
OLD ANSWER:
I think it's worth mentioning the use of seaborn.heatmap
here.
import seaborn as sns
import matplotlib.pyplot as plt
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);
This warning means that your code operates on a raw type, recompile the example with the
-Xlint:unchecked
to get the details
like this:
javac YourFile.java -Xlint:unchecked
Main.java:7: warning: [unchecked] unchecked cast
clone.mylist = (ArrayList<String>)this.mylist.clone();
^
required: ArrayList<String>
found: Object
1 warning
docs.oracle.com talks about it here: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
According to the React Documentation it's perfectly OK to call setState()
from within the componentDidMount()
function.
It will cause render()
to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.
You can find the documentation here:
https://reactjs.org/docs/react-component.html#componentdidmount
Here is the excerpt from the documentation:
You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...
It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:
data.frame
. This is not recommended because indexing is slow for data.frames
.data.frame
afterwards. A list
is very useful here.Example to illustrate the general approach:
mylist <- list() #create an empty list
for (i in 1:5) {
vec <- numeric(5) #preallocate a numeric vector
for (j in 1:5) { #fill the vector
vec[j] <- i^j
}
mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix
In this example it is not necessary to use a list
, you could preallocate a matrix
. However, if you do not know how many iterations your loop will need, you should use a list
.
Finally here is a vectorized alternative to the example loop:
outer(1:5,1:5,function(i,j) i^j)
As you see it's simpler and also more efficient.
I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The data layer has the context and all the models. The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config of the business layer (and the data layer) and viola it works. Putting this here for others who may encounter the same issue.
I already did it using Lotus Notus
and PHP
.
This solution works if you have access to the mail server or you can request something to the mail server
Administrator:
1) Create a group in the mail server
: Sales Department
2) Assign to the group
the accounts you need to be in the group
3) Assign an internet address to the group: [email protected]
4) Create your PHP script using the mail function:
$to = "[email protected]";
mail($to, $subject, $message, $headers);
It worked for me and all the accounts included in the group receive the mail.
The best of the lucks.
You can do this by using jquery :
ts code :
scrollTOElement = (element, offsetParam?, speedParam?) => {
const toElement = $(element);
const focusElement = $(element);
const offset = offsetParam * 1 || 200;
const speed = speedParam * 1 || 500;
$('html, body').animate({
scrollTop: toElement.offset().top + offset
}, speed);
if (focusElement) {
$(focusElement).focus();
}
}
html code :
<button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>
Apply this on elements you want to scroll :
<div id="elementTo">some content</div>
Here is a stackblitz sample.
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
If you only need two decimal places, simplest way is..
SELECT CAST(12 AS DECIMAL(16,2))
OR
SELECT CAST('12' AS DECIMAL(16,2))
Output
12.00
After review the problem, here is my delphi way, that may help
var
A: Array of Integer;
I,J,C,K, P: Integer;
begin
C:=10;
SetLength(A,10);
A[0]:=1; A[1]:=4; A[2]:=2; A[3]:=6; A[4]:=3; A[5]:=4;
A[6]:=3; A[7]:=4; A[8]:=2; A[9]:=5;
for I := 0 to C-1 do
begin
for J := I+1 to C-1 do
if A[I]=A[J] then
begin
for K := C-1 Downto J do
if A[J]<>A[k] then
begin
P:=A[K];
A[K]:=0;
A[J]:=P;
C:=K;
break;
end
else
begin
A[K]:=0;
C:=K;
end;
end;
end;
//tructate array
setlength(A,C);
end;
{% for i in range(10) %}
{{ i }}
{% endfor %}
BEGIN and END have been well answered by others.
As Gary points out, GO is a batch separator, used by most of the Microsoft supplied client tools, such as isql, sqlcmd, query analyzer and SQL Server Management studio. (At least some of the tools allow the batch separator to be changed. I have never seen a use for changing the batch separator.)
To answer the question of when to use GO, one needs to know when the SQL must be separated into batches.
Some statements must be the first statement of a batch.
select 1
create procedure #Zero as
return 0
On SQL Server 2000 the error is:
Msg 111, Level 15, State 1, Line 3
'CREATE PROCEDURE' must be the first statement in a query batch.
Msg 178, Level 15, State 1, Line 4
A RETURN statement with a return value cannot be used in this context.
On SQL Server 2005 the error is less helpful:
Msg 178, Level 15, State 1, Procedure #Zero, Line 5
A RETURN statement with a return value cannot be used in this context.
So, use GO
to separate statements that have to be the start of a batch from the statements that precede it in a script.
When running a script, many errors will cause execution of the batch to stop, but then the client will simply send the next batch, execution of the script will not stop. I often use this in testing. I will start the script with begin transaction and end with rollback, doing all the testing in the middle:
begin transaction
go
... test code here ...
go
rollback transaction
That way I always return to the starting state, even if an error happened in the test code, the begin and rollback transaction statements being part of a separate batches still happens. If they weren't in separate batches, then a syntax error would keep begin transaction from happening, since a batch is parsed as a unit. And a runtime error would keep the rollback from happening.
Also, if you are doing an install script, and have several batches in one file, an error in one batch will not keep the script from continuing to run, which may leave a mess. (Always backup before installing.)
Related to what Dave Markel pointed out, there are cases when parsing will fail because SQL Server is looking in the data dictionary for objects that are created earlier in the batch, but parsing can happen before any statements are run. Sometimes this is an issue, sometimes not. I can't come up with a good example. But if you ever get an 'X does not exist' error, when it plainly will exist by that statement break into batches.
And a final note. Transaction can span batches. (See above.) Variables do not span batches.
declare @i int
set @i = 0
go
print @i
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".
VERSION=$(head -50 pom.xml | awk -F'>' '/SNAPSHOT/ {print $2}' | awk -F'<' '{print $1}')
This is what I used to get the version number, thought there would have been a better maven way to do so
Easy done:
(?<=\[)(.*?)(?=\])
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:
Alternatively you can just capture what's between the square brackets:
\[(.*?)\]
and return the first captured group instead of the entire match.
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:
set serveroutput on;
DECLARE
v_str VARCHAR2(1000);
BEGIN
--Create encoded value
v_str := utl_encode.text_encode
('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
--Decode the value..
v_str := utl_encode.text_decode
(v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
END;
/
I do not recommend using the ExpectedException attribute (since it's too constraining and error-prone) or to write a try/catch block in each test (since it's too complicated and error-prone). Use a well-designed assert method -- either provided by your test framework or write your own. Here's what I wrote and use.
public static class ExceptionAssert
{
private static T GetException<T>(Action action, string message="") where T : Exception
{
try
{
action();
}
catch (T exception)
{
return exception;
}
throw new AssertFailedException("Expected exception " + typeof(T).FullName + ", but none was propagated. " + message);
}
public static void Propagates<T>(Action action) where T : Exception
{
Propagates<T>(action, "");
}
public static void Propagates<T>(Action action, string message) where T : Exception
{
GetException<T>(action, message);
}
public static void Propagates<T>(Action action, Action<T> validation) where T : Exception
{
Propagates(action, validation, "");
}
public static void Propagates<T>(Action action, Action<T> validation, string message) where T : Exception
{
validation(GetException<T>(action, message));
}
}
Example uses:
[TestMethod]
public void Run_PropagatesWin32Exception_ForInvalidExeFile()
{
(test setup that might propagate Win32Exception)
ExceptionAssert.Propagates<Win32Exception>(
() => CommandExecutionUtil.Run(Assembly.GetExecutingAssembly().Location, new string[0]));
(more asserts or something)
}
[TestMethod]
public void Run_PropagatesFileNotFoundException_ForExecutableNotFound()
{
(test setup that might propagate FileNotFoundException)
ExceptionAssert.Propagates<FileNotFoundException>(
() => CommandExecutionUtil.Run("NotThere.exe", new string[0]),
e => StringAssert.Contains(e.Message, "NotThere.exe"));
(more asserts or something)
}
NOTES
Returning the exception instead of supporting a validation callback is a reasonable idea except that doing so makes the calling syntax of this assert very different than other asserts I use.
Unlike others, I use 'propagates' instead of 'throws' since we can only test whether an exception propagates from a call. We can't test directly that an exception is thrown. But I suppose you could image throws to mean: thrown and not caught.
FINAL THOUGHT
Before switching to this sort of approach I considered using the ExpectedException attribute when a test only verified the exception type and using a try/catch block if more validation was required. But, not only would I have to think about which technique to use for each test, but changing the code from one technique to the other as needs changed was not trivial effort. Using one consistent approach saves mental effort.
So in summary, this approach sports: ease-of-use, flexibility and robustness (hard to do it wrong).
This can be caused by App ID prefix, when you switching different developer accounts. See https://developer.apple.com/library/content/technotes/tn2311/_index.html for Apple's support.
For me this code worked best:
private func getCoordinate(_ view: UIView) -> CGPoint {
var x = view.frame.origin.x
var y = view.frame.origin.y
var oldView = view
while let superView = oldView.superview {
x += superView.frame.origin.x
y += superView.frame.origin.y
if superView.next is UIViewController {
break //superView is the rootView of a UIViewController
}
oldView = superView
}
return CGPoint(x: x, y: y)
}
Alternative to @HostListener
and scroll output on the element I would suggest using fromEvent from RxJS since you can chain it with filter()
and distinctUntilChanges()
and can easily skip flood of potentially redundant events (and change detections).
Here is a simple example:
// {static: true} can be omitted if you don't need this element/listener in ngOnInit
@ViewChild('elementId', {static: true}) el: ElementRef;
// ...
fromEvent(this.el.nativeElement, 'scroll')
.pipe(
// Is elementId scrolled for more than 50 from top?
map((e: Event) => (e.srcElement as Element).scrollTop > 50),
// Dispatch change only if result from map above is different from previous result
distinctUntilChanged());
For me this error happened because I was trying to call a nested function. Only thing I had to do to have it fixed was to bring the function out to a scope where it was visible.
NSString *url = [NSString stringWithFormat:@"https://itunes.apple.com/us/app/kidsworld/id906660185?ls=1&mt=8"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();
These methods can also be called on a Collection for example
// <= Laravel 5.1
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->lists('word_one');
// >= Laravel 5.2
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->pluck('word_one');
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
Inside our activity we can get the root
view with:
ViewGroup rootView = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
or
View rootView = getWindow().getDecorView().getRootView();
It's very simple to implement - you should use TestContext
property and TestPropertyAttribute
.
public TestContext TestContext { get; set; }
private List<string> GetProperties()
{
return TestContext.Properties
.Cast<KeyValuePair<string, object>>()
.Where(_ => _.Key.StartsWith("par"))
.Select(_ => _.Value as string)
.ToList();
}
//usage
[TestMethod]
[TestProperty("par1", "http://getbootstrap.com/components/")]
[TestProperty("par2", "http://www.wsj.com/europe")]
public void SomeTest()
{
var pars = GetProperties();
//...
}
I prepared few extension methods to simplify access to the TestContext
property and act like we have several test cases. See example with processing simple test properties here:
[TestMethod]
[TestProperty("fileName1", @".\test_file1")]
[TestProperty("fileName2", @".\test_file2")]
[TestProperty("fileName3", @".\test_file3")]
public void TestMethod3()
{
TestContext.GetMany<string>("fileName").ForEach(fileName =>
{
//Arrange
var f = new FileInfo(fileName);
//Act
var isExists = f.Exists;
//Asssert
Assert.IsFalse(isExists);
});
}
and example with creating complex test objects:
[TestMethod]
//Case 1
[TestProperty(nameof(FileDescriptor.FileVersionId), "673C9C2D-A29E-4ACC-90D4-67C52FBA84E4")]
//...
public void TestMethod2()
{
//Arrange
TestContext.For<FileDescriptor>().Fill(fi => fi.FileVersionId).Fill(fi => fi.Extension).Fill(fi => fi.Name).Fill(fi => fi.CreatedOn, new CultureInfo("en-US", false)).Fill(fi => fi.AccessPolicy)
.ForEach(fileInfo =>
{
//Act
var fileInfoString = fileInfo.ToString();
//Assert
Assert.AreEqual($"Id: {fileInfo.FileVersionId}; Ext: {fileInfo.Extension}; Name: {fileInfo.Name}; Created: {fileInfo.CreatedOn}; AccessPolicy: {fileInfo.AccessPolicy};", fileInfoString);
});
}
Take a look to the extension methods and set of samples for more details.
The java.util.Date/Calendar classes are a mess and should be avoided.
Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.
Here's your answer using the Joda-Time 2.3 library. Very easy.
As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.
If you had placed a T
in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Parse string as a date-time in UTC (no time zone offset).
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );
// Adjust for 13 hour offset from UTC/GMT.
DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );
// Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );
Dump those values…
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "thirteenDateTime: " + thirteenDateTime );
System.out.println( "tongatapuDateTime: " + tongatapuDateTime );
When run…
dateTimeInUTC: 2011-10-06T03:35:05.000Z
thirteenDateTime: 2011-10-06T16:35:05.000+13:00
tongatapuDateTime: 2011-10-06T16:35:05.000+13:00
If you want to remove all JavaScript code from some HTML text, then removing <script>
tags isn't enough, because JavaScript can still live in "onclick", "onerror", "href" and other attributes.
Try out this npm module which handles all of this: https://www.npmjs.com/package/strip-js
If this is part of a batch script (.bat
file) and you have a large list of files, you can use a multi-line ^
, and optional /Y
flag to suppresses prompting to confirm you want to overwrite an existing destination file.
REM Concatenate several files to one
COPY /Y ^
this_is_file_1.csv + ^
this_is_file_2.csv + ^
this_is_file_3.csv + ^
this_is_file_4.csv + ^
this_is_file_5.csv + ^
this_is_file_6.csv + ^
this_is_file_7.csv + ^
this_is_file_8.csv + ^
this_is_file_9.csv ^
output_file.csv
This is tidier than performing the command on one line.
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
You can use menu Search -> Replace... (Ctrl + H).
It has a regular expression feature for replacing. You can use a regex that matches #region as well as whatever else is on the line, and replace it with empty space.
In addition, sometimes the dict instance might be a subclass of dict (defaultdict
for example). In that case, using clear
is preferred, as we don't have to remember the exact type of the dict, and also avoid duplicate code (coupling the clearing line with the initialization line).
x = defaultdict(list)
x[1].append(2)
...
x.clear() # instead of the longer x = defaultdict(list)
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
The underlying MD5 algorithm is no longer deemed secure, thus while md5sum is well-suited for identifying known files in situations that are not security related, it should not be relied on if there is a chance that files have been purposefully and maliciously tampered. In the latter case, the use of a newer hashing tool such as sha256sum is highly recommended.
So, if you are simply looking to check for file corruption or file differences, when the source of the file is trusted, MD5 should be sufficient. If you are looking to verify the integrity of a file coming from an untrusted source, or over from a trusted source over an unencrypted connection, MD5 is not sufficient.
Another commenter noted that Ubuntu and others use MD5 checksums. Ubuntu has moved to PGP and SHA256, in addition to MD5, but the documentation of the stronger verification strategies are more difficult to find. See the HowToSHA256SUM page for more details.
As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.
The best that you can do is to try to parse "X-Forwarded-For"
and rely on request.getRemoteAddr();
public static String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return request.getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
// we only want the client
return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
}
}
In latest version(2012 or more) we can get modified stored procedure detail by using this query
SELECT create_date, modify_date, name FROM sys.procedures
ORDER BY modify_date DESC
The reason reset
and revert
tend to come up a lot in the same conversations is because different version control systems use them to mean different things.
In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert
before being told that they actually want reset
.
Similarly, the revert
equivalent in other VCSes is often called rollback
or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset
but not revert
. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.
As for your actual questions about revert...
Okay, you're going to use git revert but how?
git revert first-bad-commit..last-bad-commit
And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??
By default, git revert
prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:
--edit
With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.
--no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.
This is useful when reverting more than one commits' effect to your index in a row.
In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit
to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.
It is most likely a spelling error of reserved vuejs variables. I got here because I misspelled computed:
and vuejs would not recognize my computed property variables. So if you have an error like this, check your spelling first!
While this is still a part of Docker that needs some work, you should put the volume in the Dockerfile with the VOLUME instruction so you don't need to copy the volumes from another container.
That will make your containers less inter-dependent and you don't have to worry about the deletion of one container affecting another.
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
char grid[row][col];
memset(grid, ' ', sizeof(grid));
That's for initializing char array elements to space characters.
you can do it as follow:
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/
This query will get you all the tables in the database
USE [DatabaseName];
SELECT * FROM information_schema.tables;
You may wrap it in a bash script or git alias:
cd /X/Y && git pull && cd -
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
You could use jQuery.load(): http://api.jquery.com/load/
Like this:
$(".text").load("helloworld.txt");
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
Try this:
echo mysql_result($result, 0);
This is enough because you are only fetching one field of one row.
pugixml - Light-weight, simple and fast XML parser for C++ Very small (comparable to RapidXML), very fast (comparable to RapidXML), very easy to use (better than RapidXML).
See C++ FAQ Lite How do I convert a std::string to a number?
See C++ Super-FAQ How do I convert a std::string to a number?
Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.
// the requested function
#include <sstream>
double string_to_double( const std::string& s )
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
// some tests
#include <cassert>
int main( int, char** )
{
// simple case:
assert( 0.5 == string_to_double( "0.5" ) );
// blank space:
assert( 0.5 == string_to_double( "0.5 " ) );
assert( 0.5 == string_to_double( " 0.5" ) );
// trailing non digit characters:
assert( 0.5 == string_to_double( "0.5a" ) );
// note that with your requirements you can't distinguish
// all the the allowed string representation of zero from
// the non numerical strings:
assert( 0 == string_to_double( "0" ) );
assert( 0 == string_to_double( "0." ) );
assert( 0 == string_to_double( "0.0" ) );
assert( 0 == string_to_double( "0.00" ) );
assert( 0 == string_to_double( "0.0e0" ) );
assert( 0 == string_to_double( "0.0e-0" ) );
assert( 0 == string_to_double( "0.0e+0" ) );
assert( 0 == string_to_double( "+0" ) );
assert( 0 == string_to_double( "+0." ) );
assert( 0 == string_to_double( "+0.0" ) );
assert( 0 == string_to_double( "+0.00" ) );
assert( 0 == string_to_double( "+0.0e0" ) );
assert( 0 == string_to_double( "+0.0e-0" ) );
assert( 0 == string_to_double( "+0.0e+0" ) );
assert( 0 == string_to_double( "-0" ) );
assert( 0 == string_to_double( "-0." ) );
assert( 0 == string_to_double( "-0.0" ) );
assert( 0 == string_to_double( "-0.00" ) );
assert( 0 == string_to_double( "-0.0e0" ) );
assert( 0 == string_to_double( "-0.0e-0" ) );
assert( 0 == string_to_double( "-0.0e+0" ) );
assert( 0 == string_to_double( "foobar" ) );
return 0;
}
I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.
Point 1: Am I understanding it right?
You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:
When dealing with a Collection URI like: http://example.com/resources/
GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
PUT: Meaning defined as "replace the entire collection with another collection".
POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
DELETE: Meaning defined as "delete the entire collection".
When dealing with a Member URI like: http://example.com/resources/7HOU57Y
GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
PUT: Update the addressed member of the collection or create it with the specified ID.
POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
DELETE: Delete the addressed member of the collection.
Point 2: I need more verbs
In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.
Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/
with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID
.
Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID
with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.
My instinct would be to do a GET call to a URL like
/api/users/1/activate_login
This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.
For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.
Point 3: How to return error messages and codes
Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.
Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.
The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.
Point 4: How to do authentication
As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).
You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".
There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.
Here's a cleaner way using the PackageManager
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
// the getLaunchIntentForPackage returns an intent that you can use with startActivity()
More info here http://qtcstation.com/2011/02/how-to-launch-another-app-from-your-app/
Based on what React Docs say:
Handling Multiple Inputs. When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<div className="radio-buttons">
Windows
<input
id="windows"
value="windows"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Mac
<input
id="mac"
value="mac"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Linux
<input
id="linux"
value="linux"
name="platform"
type="radio"
onChange={this.handleChange}
/>
</div>
);
}
}
Link to example: https://codesandbox.io/s/6l6v9p0qkr
At first, none of the radio buttons is selected so this.state
is an empty object, but whenever the radio button is selected this.state
gets a new property with the name of the input and its value. It eases then to check whether user selected any radio-button like:
const isSelected = this.state.platform ? true : false;
EDIT:
With version 16.7-alpha of React there is a proposal for something called hooks
which will let you do this kind of stuff easier:
In the example below there are two groups of radio-buttons in a functional component. Still, they have controlled inputs:
function App() {
const [platformValue, plaftormInputProps] = useRadioButtons("platform");
const [genderValue, genderInputProps] = useRadioButtons("gender");
return (
<div>
<form>
<fieldset>
Windows
<input
value="windows"
checked={platformValue === "windows"}
{...plaftormInputProps}
/>
Mac
<input
value="mac"
checked={platformValue === "mac"}
{...plaftormInputProps}
/>
Linux
<input
value="linux"
checked={platformValue === "linux"}
{...plaftormInputProps}
/>
</fieldset>
<fieldset>
Male
<input
value="male"
checked={genderValue === "male"}
{...genderInputProps}
/>
Female
<input
value="female"
checked={genderValue === "female"}
{...genderInputProps}
/>
</fieldset>
</form>
</div>
);
}
function useRadioButtons(name) {
const [value, setState] = useState(null);
const handleChange = e => {
setState(e.target.value);
};
const inputProps = {
name,
type: "radio",
onChange: handleChange
};
return [value, inputProps];
}
Working example: https://codesandbox.io/s/6l6v9p0qkr
If you have custom defines and want to save them before cleaning, run the following in your build directory:
sed -ne '/variable specified on the command line/{n;s/.*/-D \0 \\/;p}' CMakeCache.txt
Then create a new build directory (or remove the old build directory and recreate it) and finally run cmake
with the arguments you'll get with the script above.
This is all you need:
background-repeat: no-repeat;
ORDER BY a date type does not depend on the date format, the date format is only for showing, in the database, they are same data.
Having rolled my own solution for this before, I can whole heartedly recommend the Geo::Coder::US Perl module for this. Just download all the census data and use the included importer to create the Berkeley DB for your country and point the Perl script at it. Use the module's built in address parsing, and there you have it: An offline geocoding system!
In SSMS, "Query" menu item... "Results to"... "Results to File"
Shortcut = CTRL+shift+F
You can set it globally too
"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down
Edit: after comment
In SSMS, "Query" menu item... "SQLCMD" mode
This allows you to run "command line" like actions.
A quick test in my SSMS 2008
:OUT c:\foo.txt
SELECT * FROM sys.objects
Edit, Sep 2012
:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects
Since Redis 2.6, lua is supported, you can get number of wildcard keys like this
eval "return #redis.call('keys', 'prefix-*')" 0
see eval command
To display the query string:
print_r($this->db->last_query());
To display the query result:
print_r($query);
The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. To enable the profiler place the following line anywhere within your Controller methods:
$this->output->enable_profiler(TRUE);
Profiling user guide: https://www.codeigniter.com/user_guide/general/profiling.html
If you are in the middle of piping the result through map/filter/sort etc and you want to concat array of arrays, you can use reduce
let sorted_nums = ['1,3', '4,2']
.map(item => item.split(',')) // [['1', '3'], ['4', '2']]
.reduce((a, b) => a.concat(b)) // ['1', '3', '4', '2']
.sort() // ['1', '2', '3', '4']
try this
<table style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%;">
<tr>
<td>
<div style="text-align: left; display: inline-block;">
Your Html code Here
</div>
</td>
</tr>
</table>
Or this
<div style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%; display: table">
<div style="display: table-row">
<div style="display: table-cell; vertical-align:middle;">
<div style="text-align: left; display: inline-block;">
Your Html code here
</div>
</div>
</div>
</div>
Set either the width or height to some arbitrarily large number:
https://graph.facebook.com/username_or_id/picture?width=9999
If the width and height are the same number, the photo is cropped to a square.
WAMP [ Windows, Apache, Mysql, Php]
XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )
Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.
WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.
XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )
IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
For me, when typing the url, a user accidentally used a / instead of a ? to start the query parameters
e.g.:
url.com/endpoint/parameter=SomeValue&otherparameter=Another+value
which should have been:
url.com/endpoint?parameter=SomeValue&otherparameter=Another+value
I'm a little late to the game, but this may help others.
In my case my jenkins master has a shared external resource, which is allocated to jenkins jobs by the external-resource-dispatcher-plugin. Due to bug JENKINS-19439 in the plugin (which is in beta), I found that my resource had been locked by a previous job, but wasn't unlocked when that previous job was cancelled.
To find out if a resource is currently in the locked state, navigate to the affected jenkins node, Jenkins -> Manage Jenkins -> Manage Nodes -> master
You should see the current state of any external resources. If any are unexpectedly locked this may be the reason why jobs are waiting for an executor.
I couldn't find any details of how to manually resolve this issue.
Restarting jenkins didn't resolve the problem.
In the end I went with the brutal approach:
In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):
PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);
The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.
Some Android phones contain Busybox. Was hard to find.
To see if busybox was around:
ls -lR / | grep busybox
If you know it's around. You need some read/write space. Try you flash drive, /sdcard
cd /sdcard
ls -lR / >lsoutput.txt
upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.
busybox find /sdcard -iname 'python*'
to make busybox easier to access, you could:
cd /sdcard
ln -s /where/ever/busybox/is busybox
/sdcard/busybox find /sdcard -iname 'python*'
Or any other place you want. R
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.
And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).
That said, you can simply put your code in a function and run that function with timeit.timeit()
:
def function_to_repeat():
# ...
duration = timeit.timeit(function_to_repeat, number=1000)
This would disable the garbage collection, repeatedly call the function_to_repeat()
function, and time the total duration of those calls using timeit.default_timer()
, which is the most accurate available clock for your specific platform.
You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup
argument to either import or create those dependencies, and pass them into your function:
def function_to_repeat(var1, var2):
# ...
duration = timeit.timeit(
'function_to_repeat(var1, var2)',
'from __main__ import function_to_repeat, var1, var2',
number=1000)
would grab the globals function_to_repeat
, var1
and var2
from your script and pass those to the function each repetition.
Try this, it was the only that worked for me:
npm --proxy http://:@proxyhost: --https-proxy http://:@proxyhost: --strict-ssl false install -g package
Pay atention to the option --strict-ssl false
Good luck.
import org.springframework.core.Ordered;
public class MyFilter implements Filter, Ordered {
@Override
public void init(FilterConfig filterConfig) {
// do something
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// do something
}
@Override
public void destroy() {
// do something
}
@Override
public int getOrder() {
return -100;
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class MyAutoConfiguration {
@Bean
public MyFilter myFilter() {
return new MyFilter();
}
}
Use this higher order function to prevent the pyramid of doom
foreach(){
arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=};
for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}
example:
$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two
Prefer initialization:
class C : public A
{
public:
C(const string &val) : A(anInt) {}
};
In C++11, you can use inheriting constructors (which has the syntax seen in your example D
).
Update: Inheriting Constructors have been available in GCC since version 4.8.
If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:
class A
{
public:
A() {}
virtual ~A() {}
void init(int) { std::cout << "A\n"; }
};
class B : public A
{
public:
B() : A() {}
void init(int) { std::cout << "B\n"; }
};
class C : public A
{
public:
C() : A() {}
void init(int) { std::cout << "C\n"; }
};
class D : public A
{
public:
D() : A() {}
using A::init;
void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};
int main()
{
B b; b.init(10);
C c; c.init(10);
D d; d.init(10); d.init("a");
return 0;
}
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.
If you set fetchType=EAGER
This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.
If you set fetchType=LAZY
the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.
You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.
For the second part of the question - how to get hibernate to generate optimised SQL?
Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.
First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
Make sure you only fetch the headers, not the body content:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):
As a whole:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS
(the default) and PKCS12
(for PKCS#12 files, often with extension .p12
or sometimes .pfx
).
JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool
wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).
If you already have a PKCS#12 file, it's often easier to use the PKCS12
type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.
In Java 7, PKCS12
was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS
doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).
This has changed in Java 8, so you can now have certificate-only entries in PKCS12
stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)
There are a few other keystore types, perhaps less frequently used (depending on the context), those include:
PKCS11
, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.BKS
, using the BouncyCastle provider (commonly used for Android).Windows-MY
/Windows-ROOT
, if you want to access the Windows certificate store directly.KeychainStore
, if you want to use the OSX keychain directly.Kindly uninstall the debug app in the device or just increase the version code to overcome this issues
When we are dealing with time-series, calculating z-scores (or anomalies - not the same thing, but you can adapt this code easily) is a bit more complicated. For example, you have 10 years of temperature data measured weekly. To calculate z-scores for the whole time-series, you have to know the means and standard deviations for each day of the year. So, let's get started:
Assume you have a pandas DataFrame. First of all, you need a DateTime index. If you don't have it yet, but luckily you do have a column with dates, just make it as your index. Pandas will try to guess the date format. The goal here is to have DateTimeIndex. You can check it out by trying:
type(df.index)
If you don't have one, let's make it.
df.index = pd.DatetimeIndex(df[datecolumn])
df = df.drop(datecolumn,axis=1)
Next step is to calculate mean and standard deviation for each group of days. For this, we use the groupby method.
mean = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanmean)
std = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanstd)
Finally, we loop through all the dates, performing the calculation (value - mean)/stddev; however, as mentioned, for time-series this is not so straightforward.
df2 = df.copy() #keep a copy for future comparisons
for y in np.unique(df.index.year):
for d in np.unique(df.index.dayofyear):
df2[(df.index.year==y) & (df.index.dayofyear==d)] = (df[(df.index.year==y) & (df.index.dayofyear==d)]- mean.ix[d])/std.ix[d]
df2.index.name = 'date' #this is just to look nicer
df2 #this is your z-score dataset.
The logic inside the for loops is: for a given year we have to match each dayofyear to its mean and stdev. We run this for all the years in your time-series.
Add a icon file named "favicon.ico" to the root of your website.
Return types using arrow notation is the same as previous answers:
const sum = (a: number, b: number) : number => a + b;
I had the same problem while following a tutorial on setting up Laravel Homestead for Windows 10. The tutorial provides an example IP address 192.168.10.10
to use for the server. The problem with their example IP is that if you already have a VirtualBox Host-Only Adapter set up, the IP you use for your vagrant server must have the same first three parts of the IP address of your current adapter.
You can check what your current Virtualbox Host-Only Adapter IP address is by running ipconfig
(windows) ifconfig
(mac/linux) and looking for VirtualBox Host-Only Adapter's IPv4 address. 192.168.56.1
was mine. Usually if the host IP is 192.168.56.1
then the guest IP will be 192.168.56.101
so instead of using the example IP I used 192.168.56.102
. Any IP that is within 192.168.56.*
that is not already taken should work.
After this homestead up
worked perfectly for me.
TL;DR - If your current VirtualBox Host-Only Adapter IP is 192.168.56.1, make your Vagrant server IP 192.168.56.102.
A simple way is to write:
-std=c++11
in the Other Options section of the compiler flags. You could do this on a per-project basis (Project -> Build Options), and/or set it as a default option in the Settings -> Compilers part.
Some projects may require -std=gnu++11
which is like C++11 but has some GNU extensions enabled.
If using g++ 4.9, you can use -std=c++14
or -std=gnu++14
.
I had this problem yesterday. Before in the my solution, chek this settings.
git config --global user.email "[email protected]"
git config --global user.name "your_name"
Where "user" is the user of the laptop.
Example: dias@dias-hp-pavilion$ git config --global dias.email ...
So, confirm the informations add, doing:
dias@dias-hp-pavilion:/home/dias$ git config --global dias.email
[email protected]
dias@dias-hp-pavilion:/home/dias$ git config --global dias.name
my_name
or
nano /home/user_name/.gitconfig
and check this informations.
Doing it and the error persists, try another Git IDE (GUI Clients). I used git-cola and this error appeared, so I changed of IDE, and currently I use the CollabNet GitEye. Try you also!
I hope have helped!
yup.. here's my code:
<style>
.circle{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: blue
}
</style>
<div class="circle">
</div>
It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup
wouldn't do that.
To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping
command.
OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).
Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog
For Kotlin users:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?) : View?
{
// Inflate the layout for this fragment
var myView = inflater.inflate(R.layout.fragment_home, container, false)
var btn_test = myView.btn_test as Button
btn_test.setOnClickListener {
textView.text = "hunny home fragment"
}
return myView
}
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
First, change your directory:
cd your_project name
Then run:
python manage.py runserver
Okay. You only need to use 'flatMap' when you're facing nested Optionals. Here's the example.
public class Person {
private Optional<Car> optionalCar;
public Optional<Car> getOptionalCar() {
return optionalCar;
}
}
public class Car {
private Optional<Insurance> optionalInsurance;
public Optional<Insurance> getOptionalInsurance() {
return optionalInsurance;
}
}
public class Insurance {
private String name;
public String getName() {
return name;
}
}
public class Test {
// map cannot deal with nested Optionals
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.map(Car::getOptionalInsurance) // ? leads to a Optional<Optional<Insurance>
.map(Insurance::getName); // ?
}
}
Like Stream, Optional#map will return a value wrapped by a Optional. That's why we get a nested Optional -- Optional<Optional<Insurance>
. And at ?, we want to map it as an Insurance instance, that's how the tragedy happened.
The root is nested Optionals. If we can get the core value regardless the shells, we'll get it done. That's what flatMap does.
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.flatMap(Car::getOptionalInsurance)
.map(Insurance::getName);
}
In the end, I stronly recommed the Java 8 In Action to you if you'd like to study Java8 Systematicly.
You will need to make sure you have Options -MultiViews
as well.
None of the above worked for me on a standard cPanel host.
This worked:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
You can solve it using dictionary
to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]
dic = {}
for i in range(len(indexes)):
dic[indexes[i]]=replacements[i]
print(dic)
for index, item in enumerate(to_modify):
for i in indexes:
to_modify[i]=dic[i]
print(to_modify)
The output will be
{0: 0, 1: 0, 3: 0, 5: 0}
[0, 0, 3, 0, 1, 0]
I had to downgrade @types/core-js
to 9.36 to get it to work with "target": "es5"
set in my tsconfig.
"@types/core-js": "0.9.36",
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
ORDER_BY cast(registration_no as unsigned) ASC
gives the desired result with warnings.
Hence, better to go for
ORDER_BY registration_no + 0 ASC
for a clean result without any SQL warnings.
For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY
built-in function:
INDEXPROPERTY ( object_ID , index_or_statistics_name , property )
The simplest usage is with the IndexID
property:
If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null
If the index exists, the above will return its ID; if it doesn't, it will return NULL
.
The two most usual choices are GTK+, which has documentation links here, and is mostly used with C; or Qt which has documentation here and is more used with C++.
I posted these two as you do not specify an operating system and these two are pretty cross-platform.
Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?
Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.
Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)
I'm using
/etc/bash_completion.d/git
It came with Git and provides a prompt with branch name and argument completion.
If an URL pattern starts with /
, then it's relative to the context root. The /Admin/*
URL pattern would only match pages on http://localhost:8080/EMS2/Admin/*
(assuming that /EMS2
is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*
, so your URL pattern never matches.
You need to prefix your URL patterns with /faces/Html
as well like so:
<url-pattern>/faces/Html/Admin/*</url-pattern>
You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html
path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml
.
Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping>
with multiple <url-pattern>
entries:
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>
I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !
Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.
Went a step further...I thought this was cool...When I instead do this in Expts.py:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.
If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.
Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.
I did some experiments in playground and got some conclusions.
As you can see, in the case of class
, the use of class func
or static func
is just a question of habit.
Playground example with explanation:
class Dog {
final func identity() -> String {
return "Once a woofer, forever a woofer!"
}
class func talk() -> String {
return "Woof woof!"
}
static func eat() -> String {
return "Miam miam"
}
func sleep() -> String {
return "Zzz"
}
}
class Bulldog: Dog {
// Can not override a final function
// override final func identity() -> String {
// return "I'm once a dog but now I'm a cat"
// }
// Can not override a "class func", but redeclare is ok
func talk() -> String {
return "I'm a bulldog, and I don't woof."
}
// Same as "class func"
func eat() -> String {
return "I'm a bulldog, and I don't eat."
}
// Normal function can be overridden
override func sleep() -> String {
return "I'm a bulldog, and I don't sleep."
}
}
let dog = Dog()
let bullDog = Bulldog()
// FINAL FUNC
//print(Dog.identity()) // compile error
print(dog.identity()) // print "Once a woofer, forever a woofer!"
//print(Bulldog.identity()) // compile error
print(bullDog.identity()) // print "Once a woofer, forever a woofer!"
// => "final func" is just a "normal" one but prevented to be overridden nor redeclared by subclasses.
// CLASS FUNC
print(Dog.talk()) // print "Woof woof!", called directly from class
//print(dog.talk()) // compile error cause "class func" is meant to be called directly from class, not an instance.
print(Bulldog.talk()) // print "Woof woof!" cause it's called from Bulldog class, not bullDog instance.
print(bullDog.talk()) // print "I'm a bulldog, and I don't woof." cause talk() is redeclared and it's called from bullDig instance
// => "class func" is like a "static" one, must be called directly from class or subclassed, can be redeclared but NOT meant to be overridden.
// STATIC FUNC
print(Dog.eat()) // print "Miam miam"
//print(dog.eat()) // compile error cause "static func" is type method
print(Bulldog.eat()) // print "Miam miam"
print(bullDog.eat()) // print "I'm a bulldog, and I don't eat."
// NORMAL FUNC
//print(Dog.sleep()) // compile error
print(dog.sleep()) // print "Zzz"
//print(Bulldog.sleep()) // compile error
print(bullDog.sleep()) // print "I'm a bulldog, and I don't sleep."
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)]
above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine
is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString]
, it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]
), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
) then it will become help text for the prompt.
The latest docker supports setting ulimits through the command line and the API. For instance, docker run
takes --ulimit <type>=<soft>:<hard>
and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144
Create a new file, and then on the filename use slash. For example
Java/Helloworld.txt
I also had trouble overruling a dependency in a third party library. I used scot's approach with the exclusion but I also added the dependency with the newer version in the pom. (I used Maven 3.3.3)
So for the stAX example it would look like this:
<dependency>
<groupId>a.group</groupId>
<artifactId>a.artifact</artifactId>
<version>a.version</version>
<exclusions>
<!-- STAX comes with Java 1.6 -->
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>javax.xml.stream</groupId>
</exclusion>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
</exclusions>
<dependency>
<dependency>
<groupId>javax.xml.stream</groupId>
<artifactId>stax-api</artifactId>
<version>1.0-2</version>
</dependency>
Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars()
and JS's encodeURIComponent()
.
You can write:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
And on the server side:
htmlspecialchars($_POST['wysiwyg']);
This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.
In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.
By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.
When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.
Hmm.. well I know about XOR (exclusive or) and NAND and NOR. These are logic gates and have their software analogs.
Essentially they behave like so:
XOR is true only when one of the two arguments is true, but not both.
F XOR F = F
F XOR T = T
T XOR F = T
T XOR T = F
NAND is true as long as both arguments are not true.
F NAND F = T
F NAND T = T
T NAND F = T
T NAND T = F
NOR is true only when neither argument is true.
F NOR F = T
F NOR T = F
T NOR F = F
T NOR T = F
From your local machine:
rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage
From your local machine with a non standard ssh port:
rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path
Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:
rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage
See man rsync
for an explanation of my usual switches.
You Can Use Below Code To Make Status Bar Transparent. See Images With red highlight which helps you to identify use of Below code
Kotlin code snippet for your android app
Step:1 Write down code in On create Method
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}
if (Build.VERSION.SDK_INT >= 19) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
window.statusBarColor = Color.TRANSPARENT
}
Step2: You Need SetWindowFlag method which describe in Below code.
private fun setWindowFlag(bits: Int, on: Boolean) {
val win = window
val winParams = win.attributes
if (on) {
winParams.flags = winParams.flags or bits
} else {
winParams.flags = winParams.flags and bits.inv()
}
win.attributes = winParams
}
Java code snippet for your android app:
Step1: Main Activity Code
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
Step2: SetWindowFlag Method
public static void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
For Xamarin Users:
[Activity(MainLauncher = true,
ScreenOrientation = ScreenOrientation.Portrait,
WindowSoftInputMode = SoftInput.StateHidden)] //SoftInput.StateHidden - disables keyboard autopop
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.
[HttpPost]
public ActionResult PostViaAjax()
{
var body = Request.BinaryRead(Request.TotalBytes);
var result = Content(JsonError(new Dictionary<string, string>()
{
{"err", "Some error!"}
}), "application/json; charset=utf-8");
HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return result;
}
Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("your.package.to.scan");
return marshaller;
}
Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:
Using collections.defaultdict
:
import collections
dict_x = collections.defaultdict(list)
...
dict_x[key].append(value)
Pros: Probably best performance. Cons: Not available in Python 2.4.x.
Using dict().setdefault()
:
dict_x = {}
...
dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list()
s.
Using try ... except
:
dict_x = {}
...
try:
values = dict_x[key]
except KeyError:
values = dict_x[key] = []
values.append(value)
Or:
try:
dict_x[key].append(value)
except KeyError:
dict_x[key] = [value]
In Controller
return redirect()->route('company')->with('update', 'Content has been updated successfully!');
In view
@if (session('update'))
<div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong> {{ session('update') }} </strong>
</div>
@endif
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
do you called the ViewTreeObserver and not remove it.
mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// do nothing here can cause such problem
});
select DATEDIFF(dd, '12/30/1899', mydatefield)
Isn't this a much simpler solution, if I correctly understand the question, of course.
I want to load email addresses that are in a table called "spam" into a variable.
select email from spam
produces the following list, say:
.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu
To load into the variable @list:
declare @list as varchar(8000)
set @list += @list (select email from spam)
@list may now be INSERTed into a table, etc.
I hope this helps.
To use it for a .csv file or in VB, spike the code:
declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list
and it produces ready-made code to use elsewhere:
".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"
One can be very creative.
Thanks
Nico
You don't need to use
adb shell getevent -l
command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.
Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/
Sure. Add an Axes
using add_subplot
. (Edited import
.) (Edited show
.)
import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()
Alternatively, use add_axes
.
ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))
I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).
To fix it, I had to check if the IAsyncResult.IsCompleted==true
. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()
Like this :
Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
ar.AsyncWaitHandle.WaitOne();
Most of the time, ar.IsCompleted
will be true
.
#sub-left, #sub-right
{
display: inline-block;
}
I had to uninstall then re-install the xunit.runner.visualstudio nuget package. I tried this after trying all the above suggestions, so may be it was a mixture of things.
This works using grep without needing to use perl or find.
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
In Python 3 the following should work:
max(set(a), key=lambda x: a.count(x))
The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:
Dynamic pivot tables (transform rows to columns)
Your code would look like this:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
)
) INTO @sql
FROM product_additional;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See Demo
NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len
There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:
j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon
I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:
combineListsAsOne <-function(list1, list2){
n <- c()
for(x in list1){
n<-c(n, x)
}
for(y in list2){
n<-c(n, y)
}
return(n)
}
It just creates a new list and adds items from two supplied lists to create one.
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
If you want to use the --prefix
or -p
arguments, but want to avoid having to use the environment's full path to activate it, you need to edit the .condarc
config file before you create the environment.
The .condarc
file is in the home directory; C:\Users\<user>
on Windows. Edit the values under the envs_dirs
key to include the custom path for your environment. Assuming the custom path is D:\envs
, the file should end up looking something like this:
ssl_verify: true
channels:
- defaults
envs_dirs:
- C:\Users\<user>\Anaconda3\envs
- D:\envs
Then, when you create a new environment on that path, its name will appear along with the path when you run conda env list
, and you should be able to activate it using only the name, and not the full path.
In summary, if you edit .condarc
to include D:\envs
, and then run conda env create -p D:\envs\myenv python=x.x
, then activate myenv
(or source activate myenv
on Linux) should work.
Hope that helps!
P.S. I stumbled upon this through trial and error. I think what happens is when you edit the envs_dirs
key, conda updates ~\.conda\environments.txt
to include the environments found in all the directories specified under the envs_dirs
, so they can be accessed without using absolute paths.
$.listen('click', '#captcha', function() {
$('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
$.get("/captcha/new", null, function(data) {
$('#captcha-block').html(data);
});
return false;
});
#loading { background: url(/image/loading.gif) no-repeat center; }
Only using class names is not sufficient in your case.
By.cssSelector(".ban")
has 15 matching nodesBy.cssSelector(".hot")
has 11 matching nodesBy.cssSelector(".ban.hot")
has 5 matching nodesTherefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.
Option 1: Using list items' index (CssSelector or XPath)
Limitations
Example:
driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));
Option 2: Using Selenium's FindElements
, then index them. (CssSelector or XPath)
Limitations
Example:
// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];
Option 3: Using text (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));
Option 4: Index the grouped selector (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));
Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)
Limitations
Example:
driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));
All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:
See it in action with jsfiddle here (except the php processor)
### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'emails[]';
nextEmail.className = 'class_for_styling';
nextEmail.style.display = 'block';
nextEmail.placeholder = 'Enter E-mail Here';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
foreach ($_POST[emails] AS $postEmail){
if ($postEmail){$mailer->AddAddress($postEmail);}
}
}
?>
So what it does basically is to generate a new input text box on every click with the name "emails[]".
The [] added at the end makes it an array when posted.
Then we go through each element of the array with "foreach" on PHP side adding the:
$mailer->AddAddress($postEmail);
static class ArrayExtensions
{
public static int FindIndex<T>(this T[] array, Predicate<T> match)
{
return Array.FindIndex(array, match);
}
}
Usage
int[] array = { 9,8,7,6,5 };
var index = array.FindIndex(i => i == 7);
Console.WriteLine(index); // Prints "2"
I wrote this first not reading the question properly...
static class ArrayExtensions
{
public static int IndexOf<T>(this T[] array, T value)
{
return Array.IndexOf(array, value);
}
}
Usage
int[] array = { 9,8,7,6,5 };
var index = array.IndexOf(7);
Console.WriteLine(index); // Prints "2"
If you are looking for delete cache of your own application then simply delete your cache directory and its all done !
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) { e.printStackTrace();}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict = {}
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >= currentTime.TimeOfDay)
{
//match found
}
if you really want to parse a string into a TimeSpan, then you can use:
TimeSpan start = TimeSpan.Parse("11:59");
TimeSpan end = TimeSpan.Parse("13:01");
See the github repo, works with Django 3
Run startproject::
$ django-admin.py startproject sample
now a folder(sample) is created.
Create an app::
$ cd sample
$ python manage.py startapp uploader
Now a folder(uploader
) with these files are created::
uploader/
__init__.py
admin.py
app.py
models.py
tests.py
views.py
migrations/
__init__.py
On sample/settings.py
add 'uploader'
to INSTALLED_APPS
and add MEDIA_ROOT
and MEDIA_URL
, ie::
INSTALLED_APPS = [
'uploader',
...<other apps>...
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
in sample/urls.py
add::
...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views
urlpatterns = [
...<other url patterns>...
path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
update uploader/models.py
::
from django.db import models
class Upload(models.Model):
upload_file = models.FileField()
upload_date = models.DateTimeField(auto_now_add =True)
update uploader/views.py
::
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
model = Upload
fields = ['upload_file', ]
success_url = reverse_lazy('fileupload')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['documents'] = Upload.objects.all()
return context
Create a folder sample/uploader/templates/uploader
Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html
::
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>Django File Upload</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form><hr>
<ul>
{% for document in documents %}
<li>
<a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
<small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
</li>
{% endfor %}
</ul>
</div>
Syncronize database and runserver::
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver
visit http://localhost:8000/
flask.Flask.run
accepts additional keyword arguments (**options
) that it forwards to werkzeug.serving.run_simple
- two of those arguments are threaded
(a boolean) and processes
(which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).
threaded
defaults to True
as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True
to enable this behaviour.
For example, you can do
if __name__ == '__main__':
app.run(threaded=True)
to handle multiple clients using threads in a way compatible with old Flask versions, or
if __name__ == '__main__':
app.run(threaded=False, processes=3)
to tell Werkzeug to spawn three processes to handle incoming requests, or just
if __name__ == '__main__':
app.run()
to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.
That being said, Werkzeug's serving.run_simple
wraps the standard library's wsgiref
package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).
I'm not sure why the accepted answer was accepted if the suggested solution did not and does not solve the issue. There can actually be two related issues related to this topic.
Issue #1
The master page (e.g. _Layout.cshtml
) has a section defined and it is required but the inheriting views did not implement it. For example,
The Layout Template
<body>
@* Visible only to admin users *@
<div id="option_box">
@* this section is required due to the absence of the second parameter *@
@RenderSection("OptionBox")
</div>
</body>
The Inheriting View
No need to show any code, just consider that there is no implementation of @section OptionBox {}
on the view.
The Error for Issue #1
Section not defined: "OptionBox ".
Issue #2
The master page (e.g. _Layout.cshtml
) has a section defined and it is required AND the inheriting view did implement it. However, the implementing view have additional script
sections that are not defined on (any of) its master page(s).
The Layout Template
same as above
The Inheriting View
<div>
<p>Looks like the Lakers can still make it to the playoffs</p>
</div>
@section OptionBox {
<a href"">Go and reserve playoff tickets now</a>
}
@section StatsBox {
<ul>
<li>1. San Antonio</li>
<li>8. L. A. Lakers</li>
</ul>
}
The Error for Issue #2
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "StatsBox"
The OP's issue is similar to Issue #2 and the accepted answer is for Issue #1.
Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:
#! /bin/bash
awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2
Use it like so:
$ ./cgrep pattern [file]
Unfortunately, it doesn't have all the functionality of grep.
For more information , you can refer to an article "So You Like Color" in Linux Journal
You can pass the format in to the ToString
method, e.g.:
myFloatVariable.ToString("0.00"); //2dp Number
myFloatVariable.ToString("n2"); // 2dp Number
myFloatVariable.ToString("c2"); // 2dp currency
$ git submodule status --recursive
Is also a life saver in this situation. You can use it and gitk --all
to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.
Adding to the above answers:
This can be easily achieved via storyboard.
For the record, if you use Scala, you can do:
StringContext.treatEscapes(escaped)
I had the same error after using the hibernate code generation
https://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/
then the hibernate.cfg.xml
was created in /src/main/java
but without the connection parameters
after removing it - my problem was solved
you can use this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace GClass1
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _GesGasConnect
{
[DispId(1)]
int SetClass1Ver(string version);
}
[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("InterfacesSMS.Setting")]
public class Class1 : _Class1
{
public Class1() { }
public int SetClass1(string version)
{
return (DateTime.Today.Day);
}
}
}
It's not that simple.
UTF-16 is a 16-bit, variable-width encoding. Simply calling something "Unicode" is ambiguous, since "Unicode" refers to an entire set of standards for character encoding. Unicode is not an encoding!
http://en.wikipedia.org/wiki/Unicode#Unicode_Transformation_Format_and_Universal_Character_Set
and of course, the obligatory Joel On Software - The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) link.
A couple ways this can be done:
This will make it a square
ul
{
list-style-type: square;
}
This will make it green
li
{
color: #0F0;
}
This will prevent the text from being green
li p
{
color: #000;
}
However that will require that all text within lists be in paragraphs so that the color is not overridden.
A better way is to make an image of a green square and use:
ul
{
list-style: url(green-square.png);
}
map HTTP request header Content-Type
, handle request body.
@RequestParam
? application/x-www-form-urlencoded
,
@RequestBody
? application/json
,
@RequestPart
? multipart/form-data
,
RequestParam (Spring Framework 5.1.9.RELEASE API)
map to query parameters, form data, and parts in multipart requests.
RequestParam
is likely to be used with name-value form fields
RequestBody (Spring Framework 5.1.9.RELEASE API)
bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the
content type
of the request. (e.g. JSON, XML)
RequestPart (Spring Framework 5.1.9.RELEASE API)
used to associate the part of a "
multipart/form-data
" request
RequestPart
is likely to be used with parts containing more complex content
HttpMessageConverter (Spring Framework 5.1.9.RELEASE API)
a converter that can convert from and to HTTP requests and responses.
All Known Implementing Classes: ..., AbstractJsonHttpMessageConverter, AbstractXmlHttpMessageConverter, ...
In python, not
is a boolean operator which gets the opposite of a value:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1
and False == 0
(if you need to convert it to an integer, you can use int()
)
I set up finally using microweber/screen as proposed by @boksiora.
Initially when trying the mentioned link here what I got:
Please download this script from here https://github.com/microweber/screen
I'm on Linux. So if you want to run it, you may adjust my step follow to your environment.
Here are the step I did on my shell on DOCUMENT_ROOT
folder:
$ sudo wget https://github.com/microweber/screen/archive/master.zip
$ sudo unzip master.zip
$ sudo mv screen-master screen
$ sudo chmod +x screen/bin/phantomjs
$ sudo yum install fontconfig
$ sudo yum install freetype*
$ cd screen
$ sudo curl -sS https://getcomposer.org/installer | php
$ sudo php composer.phar update
$ cd ..
$ sudo chown -R apache screen
$ sudo chgrp -R www screen
$ sudo service httpd restart
Point your browser to screen/demo/shot.php?url=google.com
. When you see the screenshot, you are done. Discussion for more advance setting is available here and here.
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
For mac users: in terminal command :
unzip yourWARfileName.war
In the particular case where you know the number of positions that you want to remove from the dataframe column, you can use string indexing inside a lambda function to get rid of that parts:
Last character:
data['result'] = data['result'].map(lambda x: str(x)[:-1])
First two characters:
data['result'] = data['result'].map(lambda x: str(x)[2:])
String guid = System.Guid.NewGuid().ToString();
Otherwise it's a delegate.
NOTE: this topic is about installation issues with MS project templates.
I came here via a search in Google, I was looking for a missing Template option in Visual Studio 2017 File menu: in VS-2015, it was Export to Template and I used it to add my own standard Project Items.
Meanwhile, I found an answer.. my issue was not related to default templates and it does not need install things. The option Export to Template has been moved to the VS-2017 Project menu !
If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.
Ex:
--id is primary key of MainTable
declare @id int
set @id = 1
declare theMain cursor for select FK from MainTable where MainID = @id
declare @fk_Id int
open theMain
fetch next from theMain into @fk_Id
while @@fetch_status=0
begin
--fkid is the foreign key
--Must delete from Main Table first then child.
delete from MainTable where fkid = @fk_Id
delete from ReferencingTable where fkid = @fk_Id
fetch next from theMain into @fk_Id
end
close theMain
deallocate theMain
hope is useful
You have to use UPDATE instead of INSERT:
For Example:
UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
I spent some time recently looking into building html email templates, the best solution I found was to use this http://htmlemailboilerplate.com/. I have since built 3 quite complex templates and they have worked well in the various email clients.