Without some manual String masks or TimeFormatters
import Foundation
struct DateISO: Codable {
var date: Date
}
extension Date{
var isoString: String {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
guard let data = try? encoder.encode(DateISO(date: self)),
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String]
else { return "" }
return json?.first?.value ?? ""
}
}
let dateString = Date().isoString
is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>
, then you wrote <target name="build-subprojects"/>
(it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/>
print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277
I fixed this by adding facets in Module settings. They were missing.
right click on project > open Module settings > Facets > Add facets ( "+" sign at the top ) > Android.
After adding facets you will have modules.
UPDATE:
For latest version of gradle, Facets have been removed, you can directly add modules now.
right click on project > open Module settings > Add module ( "+" sign at the top ) > Phone and Tablet Application (Now you can create a new module and configure it).
I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :
compile fileTree(dir: 'libs', include: '*.jar')}
BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries
http://tools.android.com/recent
Hope this helps people!
This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update
again:
Excluding unwanted Manifest entries fixed the MainClass file not found error in a Gradle build jar file.
jar{
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
from {
-----
}
}
In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:
[core] worktree
line. Mine changed from ../../../AFNetworking
to ../../../../ext/AFNetworking
gitdir
. Mine changed from ../.git/modules/AFNetworking
to ../../git/modules/ext/AFNetworking
git add .gitmodules
git rm --cached AFNetworking
git submodule add -f <url> ext/AFNetworking
Finally, I saw in the git status:
matt$ git status
# On branch ios-master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: .gitmodules
# renamed: AFNetworking -> ext/AFNetworking
Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
Try something like
SELECT
CASE var
WHEN xyz THEN col1
WHEN zyx THEN col2
ELSE col7
END AS col1,
...
In other words, use a conditional expression to select the value, then rename the column.
Alternately, you could build up some sort of dynamic SQL hack to share the query tail; I've done this with iBatis before.
Your initial problem was:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
previous posts correctly point out, if you want a computed property, the =
sign is errant.
Additional possibility for error:
If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }()
}
Instead of removing the =
, we add ()
to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)
However, the exact same error occurs:
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy
. It will not be executed until the value is accessed.
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
lazy var numPages: Int = { return categoriesPerPage.count }()
}
now the compiler is happy!
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
Use this class for encryption. It works.
public class ObjectCrypter {
public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException, IOException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return cipher.doFinal(mes);
}
public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException, IOException, ClassNotFoundException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return cipher.doFinal(bytes);
}
}
And these are ivBytes and a random key;
String key = "e8ffc7e56311679f12b6fc91aa77a5eb";
byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");
To make the whole div act as a link, set the anchor tag as:
display: block
And set your height of the anchor tag to 100%. Then set a fixed height to your div tag. Then style your anchor tag like usual.
For example:
<html>
<head>
<title>DIV Link</title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: #c8c8c8;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: #f8f8f8;
}
</style>
</head>
<body>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
</body> </html>
Good luck!
You can use =A4, in case A4 is having long formula
This works also:
for i in range(19):
plt.subplot(5,4,i+1)
It plots 19 total graphs on one page. The format is 5 down and 4 across..
Use ngStorage
For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.
ngStorage
contains two services, $localStorage
and $sessionStorage
angular.module('app', [
'ngStorage'
]).controller('Ctrl', function(
$scope,
$localStorage,
$sessionStorage
){});
Check the Demo
When you want to generate URL from your Business Logic layer, you do not have the flexibility of using ASP.NET Web Form's Page class/ Control's ResolveUrl(..) etc. Moreover, you may need to generate URL from ASP.NET MVC controller too where you not only miss the Web Form's ResolveUrl(..) method, but also you cannot get the Url.Action(..) even though Url.Action takes only Controller name and Action name, not the relative url.
I tried using
var uri = new Uri(absoluteUrl, relativeUrl)
approach, but there is a problem too. If the web application is hosted in IIS virtual directory, where the url of the app is like this : http://localhost/MyWebApplication1/
, and the relative url is "/myPage" then the relative url is resolved as "http://localhost/MyPage
" which is another problem.
Therefore, in order to overcome such problems, I have written a UrlUtils class which can work from a class library. So, it wont depend on Page class but it depends on ASP.NET MVC. So, if you dont mind adding reference to MVC dll to your class library project then my class will work smoothly. I have tested in IIS virtual directory scenario where the web application url is like this : http://localhost/MyWebApplication/MyPage
. I realized that, sometimes we need to make sure that the Absolute url is SSL url or non SSL url. So, I wrote my class library supporting this option. I have restricted this class library so that the relative url can be absolute url or a relative url that starts with '~/'.
Using this library, I can call
string absoluteUrl = UrlUtils.MapUrl("~/Contact");
Returns : http://localhost/Contact
when the page url is : http://localhost/Home/About
Returns : http://localhost/MyWebApplication/Contact
when the page url is : http://localhost/MyWebApplication/Home/About
string absoluteUrl = UrlUtils.MapUrl("~/Contact", UrlUtils.UrlMapOptions.AlwaysSSL);
Returns : **https**://localhost/MyWebApplication/Contact
when the page url is : http://localhost/MyWebApplication/Home/About
Here is my class Library :
public class UrlUtils
{
public enum UrlMapOptions
{
AlwaysNonSSL,
AlwaysSSL,
BasedOnCurrentScheme
}
public static string MapUrl(string relativeUrl, UrlMapOptions option = UrlMapOptions.BasedOnCurrentScheme)
{
if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return relativeUrl;
if (!relativeUrl.StartsWith("~/"))
throw new Exception("The relative url must start with ~/");
UrlHelper theHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
string theAbsoluteUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
theHelper.Content(relativeUrl);
switch (option)
{
case UrlMapOptions.AlwaysNonSSL:
{
return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? string.Format("http://{0}", theAbsoluteUrl.Remove(0, 8))
: theAbsoluteUrl;
}
case UrlMapOptions.AlwaysSSL:
{
return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? theAbsoluteUrl
: string.Format("https://{0}", theAbsoluteUrl.Remove(0, 7));
}
}
return theAbsoluteUrl;
}
}
@bitestar has the correct solution, but there is one more step:
It was hidden away in the docs, however you must change the launchMode
of the Activity
to anything other than standard
. Otherwise it will be destroyed and recreated instead of being reset to the top.
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
Various ways:
return
break
or continue
when in a loopbreak
to label when in a labeled statement (see @aioobe's example)break
when in a switch statement....
System.exit()
... though that's probably not what you mean.In my opinion, "break to label" is the most natural (least contorted) way to do this if you just want to get out of a try/catch. But it could be confusing to novice Java programmers who have never encountered that Java construct.
But while labels are obscure, in my opinion wrapping the code in a do ... while (false)
so that you can use a break
is a worse idea. This will confuse non-novices as well as novices. It is better for novices (and non-novices!) to learn about labeled statements.
By the way, return
works in the case where you need to break out of a finally
. But you should avoid doing a return
in a finally
block because the semantics are a bit confusing, and liable to give the reader a headache.
const CString REG_SW_GROUP_I_WANT = _T("SOFTWARE\\My Corporation\\My Package\\Group I want");
const CString REG_KEY_I_WANT= _T("Key Name");
CRegKey regKey;
DWORD dwValue = 0;
if(ERROR_SUCCESS != regKey.Open(HKEY_LOCAL_MACHINE, REG_SW_GROUP_I_WANT))
{
m_pobLogger->LogError(_T("CRegKey::Open failed in Method"));
regKey.Close();
goto Function_Exit;
}
if( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT))
{
m_pobLogger->LogError(_T("CRegKey::QueryValue Failed in Method"));
regKey.Close();
goto Function_Exit;
}
// dwValue has the stuff now - use for further processing
>df1.show()
+-----+--------------------+--------+----------+-----------+
|floor| timestamp| uid| x| y|
+-----+--------------------+--------+----------+-----------+
| 1|2014-07-19T16:00:...|600dfbe2| 103.79211|71.50419418|
| 1|2014-07-19T16:00:...|5e7b40e1| 110.33613|100.6828393|
| 1|2014-07-19T16:00:...|285d22e4|110.066315|86.48873585|
| 1|2014-07-19T16:00:...|74d917a1| 103.78499|71.45633073|
>row1 = df1.agg({"x": "max"}).collect()[0]
>print row1
Row(max(x)=110.33613)
>print row1["max(x)"]
110.33613
The answer is almost the same as method3. but seems the "asDict()" in method3 can be removed
Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.
Use return
statement at end of function to return value.
e.g.:
Return None value.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
listView1.View = View.Details;
listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
listView1.Columns.Add(" Range ", 100, HorizontalAlignment.Center);
listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);
i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...
Another idea is to use clipToOutline
property of an ImageView
.
Here is an example layout:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Simple view to draw borders for an image,
borders will be rounded because of the oval-shaped background. -->
<View
android:id="@+id/v_border"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/shape_border"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Image itself: fits the border view,
a margin serves as a border width;
the key point here - is a background shape which will clip the view to its forms. -->
<ImageView
android:id="@+id/iv_image"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
android:background="@drawable/shape_oval"
android:src="@mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="@+id/v_border"
app:layout_constraintEnd_toEndOf="@+id/v_border"
app:layout_constraintStart_toStartOf="@+id/v_border"
app:layout_constraintTop_toTopOf="@+id/v_border" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here are our shape_border
drawable:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#FF00FF" />
</shape>
And shape_oval
drawable:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" />
The only thing you should do in the code - is to enable clipToOutline
property:
binding.ivImage.clipToOutline = true
And of course you can avoid even this line of the code with some BindingAdapter.
You can also use START WITH
to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,
SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
In Linux:
sudo docker ps -aqf "name=containername"
Or in OS X, Windows:
docker ps -aqf "name=containername"
where containername
is your container name.
To avoid getting false positives, as @llia Sidorenko notes, you can use regex anchors like so:
docker ps -aqf "name=^containername$"
explanation:
-q
for quiet. output only the ID-a
for all. works even if your container is not running-f
for filter.^
container name must start with this string$
container name must end with this stringUse cut
:
cut -c6-
This prints each line of the input starting at column 6 (the first column is 1).
Firstly, application.properties in the @PropertySource should read application-test.properties
if that's what the file is named (matching these things up matters):
@PropertySource("classpath:application-test.properties ")
That file should be under your /src/test/resources
classpath (at the root).
I don't understand why you'd specify a dependency hard coded to a file called application-test.properties
. Is that component only to be used in the test environment?
The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.
In a typically laid out application, you'd have:
src/test/resources/application.properties
and
src/main/resources/application.properties
And then inject it like this:
@PropertySource("classpath:application.properties")
The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?
// Here is the simple code using COM object in PHP
class Excel_ReadWrite{
private $XLSHandle;
private $WrkBksHandle;
private $xlBook;
function __construct() {
$this->XLSHandle = new COM("excel.application") or die("ERROR: Unable to instantaniate COM!\r\n");
}
function __destruct(){
//if already existing file is opened
if($this->WrkBksHandle != null)
{
$this->WrkBksHandle->Close(True);
unset($this->WrkBksHandle);
$this->XLSHandle->Workbooks->Close();
}
//if created new xls file
if($this->xlBook != null)
{
$this->xlBook->Close(True);
unset($this->xlBook);
}
//Quit Excel Application
$this->XLSHandle->Quit();
unset($this->XLSHandle);
}
public function OpenFile($FilePath)
{
$this->WrkBksHandle = $this->XLSHandle->Workbooks->Open($FilePath);
}
public function ReadData($RowNo, $ClmNo)
{
$Value = $this->XLSHandle->ActiveSheet->Cells($RowNo, $ClmNo)->Value;
return $Value;
}
public function SaveOpenedFile()
{
$this->WrkBksHandle->Save();
}
/***********************************************************************************
* Function Name:- WriteToXlsFile() will write data based on row and column numbers
* @Param:- $CellData- cell data
* @Param:- $RowNumber- xlsx file row number
* @Param:- $ColumnNumber- xlsx file column numbers
************************************************************************************/
function WriteToXlsFile($CellData, $RowNumber, $ColumnNumber)
{
try{
$this->XLSHandle->ActiveSheet->Cells($RowNumber,$ColumnNumber)->Value = $CellData;
}
catch(Exception $e){
throw new Exception("Error:- Unable to write data to xlsx sheet");
}
}
/****************************************************************************************
* Function Name:- CreateXlsFileWithClmName() will initialize xls file with column Names
* @Param:- $XlsColumnNames- Array of columns data
* @Param:- $XlsColumnWidth- Array of columns width
*******************************************************************************************/
function CreateXlsFileWithClmNameAndWidth($WorkSheetName = "Raman", $XlsColumnNames = null, $XlsColumnWidth = null)
{
//Hide MS Excel application window
$this->XLSHandle->Visible = 0;
//Create new document
$this->xlBook = $this->XLSHandle->Workbooks->Add();
//Create Sheet 1
$this->xlBook->Worksheets(1)->Name = $WorkSheetName;
$this->xlBook->Worksheets(1)->Select;
if($XlsColumnWidth != null)
{
//$XlsColumnWidth = array("A1"=>15,"B1"=>20);
foreach($XlsColumnWidth as $Clm=>$Width)
{
//Set Columns Width
$this->XLSHandle->ActiveSheet->Range($Clm.":".$Clm)->ColumnWidth = $Width;
}
}
if($XlsColumnNames != null)
{
//$XlsColumnNames = array("FirstColumnName"=>1, "SecondColumnName"=>2);
foreach($XlsColumnNames as $ClmName=>$ClmNumber)
{
// Cells(Row,Column)
$this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Value = $ClmName;
$this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Font->Bold = True;
$this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Interior->ColorIndex = "15";
}
}
}
//56 is for xls 8
public function SaveCreatedFile($FileName, $FileFormat = 56)
{
$this->xlBook->SaveAs($FileName, $FileFormat);
}
public function MakeFileVisible()
{
//Hide MS Excel application window`enter code here`
$this->XLSHandle->Visible = 1;
}
}//end of EXCEL class
From MySQL reference of CREATE VIEW
:
The DEFINER and SQL SECURITY clauses specify the security context to be used when checking access privileges at view invocation time.
This user must exist and is always better to use 'localhost' as hostname. So I think that if you check that the user exists and change it to 'localhost' on create view you won't have this error.
My personal taste is to attribute the :hover
styles to the :focus
state as well, like:
p {
color: red;
}
p:hover, p:focus {
color: blue;
}
Then with the following HTML:
<p id="some-p-tag" tabindex="-1">WOOOO</p>
And the following JavaScript:
$("#some-p-tag").on("touchstart", function(e){
e.preventDefault();
var $elem = $(this);
if($elem.is(":focus")) {
//this can be registered as a "click" on a mobile device, as it's a double tap
$elem.blur()
}
else {
$elem.focus();
}
});
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
I did a pure javascript hack to make this possible.
<div class="my_background_image" style="background-image: url(broken-image.jpg)">
<img class="image_error" src="broken-image.jpg" onerror="this.parentElement.style.display='none';">
</div>
Or
onerror="this.parentElement.backgroundImage = "url('image_placeHolder.png')";
css:
.image_error {
display: none;
}
ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd
directly.
It is a much safer way than running batch files!
You could use the undocumented
DBCC LOG(databasename, typeofoutput)
where typeofoutput:
0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.
For example, DBCC LOG(database, 1)
You could also try fn_dblog.
For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.
You can revert all your files under your working directory and index by typing following this command
git reset --hard <SHAsum of your commit>
You can also type
git reset --hard HEAD #your current head point
or
git reset --hard HEAD^ #your previous head point
Hope it helps
A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is " + df.format(d));
gives
date is 2011-12-05
formatted date is 05/12/2011
Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.
target_compile_options
solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)
I ran into this issue using Phusion Passenger (running as an nginx module) on a Redhat server. We already had a Javascript runtime installed. Other Rails apps in the same parent directory worked fine.
It turned out that we had a permissions issue. Run "ls -l" and see if the folder has the same owner and group as other working apps on the system. I had to run chown and chgrp on the folder (with the recursive switch) to fix it.
I thought of
SELECT LENGTH('123-345-566') - LENGTH(REPLACE('123-345-566', '-', '')) FROM DUAL;
You can easily do this with a Hashmap
. You obviously have a key (which is the String data) and some values.
Loop on all your lines and add them to your Map.
Map<String, List<Integer>> map = new HashMap<>();
...
while (s.hasNext()){
String stringData = ...
List<Integer> values = ...
map.put(stringData,values);
}
Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData);
before putting in the map.
If the latitude coordinate is reported as -6.3572375290155 or -63.572375290155 in decimal degrees then you could round-off and store up to 6 decimal places for 10 cm (or 0.1 meters) precision.
The valid range of latitude in degrees is -90 and +90 for the southern and northern hemisphere respectively. Longitude is in the range -180 and +180 specifying coordinates west and east of the Prime Meridian, respectively.
For reference, the Equator has a latitude of 0°, the North pole has a latitude of 90° north (written 90° N or +90°), and the South pole has a latitude of -90°.
The Prime Meridian has a longitude of 0° that goes through Greenwich, England. The International Date Line (IDL) roughly follows the 180° longitude. A longitude with a positive value falls in the eastern hemisphere and the negative value falls in the western hemisphere.
Six (6) decimal places precision in coordinates using decimal degrees notation is at a 10 cm (or 0.1 meters) resolution. Each .000001 difference in coordinate decimal degree is approximately 10 cm in length. For example, the imagery of Google Earth and Google Maps is typically at the 1-meter resolution, and some places have a higher resolution of 1 inch per pixel. One meter resolution can be represented using 5 decimal places so more than 6 decimal places are extraneous for that resolution. The distance between longitudes at the equator is the same as latitude, but the distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.
For millimeter (mm) precision then represent lat/lon with 8 decimal places in decimal degrees format. Since most applications don't need that level of precision 6 decimal places is sufficient for most cases.
In the other direction, whole decimal degrees represent a distance of ~111 km (or 60 nautical miles) and a 0.1 decimal degree difference represents a ~11 km distance.
Here is a table of # decimal places difference in latitude with the delta degrees and the estimated distance in meters using 0,0 as the starting point.
Decimal places | Decimal degrees | Distance (meters) | |
---|---|---|---|
1 | 0.10000000 | 11,057.43 | 11 km |
2 | 0.01000000 | 1,105.74 | 1 km |
3 | 0.00100000 | 110.57 | |
4 | 0.00010000 | 11.06 | |
5 | 0.00001000 | 1.11 | |
6 | 0.00000100 | 0.11 | 11 cm |
7 | 0.00000010 | 0.01 | 1 cm |
8 | 0.00000001 | 0.001 | 1 mm |
For DMS notation 1 arc second = 1/60/60 degree = ~30 meter length and 0.1 arc sec delta is ~3 meters.
Example:
0° 0' 0" W, 0° 0' 0" N
? 0° 0' 0" W, 0° 0' 1" N
? 30.715 meters0° 0' 0" W, 0° 0' 0" N
? 0° 0' 0" W, 0° 0' 0.1" N
? 3.0715 meters1 arc minute = 1/60 degree = ~2000m (2km)
Here is an amusing comic strip about coordinate precision.
You can delete cache directory of nginx or You can search specific file:
grep -lr 'http://mydomain.pl/css/myedited.css' /var/nginx/cache/*
And delete only one file to nginx refresh them.
The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.
http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm
Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.
I put the data starting on row 5:
Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.
That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.
Please not that rand()
does not generate a cryptographically secure value according to the docs:
http://php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
Instead it is better to use random_int()
, available on PHP 7 (See: http://php.net/manual/en/function.random-int.php).
So to extend @Marcus's answer, you should use:
function generateSecureRandomNumber($digits): int {
return random_int(pow(10, $digits - 1), pow(10, $digits) - 1);
}
function generateSecureRandomNumberWithPadding($digits): string {
$randomNumber = random_int(0, pow(10, $digits) - 1);
return str_pad($randomNumber, $digits, '0', STR_PAD_LEFT);
}
Note that using rand()
is fine if you don't need a secure random number.
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
There are detailed notes on this that helped me completely, located here.
Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart
However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:
external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
"X-Forwarded-Proto" => "http",
"CUSTOM_HEADER" => "VALUE"
}
Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by
sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.
As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:
sudo gitlab-ctl tail nginx
'<option value=''.$key.'">'
should be
'<option value="'.$key.'">'
A better idea,
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for
?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Markup Generated after error
<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
A. Sign in if you are not signed in already.
B. If signed in already, click the link Check for an updated license on the account settings page.
C. "We could not download a license. Please ensure your accounts are authenticated." If this message is encountered, sign out and sign back in. You can either sign out by clicking on the Sign out link and then signing back in by clicking on the account icon in the upper right corner of Visual Studio. Or you can just click the link Reenter your credentials. This link is a good indication that your account is not synced up with Microsoft servers and the error message is right in that your account is not authenticated and the license cannot be refreshed.
Once you have signed back in and your account is successfully authenticated, you will see that the "Reenter your credentials" link is gone. This is a good indicator that you can now go ahead and refresh the license. If it does not do that automatically you can click the Check for an updated license link once again. This time you will see a short confirmation message and your associated email address will be listed.
Signing in is inevitable if you want to get rid of this annoying warning. But even if you have always been signed from day one, you may still run into this warning. Based on my experience, this may happen if you have recently changed the password for your account, or you have added 2FA (two step verification) to your account, or you have reset the recovery code for the account and with it the app passwords. It may also have to do with inactivity or the recent changes Microsoft has been making to the "sign in experience" for Microsoft accounts.
Whatever the reason may be, signing in, or signing out and then signing back in again appears to be the best treatment for this annoyance.
You also can use react-location-query package, example:
const [name, setName] = useLocationField("name", {
type: "string",
initial: "Rostyslav"
});
return (
<div className="App">
<h1>Hello {name}</h1>
<div>
<label>Change name: </label>
<input value={name} onChange={e => setName(e.target.value)} />
</div>
</div>
);
name - to get value setName = to set value
This package has many options, read more in docs on Github
Insert this in your Makefile
$(MAKE) -C $(KDIR) M=$(PWD) modules_install
it will install the module in the directory /lib/modules/<var>/extra/
After make , insert module with modprobe module_name (without .ko extension)
OR
After your normal make, you copy module module_name.ko into directory /lib/modules/<var>/extra/
then do modprobe module_name (without .ko extension)
Make sure the scp command is available on both sides - both on the client and on the server.
If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:
yum -y install openssh-clients
If you work with Debian or Ubuntu and clones, install this package:
apt-get install openssh-client
Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found
or similar although you have it locally. This already confused thousands of people, I guess :)
In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%'
there
are position
(reversed order of args) and strpos
.
SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0
Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain %
and especially _
(single char wildcard), to give no false positives.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
several years ago I wrote script library for bash which supported associative arrays among other features (logging, configuration files, extended support for command line argument, generate help, unit testing, etc). The library contains a wrapper for associative arrays and automatically switches to appropriate model (internal for bash4 and emulate for previous versions). It was called shell-framework and hosted at origo.ethz.ch but today the resource is closed. If someone still needs it I can share it with you.
To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile
Vagrant.configure("2") do |config|
# usual vagrant config here
config.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 2
end
end
If you want to get classes of div and then want to check if any class exists then simple use.
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// do something...
}
e.g;
if ( $('body').hasClass( 'home' ) ) {
$('#menu-item-4').addClass('active');
}
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
oSheet.get_Range("A1", "AS1").Merge();
In Python 3, raw_input()
doesn't exist which was already mentioned by Sven.
In Python 2, the input()
function evaluates your input.
Example:
name = input("what is your name ?")
what is your name ?harsha
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
name = input("what is your name ?")
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":
>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha
raw_input()
The raw_input()` function doesn't evaluate, it will just read whatever you enter.
Example:
name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'
Example:
name = eval(raw_input("what is your name?"))
what is your name?harsha
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
name = eval(raw_input("what is your name?"))
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In example above, I was just trying to evaluate the user input with the eval
function.
You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString()
on each object in the list. You could think that given it is a list of SelectListItem
it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each items selected true/false.
Then, in your view:
@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType
will be null (the UserType
need to be int?
).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
from this blog:
You can temporarily disable foreign key checks:
SET FOREIGN_KEY_CHECKS=0;
Just be sure to restore them once you’re done messing around:
SET FOREIGN_KEY_CHECKS=1;
You can check this
[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{
string url = "https://localhost:44305/Templates/ReportPage.html";
System.Uri uri = new System.Uri(url);
return Redirect(uri);
}
Set the version number to "1.0.*" and it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight)
There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor)
and .AddFromFile(Filename)
. Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile
because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.
The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)
If you are having problems getting the code to run, there are two possible issues.
Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.
left = None
left is None #evaluates to True
This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md
Symfony 2.1 has a JsonResponse class.
return new JsonResponse(array('name' => $name));
The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.
There is also a handy setCallback
function for JSONP.
match_parent
and fill_parent
are same property, used to define width or height of a view in full screen horizontally or vertically.
These properties are used in android xml files like this.
android:layout_width="match_parent"
android:layout_height="fill_parent"
or
android:layout_width="fill_parent"
android:layout_height="match_parent"
fill_parent
was used in previous versions, but now it has been deprecated and replaced by match_parent
.
I hope it'll help you.
I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.
One column was a CHAR (90) and the other was a BIGINT (20).
One table was InnoDB and the other was MEMORY.
Part of query:
[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );
Changing the column type on the one column from BIGINT to CHAR solved the issue.
Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.
Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.
The advantages over other FTS (full text search) Engines are:
We are using this search engine at our project and very happy with it.
Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.
Here's an example:
<section class="content">
<div class="modal"></div>
</section>
<div class="side-tab"></div>
// CSS //
.content {
position: relative;
z-index: 1;
}
.modal {
position: fixed;
z-index: 100;
}
.side-tab {
position: fixed;
z-index: 5;
}
In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.
Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/
You need to have file system permission to create the directory.
Example: In Ubuntu 10.04 apache (php) runs as user: www-data in group: www-data
Meaning the user www-data needs access to create the directory.
You can try this yourself by using: 'su www-data' to become the www-data user.
As a quick fix, you can do: sudo chmod 777 my_parent_dir
Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following
<?php
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
$arrayCount = 0
while ($row = mysql_fetch_row($result)) {
$tableNames[$arrayCount] = $row[0];
$arrayCount++; //only do this to make sure it starts at index 0
}
foreach ($tableNames as &$name {
$query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
mysql_query($query);
}
?>
Go read about HP Labs' Dynamo, an interpreter for PA-8000 that runs on PA-8000, and often runs programs faster than they do natively. Then it won't seem at all surprising!
Don't think of it as an "intermediate step" -- running a program involves lots of other steps already, in any language.
It often comes down to:
programs have hot-spots, so even if you're slower running 95% of the body of code you have to run, you can still be performance-competitive if you're faster at the hot 5%
a HLL knows more about your intent than a LLL like C/C++, and so can generate more optimized code (OCaml has even more, and in practice is often even faster)
a JIT compiler has a lot of information that a static compiler doesn't (like, the actual data you happen to have this time)
a JIT compiler can do optimizations at run-time that traditional linkers aren't really allowed to do (like reordering branches so the common case is flat, or inlining library calls)
All in all, C/C++ are pretty lousy languages for performance: there's relatively little information about your data types, no information about your data, and no dynamic runtime to allow much in the way of run-time optimization.
What I did to solve this -
AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
filepaths.xml (Allowing the FileProvider to share all the files that are inside the app's external files directory)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="files"
path="/" />
</paths>
and in java class -
Uri fileProvider = FileProvider.getUriForFile(getContext(),"com.mydomain.fileprovider",newFile);
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.
mWebView.setWebViewClient(new WebViewClient()
{
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
// Here put your code
return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
}
});
Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'
. (you need to use the hex number, not the 8226 decimal one)
Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.
I did some speed tests on Firefox.
-100/3 // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34, 0.5016 millisec
~~(-100/3) // -33, 0.3619 millisec
(-100/3>>0) // -33, 0.3632 millisec
(-100/3|0) // -33, 0.3856 millisec
(-100-(-100%3))/3 // -33, 0.3591 millisec
/* a=-100, b=3 */
a/b // -33.33..., 0.4863 millisec
Math.floor(a/b) // -34, 0.6019 millisec
~~(a/b) // -33, 0.5148 millisec
(a/b>>0) // -33, 0.5048 millisec
(a/b|0) // -33, 0.5078 millisec
(a-(a%b))/b // -33, 0.6649 millisec
The above is based on 10 million trials for each.
Conclusion: Use (a/b>>0)
(or (~~(a/b))
or (a/b|0)
) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor
, when a/b<0 && a%b!=0
.
Hey It's very simple see this
@OLD_GUEST_NAME = d.GUEST_NAME from deleted d;
this variable will store your old deleted value and then you can insert it where you want.
for example-
Create trigger testupdate on test for update, delete
as
declare @tableid varchar(50);
declare @testid varchar(50);
declare @newdata varchar(50);
declare @olddata varchar(50);
select @tableid = count(*)+1 from audit_test
select @testid=d.tableid from inserted d;
select @olddata = d.data from deleted d;
select @newdata = i.data from inserted i;
insert into audit_test (tableid, testid, olddata, newdata) values (@tableid, @testid, @olddata, @newdata)
go
I know this is a bit late, but I'm having a similar issue. SQL*Plus
executes the query successfully, but Oracle SQL Developer
shows the ORA-01843: not a valid month error.
SQL*Plus
seems to know that the date I'm using is in the valid format, whereas Oracle SQL Developer needs to be told explicitly what format my date is in.
SQL*Plus statement
:
select count(*) from some_table where DATE_TIME_CREATED < '09-12-23';
VS
Oracle SQL Developer statement
:
select count(*) from some_table where DATE_TIME_CREATED < TO_DATE('09-12-23','RR-MM-DD');
Occurs when the text content of an element is changed through the user interface.
It's not quite an alias for keyup
because keyup
will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup
event).
A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl
by itself will not trigger the event, but Ctrl-V
to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.
See this page and the comments on this answer for more details.
Below sync command resolved the issue :
git submodule sync
I haven't played with these settings myself so this is just speculation but if we think about this issue as normal cores and threads in a distributed system then in your cluster you can use up to 12 cores (4 * 3 machines) and 24 threads (8 * 3 machines). In your first two examples you are giving your job a fair number of cores (potential computation space) but the number of threads (jobs) to run on those cores is so limited that you aren't able to use much of the processing power allocated and thus the job is slower even though there is more computation resources allocated.
you mention that your concern was in the shuffle step - while it is nice to limit the overhead in the shuffle step it is generally much more important to utilize the parallelization of the cluster. Think about the extreme case - a single threaded program with zero shuffle.
cur_ques_details
is already a JS object, you don't need to parse it
It seems like two different scenarios are being mixed together in this discussion:
Scenario 1
Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.
This is, as pointed out, done with
git submodule foreach git pull origin BRANCH
git submodule update
Scenario 2, which I think is what OP is aiming at
New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.
This would be done by
git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH
Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.
It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add
) to point to the head of the submodule(s).
For this, I made this small Bash script:
git-update-submodules.sh
#!/bin/bash
APP_PATH=$1
shift
if [ -z $APP_PATH ]; then
echo "Missing 1st argument: should be path to folder of a git repo";
exit 1;
fi
BRANCH=$1
shift
if [ -z $BRANCH ]; then
echo "Missing 2nd argument (branch name)";
exit 1;
fi
echo "Working in: $APP_PATH"
cd $APP_PATH
git checkout $BRANCH && git pull --ff origin $BRANCH
git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH
To run it, execute
git-update-submodules.sh /path/to/base/repo BRANCH_NAME
Elaboration
First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.
The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).
git checkout $BRANCH && git pull --ff origin $BRANCH
Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:
git submodule sync
git submodule init
git submodule update
Then I update/pull all submodules:
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
Notice a few things: First of all, I'm chaining some Git commands using &&
- meaning previous command must execute without error.
After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.
Finally, the final || true
is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).
My favourite part:
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
Iterate all submodules - with --quiet
, which removes the 'Entering MODULE_PATH' output. Using 'echo $path'
(must be in single-quotes), the path to the submodule gets written to output.
This list of relative submodule paths is captured in an array ($(...)
) - finally iterate this and do git add $i
to update the parent repository.
Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.
I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.
I hope this will be of help to someone.
Google lead me here while searching on the same question phill asked (sorting floats) so I figured it would be worth posting the answer despite the thread being kind of old. I'm new to perl and am still getting my head wrapped around it but brian d foy's statement "Perl cares more about the verbs than it does the nouns." above really hits the nail on the head. You don't need to convert the strings to floats before applying the sort. You need to tell the sort to sort the values as numbers and not strings. i.e.
my @foo = ('1.2', '3.4', '2.1', '4.6');
my @foo_sort = sort {$a <=> $b} @foo;
See http://perldoc.perl.org/functions/sort.html for more details on sort
I think it should be the case. To erase the character, you should use replace(".", "")
instead.
I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):
private string PasswordSalt
{
get
{
var rng = new RNGCryptoServiceProvider();
var buff = new byte[32];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
}
private string EncodePassword(string password, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] src = Encoding.Unicode.GetBytes(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inarray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inarray);
}
I had the same question. Without knowing it, I had created a dangling commit.
List dangling commits
git fsck --lost-found
Inspect each dangling commit
git reset --hard <commit id>
My files reappeared when I moved to the dangling commit.
git status
for the reason:
“HEAD detached from <commit id where it detached>”
It leaves blank pages so that a new part or chapter start on the right-hand side. You can fix this with the "openany" option for the document class. ;)
As of PHP 5.5, PHP has simple, secure functions for hashing and verifying passwords, password_hash() and password_verify()
$password = 'anna';
$hash = password_hash($password, PASSWORD_DEFAULT);
$expensiveHash = password_hash($password, PASSWORD_DEFAULT, array('cost' => 20));
password_verify('anna', $hash); //Returns true
password_verify('anna', $expensiveHash); //Also returns true
password_verify('elsa', $hash); //Returns false
When password_hash()
is used, it generates a random salt and includes it in the outputted hash (along with the the cost and algorithm used.) password_verify()
then reads that hash and determines the salt and encryption method used, and verifies it against the provided plaintext password.
Providing the PASSWORD_DEFAULT
instructs PHP to use the default hashing algorithm of the installed version of PHP. Exactly which algorithm that means is intended to change over time in future versions, so that it will always be one of the strongest available algorithms.
Increasing cost (which defaults to 10) makes the hash harder to brute-force but also means generating hashes and verifying passwords against them will be more work for your server's CPU.
Note that even though the default hashing algorithm may change, old hashes will continue to verify just fine because the algorithm used is stored in the hash and password_verify()
picks up on it.
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:
string removeCharsFromString(const string str, char* charsToRemove )
{
char c[str.length()+1]; // + terminating char
const char *p = str.c_str();
unsigned int z=0, size = str.length();
unsigned int x;
bool rem=false;
for(x=0; x<size; x++)
{
rem = false;
for (unsigned int i = 0; charsToRemove[i] != 0; i++)
{
if (charsToRemove[i] == p[x])
{
rem = true;
break;
}
}
if (rem == false) c[z++] = p[x];
}
c[z] = '\0';
return string(c);
}
Just use as
myString = removeCharsFromString(myString, "abc\r");
and it will remove all the occurrence of the given char list.
This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.
Here's a working example:
<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
<b>{{key}}</b> : {{value}}
</div>
edited
This is one way without using time a zone:
LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);
To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-
__block Person *aPerson = nil;
using ssh from java should not be as hard as jsch makes it. you might be better off with sshj.
Coming from the Mozilla Documentation, "You can use the delete operator to delete variables declared implicitly but not those declared with the var statement. "
Here is the link: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Operators:Special_Operators:delete_Operator
Wamp server default disk is "C:\"
if you install it to another disk for ex G:\
:
go to
g:\wamp\bin\apache\apache2.4.9\bin\
2 .call cmd
3 .execute httpd.exe -t
you will see errors
go to
g:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf
change in line 23 to :
Alias /icons/ "g:/Apache24/icons/"
<Directory "g:/Apache24/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
The trick to using display:none with images is to assign them an id. This was there is not a lot of code needed to make it work. Here is an example using media queries and 3 stylesheets. One for phone, one for tablet, and one for desktop. I have 3 images, image of a phone, a tablet, and a desktop. On a phone screen only an image of the phone will display, a tablet will display only the tablet image, a desktop displays on the desktop computer image. Here is a code example to make it work:
Source code:
<div id="content">
<img id="phone" src="images/phone.png" />
<img id="tablet" src="images/tablet.png" />
<img id="desktop" src="images/desktop.png" />
</div>
The phone CSS which doesn't need a media query. Its the img#phone that makes it work:
img#phone {
display: block;
margin: 6em auto 0 auto;
width: 70%;
}
img#tablet {display: none;}
img#desktop {display: none;}
The tablet css:
@media only screen and (min-width: 641px) {
img#phone {display: none;}
img#tablet {
display: block;
margin: 6em auto 0 auto;
width: 70%;
}
}
And the desktop css:
@media only screen and (min-width: 1141px) {
img#tablet {display: none;}
img#desktop {
display: block;
margin: 6em auto 0 auto;
width: 80%;
}
}
Good luck and let me know how it works for you.
mysql> SET PASSWORD = PASSWORD('your_new_password');
That works for me.
Here is a simple method which can avoid the use of PhonestateListener
and other complications.
So here we are receiving the 3 events from android such as RINGING
,OFFHOOK
and IDLE
. And in order to get the all possible state of call,we need to define our own states like RINGING
, OFFHOOK
, IDLE
, FIRST_CALL_RINGING
, SECOND_CALL_RINGING
.
It can handle every states in a phone call.
Please think in a way that we are receiving events from android and we will define our on call states. See the code.
public class CallListening extends BroadcastReceiver {
private static final String TAG ="broadcast_intent";
public static String incoming_number;
private String current_state,previus_state,event;
public static Boolean dialog= false;
private Context context;
private SharedPreferences sp,sp1;
private SharedPreferences.Editor spEditor,spEditor1;
public void onReceive(Context context, Intent intent) {
//Log.d("intent_log", "Intent" + intent);
dialog=true;
this.context = context;
event = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "The received event : "+event+", incoming_number : " + incoming_number);
previus_state = getCallState(context);
current_state = "IDLE";
if(incoming_number!=null){
updateIncomingNumber(incoming_number,context);
}else {
incoming_number=getIncomingNumber(context);
}
switch (event) {
case "RINGING":
Log.d(TAG, "State : Ringing, incoming_number : " + incoming_number);
if((previus_state.equals("IDLE")) || (previus_state.equals("FIRST_CALL_RINGING"))){
current_state ="FIRST_CALL_RINGING";
}
if((previus_state.equals("OFFHOOK"))||(previus_state.equals("SECOND_CALL_RINGING"))){
current_state = "SECOND_CALL_RINGING";
}
break;
case "OFFHOOK":
Log.d(TAG, "State : offhook, incoming_number : " + incoming_number);
if((previus_state.equals("IDLE")) ||(previus_state.equals("FIRST_CALL_RINGING")) || previus_state.equals("OFFHOOK")){
current_state = "OFFHOOK";
}
if(previus_state.equals("SECOND_CALL_RINGING")){
current_state ="OFFHOOK";
startDialog(context);
}
break;
case "IDLE":
Log.d(TAG, "State : idle and incoming_number : " + incoming_number);
if((previus_state.equals("OFFHOOK")) || (previus_state.equals("SECOND_CALL_RINGING")) || (previus_state.equals("IDLE"))){
current_state="IDLE";
}
if(previus_state.equals("FIRST_CALL_RINGING")){
current_state = "IDLE";
startDialog(context);
}
updateIncomingNumber("no_number",context);
Log.d(TAG,"stored incoming number flushed");
break;
}
if(!current_state.equals(previus_state)){
Log.d(TAG, "Updating state from "+previus_state +" to "+current_state);
updateCallState(current_state,context);
}
}
public void startDialog(Context context) {
Log.d(TAG,"Starting Dialog box");
Intent intent1 = new Intent(context, NotifyHangup.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
}
public void updateCallState(String state,Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
spEditor = sp.edit();
spEditor.putString("call_state", state);
spEditor.commit();
Log.d(TAG, "state updated");
}
public void updateIncomingNumber(String inc_num,Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
spEditor = sp.edit();
spEditor.putString("inc_num", inc_num);
spEditor.commit();
Log.d(TAG, "incoming number updated");
}
public String getCallState(Context context){
sp1 = PreferenceManager.getDefaultSharedPreferences(context);
String st =sp1.getString("call_state", "IDLE");
Log.d(TAG,"get previous state as :"+st);
return st;
}
public String getIncomingNumber(Context context){
sp1 = PreferenceManager.getDefaultSharedPreferences(context);
String st =sp1.getString("inc_num", "no_num");
Log.d(TAG,"get incoming number as :"+st);
return st;
}
}
Using Windows Powershell, if the following expression returns true, then it's a 64 bit OS:
(([Array](Get-WmiObject -Class Win32_Processor | Select-Object AddressWidth))[0].AddressWidth -eq 64)
This was taken and modified from: http://depsharee.blogspot.com/2011/06/how-do-detect-operating-system.html (Method #3). I've tested this on Win7 64 bit (in both 32 and 64 bit PowerShell sessions), and XP 32 bit.
Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello"
that would probably end up as "H\0e\0l\0l\0o\0\0\0"
and your program would only print the 'H'
before it sees what it thinks is a null terminator.
So now you may wonder why it even compiles and links.
Well it compiles because you are allowed to define an overload to a function.
Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.
Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[])
version.
Well you can use below command to export,
mysqldump --databases --user=root --password your_db_name > export_into_db.sql
and the generated file will be available in the same directory where you had ran this command.
Now login to mysql using command,
mysql -u[username] -p
then use "source" command with the file path.
One possible solution would to use regex.
'phone' => 'required|regex:/(01)[0-9]{9}/'
This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric
or size
validation rules.
If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.
In your AppServiceProvider
's boot
method:
Validator::extend('phone_number', function($attribute, $value, $parameters)
{
return substr($value, 0, 2) == '01';
});
This will allow you to use the phone_number
validation rule anywhere in your application, so your form validation could be:
'phone' => 'required|numeric|phone_number|size:11'
In your validator extension you could also check if the $value
is numeric and 11 characters long.
An alternative way you can do this, is using dictionary comprehension. This should be compatible with 2.7+
result = {
key: value for key, value in
{"foo": "bar", "lorem": None}.items()
if value
}
Elegant easy solution using jQuery.
<script>
function call() {
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
});
}
</script>
and in your html :
<div onclick="call()"><img src="../img/[email protected]"></div>
You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.
IDLE output.
>>> round(2.99999999999)
3
>>> round(2.6)
3
>>> round(2.5)
3
>>> round(2.4)
2
You can use something like this pseudo code:
request = System.Net.HttpWebRequest.Create(your url)
request.Method = WebRequestMethods.Http.Post
writer = New System.IO.StreamWriter(request.GetRequestStream())
writer.Write("your data")
writer.Close()
response = request.GetResponse()
reader = New System.IO.StreamReader(response.GetResponseStream())
responseText = reader.ReadToEnd
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
You can use "ELSE IF" using conditional operator in expression language as below:
<p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending':
transaction.status.equals('RJCTD')?'Rejected':
transaction.status.equals('CNFRMD')?'Confirmed':
transaction.status.equals('PSTD')?'Posted':''}"/>
Skip reading the html and use curl
to POST whatever form data you want to submit to the server.
Kotlin solution using extension function, to set and unset the tinting :
fun ImageView.setTint(@ColorInt color: Int?) {
if (color == null) {
ImageViewCompat.setImageTintList(this, null)
return
}
ImageViewCompat.setImageTintMode(this, PorterDuff.Mode.SRC_ATOP)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(color))
}
I am also new to this.
I have followed this process to start the application in Mac:
apache-jmeter-3.3_src.zip
from
http://jmeter.apache.org/download_jmeter.cgi website.jmeter
, this is an executable file. Right click
on this and open with terminal and wait for 5 minutes, that's it.Thank you, I hope this might help.
For completeness, I'll mention that Oracle 12c does support this feature. Also it's supposedly faster than the triggers approach. For example:
CREATE TABLE foo
(
id NUMBER GENERATED BY DEFAULT AS IDENTITY (
START WITH 1 NOCACHE ORDER ) NOT NULL ,
name VARCHAR2 (50)
)
LOGGING ;
ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY ( id ) ;
Well one of the option is to goto your workspace, your project folder, then bin copy and paste the log4j properites file. it would be better to paste the file also in source folder.
Now you may want to know from where to get this file, download smslib, then extract it, then smslib->misc->log4j sample configuration -> log4j here you go.
This what helped,me so just wanted to know.
You should had in mind that...
contructor()
constructor(a:any, b:any, c:any)
It's the same as new()
or new("a","b","c")
Thus
constructor(a?:any, b?:any, c?:any)
is the same above and is more flexible...
new()
or new("a")
or new("a","b")
or new("a","b","c")
You don't want Boost lexical_cast for string <-> floating point anyway. That subset of use cases is the only set for which boost consistently is worse than the older functions- and they basically concentrated all their failure there, because their own performance results show a 20-25X SLOWER performance than using sscanf and printf for such conversions.
Google it yourself. boost::lexical_cast can handle something like 50 conversions and if you exclude the ones involving floating point #s its as good or better as the obvious alternatives (with the added advantage of being having a single API for all those operations). But bring in floats and its like the Titanic hitting an iceberg in terms of performance.
The old, dedicated str->double functions can all do 10000 parses in something like 30 ms (or better). lexical_cast takes something like 650 ms to do the same job.
You can use select2 plugin for creating such a filter. With this lot's of coding work can be avoided. You can grab the plugin from https://select2.github.io/
This plugin is much simple to apply and even advanced work can be easily done with it. :)
recently i wanted to know the assembly of each functions in a program
this is how i did it.
$ gcc main.c // main.c source file
$ gdb a.exe // gdb a.out in linux
(gdb) disass main // note here main is a function
// similary it can be done for other functions
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
If so,go into your config file,my.cnf and add or uncomment these lines:
character-set-server = utf8
collation-server = utf8_unicode_ci
Restart the server. Yes late to the party,just encountered the same issue.
Given your example, you need to add the following import in your main.main
class:
import second.second;
Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:
package main; //lowercase package names
public class Main //titlecase class names
{
//Main class content
}
You can check for yourself.
In this fiddle, I ran a test to demonstrate the blocking nature of await
, as opposed to Promise.all
which will start all of the promises and while one is waiting it will go on with the others.
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
You can do it with initializer list:
std::vector<unsigned int> array;
// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });
Some compact syntax that achieves the desired result, POJS:
"mousemove touchmove".split(" ").forEach(function(e){
window.addEventListener(e,mouseMoveHandler,false);
});
public static String getCurrentMonthFirstDate(){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
//System.out.println(df.format(c.getTime()));
return df.format(c.getTime());
}
You can use the Reflection API
You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:
DO $$ BEGIN
CASE
WHEN boolean-expression THEN
statements;
WHEN boolean-expression THEN
statements;
...
ELSE
statements;
END CASE;
END $$;
References:
I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.
you can put all route functions in other files(modules) , and link it to the main server file. in the main express file, add a function that will link the module to the server:
function link_routes(app, route_collection){
route_collection['get'].forEach(route => app.get(route.path, route.func));
route_collection['post'].forEach(route => app.post(route.path, route.func));
route_collection['delete'].forEach(route => app.delete(route.path, route.func));
route_collection['put'].forEach(route => app.put(route.path, route.func));
}
and call that function for each route model:
link_routes(app, require('./login.js'))
in the module files(for example - login.js file), define the functions as usual:
const login_screen = (req, res) => {
res.sendFile(`${__dirname}/pages/login.html`);
};
const forgot_password = (req, res) => {
console.log('we will reset the password here')
}
and export it with the request method as a key and the value is an array of objects, each with path and function keys.
module.exports = {
get: [{path:'/',func:login_screen}, {...} ],
post: [{path:'/login:forgotPassword', func:forgot_password}]
};
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
you can use of promise
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
use
console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });
or
console.log("Hello");
await sleep(2000);
console.log("World!");
Concatenation of a string and integer is simple: just use
abhishek+str(2)
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
$ yum install -y yum-utils
$ repoquery -l packagename
jQuery would be the easiest way if you want to use it, but this should work.
function showHide(){
var e = document.getElementById('e');
if ( e.style.display !== 'none' ) {
e.style.display = 'none';
} else {
e.style.display = '';
}
}
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
this helps for me:
on your build.gradle:
implementation 'com.android.support:design:28.0.0'
To write a pandas DataFrame to a CSV file, you will need DataFrame.to_csv
. This function offers many arguments with reasonable defaults that you will more often than not need to override to suit your specific use case. For example, you might want to use a different separator, change the datetime format, or drop the index when writing. to_csv
has arguments you can pass to address these requirements.
Here's a table listing some common scenarios of writing to CSV files and the corresponding arguments you can use for them.
Footnotes
- The default separator is assumed to be a comma (
','
). Don't change this unless you know you need to.- By default, the index of
df
is written as the first column. If your DataFrame does not have an index (IOW, thedf.index
is the defaultRangeIndex
), then you will want to setindex=False
when writing. To explain this in a different way, if your data DOES have an index, you can (and should) useindex=True
or just leave it out completely (as the default isTrue
).- It would be wise to set this parameter if you are writing string data so that other applications know how to read your data. This will also avoid any potential
UnicodeEncodeError
s you might encounter while saving.- Compression is recommended if you are writing large DataFrames (>100K rows) to disk as it will result in much smaller output files. OTOH, it will mean the write time will increase (and consequently, the read time since the file will need to be decompressed).
What happens in your code if $usertable
is not a valid table or doesn't include a column PartNumber or part is not a number.
You must escape $partid and also read the document for mysql_fetch_assoc() because it can return a boolean
Opening XCode and accepting the license fixes the issue.
The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:
In C++, an underscore usually indicates a private member variable.
In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.
Before:
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
After:
public string Name { get; set; }
Summarized
Adding:
android:layout_centerInParent="true"
just works on RelativeLayout, if one of the following attributes is also set for the view:
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
which alignes the child view to the parent view. The "center" is based on the axis of the alignement you have chosen:
left/right -> vertical
top/bottom -> horizontal
Setting the gravity of childs/content inside the view:
android:gravity="center"
is centering the child inside the parent view in any case, if there is no alignment set. Optional you can choose:
<!-- Axis to Center -->
android:gravity="center_horizontal"
android:gravity="center_vertical"
<!-- Alignment to set-->
android:gravity="top"
android:gravity="bottom"
android:gravity="left"
android:gravity="right"
android:gravity="fill"
...
Then there is:
android:layout_gravity="center"
which is centering the view itself inside it's parent
And at last you can add the following attribute to the parents view:
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
You can use the backtick operator:
& "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
-verb:sync `
-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"
That's still a little too long for my taste, so I'd use some well-named variables:
$msdeployPath = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
$verbArg = '-verb:sync'
$sourceArg = '-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"'
$destArg = '-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"'
& $msdeployPath $verbArg $sourceArg $destArg
The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).
The ApplicationSettings
class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.
You can fight the system with the ConfigurationManager
class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.
from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")
The directory where you will extract your files doesn't need to exist before, you name it at this moment
YOURZIP.zip is the name of the zip if your project is in the same directory. If not, use the PATH i.e : C://....//YOURZIP.zip
Think to escape the /
by an other /
in the PATH
If you have a permission denied
try to launch your ide (i.e: Anaconda) as administrator
YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project
This solution uses an Asynchronous call. It will likely work better than a synchronous solution.
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var my_JSON_object = JSON.parse(request.responseText);
console.log(my_JSON_object);
}
}
I knew how to use threads before I knew .NET, so it took some getting used to when I began using BackgroundWorker
s. Matt Davis has summarized the difference with great excellence, but I would add that it's more difficult to comprehend exactly what the code is doing, and this can make debugging harder. It's easier to think about creating and shutting down threads, IMO, than it is to think about giving work to a pool of threads.
I still can't comment other people's posts, so forgive my momentary lameness in using an answer to address piers7
Don't use Thread.Abort();
instead, signal an event and design your thread to end gracefully when signaled. Thread.Abort()
raises a ThreadAbortException
at an arbitrary point in the thread's execution, which can do all kinds of unhappy things like orphan Monitors, corrupt shared state, and so on.
http://msdn.microsoft.com/en-us/library/system.threading.thread.abort.aspx
You can't resize an array, but you can redefine it keeping old values or use a java.util.List
Here follows two solutions but catch the performance differences running the code below
Java Lists are 450 times faster but 20 times heavier in memory!
testAddByteToArray1 nanoAvg:970355051 memAvg:100000 testAddByteToList1 nanoAvg:1923106 memAvg:2026856 testAddByteToArray1 nanoAvg:919582271 memAvg:100000 testAddByteToList1 nanoAvg:1922660 memAvg:2026856 testAddByteToArray1 nanoAvg:917727475 memAvg:100000 testAddByteToList1 nanoAvg:1904896 memAvg:2026856 testAddByteToArray1 nanoAvg:918483397 memAvg:100000 testAddByteToList1 nanoAvg:1907243 memAvg:2026856
import java.util.ArrayList;
import java.util.List;
public class Test {
public static byte[] byteArray = new byte[0];
public static List<Byte> byteList = new ArrayList<>();
public static List<Double> nanoAvg = new ArrayList<>();
public static List<Double> memAvg = new ArrayList<>();
public static void addByteToArray1() {
// >>> SOLUTION ONE <<<
byte[] a = new byte[byteArray.length + 1];
System.arraycopy(byteArray, 0, a, 0, byteArray.length);
byteArray = a;
//byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
}
public static void addByteToList1() {
// >>> SOLUTION TWO <<<
byteList.add(new Byte((byte) 0));
}
public static void testAddByteToList1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToList1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteList = new ArrayList<>();
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void testAddByteToArray1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToArray1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteArray = new byte[0];
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void resetMem() {
nanoAvg = new ArrayList<>();
memAvg = new ArrayList<>();
}
public static Double getAvg(List<Double> dl) {
double max = Collections.max(dl);
double min = Collections.min(dl);
double avg = 0;
boolean found = false;
for (Double aDouble : dl) {
if (aDouble < max && aDouble > min) {
if (avg == 0) {
avg = aDouble;
} else {
avg = (avg + aDouble) / 2d;
}
found = true;
}
}
if (!found) {
return getPopularElement(dl);
}
return avg;
}
public static double getPopularElement(List<Double> a) {
int count = 1, tempCount;
double popular = a.get(0);
double temp = 0;
for (int i = 0; i < (a.size() - 1); i++) {
temp = a.get(i);
tempCount = 0;
for (int j = 1; j < a.size(); j++) {
if (temp == a.get(j))
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void testCompare() throws InterruptedException {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 20; i++) {
testAddByteToArray1();
}
System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
for (int i = 0; i < 20; i++) {
testAddByteToList1();
}
System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
}
}
private static long getMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
public static void main(String[] args) throws InterruptedException {
testCompare();
}
}
There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv
. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.
I did it by using this code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<script>
$(".confirm").on('click',function(){
window.location.href = "index.php";
});
</script>
Thanks.
return this.substr(0, index) + char + this.substr(index + char.length);
char.length
is zero. You need to add 1
in this case in order to skip character.
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:
rem The retail files set
set FILES_SET="(*.exe *.dll"
rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"
rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
rem Append the closing bracket
set FILES_SET=%FILES_SET%)
echo %FILES_SET%
Cheers...
My suggestion would be to use Unit Tests.
In your application do the following switches in Program.cs
:
#if DEBUG
public class Program
#else
class Program
#endif
and the same for static Main(string[] args)
.
Or alternatively use Friend Assemblies by adding
[assembly: InternalsVisibleTo("TestAssembly")]
to your AssemblyInfo.cs
.
Then create a unit test project and a test that looks a bit like so:
[TestClass]
public class TestApplication
{
[TestMethod]
public void TestMyArgument()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw); // this makes any Console.Writes etc go to sw
Program.Main(new[] { "argument" });
var result = sw.ToString();
Assert.AreEqual("expected", result);
}
}
}
This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.
If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
This is possible with CSS3. Just use position: sticky
, as seen here.
position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
The IFRAME
element may be a security risk if your site is embedded inside an IFRAME
on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe>
or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY
and hope that the browser knows its job.
In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe>
on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY
and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).
That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.
If somebody claims that using an <iframe>
element on your site is dangerous and causes a security risk, he does not understand what <iframe>
element does, or he is speaking about possibility of <iframe>
related vulnerabilities in browsers. Security of <iframe src="...">
tag is equal to <img src="..."
or <a href="...">
as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>
, <img>
or <a>
element, so it's not worth considering for this issue.
However, be warned that content from <iframe>
can initiate top level navigation by default. That is, content within the <iframe>
is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox
attribute without value allow-top-navigation
. For example, <iframe sandbox="allow-forms allow-scripts" ...>
. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.
Note that X-Frame-Options: DENY
also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").
You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises
or you can use this code which I am using, it also converts mouse events into touch and it works like magic.
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
And in your document.ready just call the init() function
code found from Here
Try using fake sendmail to send emails in a WAMP enviroment.
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
Should work.
Here's a working example:
Excerpt:
function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
I had the very same error message. Finally I figured out I misspelled the name of the table in the command:
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);
versus
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);
I wonder why on earth MySQL cannot tell such a table does not exist...
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
switch(handler.key){
case "ctrl+a":alert('you pressed ctrl+a!');break;
case "ctrl+b":alert('you pressed ctrl+b!');break;
case "r":alert('you pressed r!');break;
case "f":alert('you pressed f!');break;
}
});
hotkeys understands the following modifiers: ?
, shift
, option
, ?
, alt
, ctrl
, control
, command
, and ?
.
The following special keys can be used for shortcuts: backspace
, tab
, clear
, enter
, return
, esc
, escape
, space
, up
, down
, left
, right
, home
, end
, pageup
, pagedown
, del
, delete
and f1
through f19
.
If you are parsing the file after unzipping it, don't forget to use decode() method, is necessary when you open a file as binary.
import gzip
with gzip.open(file.gz, 'rb') as f:
for line in f:
print(line.decode().strip())
Mark's iterative approach would be the usual way, I think.
Here's an alternative with string-splitting, which can often be useful for finding-related processes:
def findnth(haystack, needle, n):
parts= haystack.split(needle, n+1)
if len(parts)<=n+1:
return -1
return len(haystack)-len(parts[-1])-len(needle)
And here's a quick (and somewhat dirty, in that you have to choose some chaff that can't match the needle) one-liner:
'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
Yes, add the -Force
parameter.
copy-item $from $to -Recurse -Force
You can use this method to pick image from gallery. Only images will be displayed.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
and override onActivityResult as
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap newProfilePic = extras.getParcelable("data");
}
}
}
Yes it is possible :) In fact let Internet Explorer do the dirty work for you ;)
TRIED AND TESTED
MY ASSUMPTIONS
CODE (See NOTE at the end)
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
.document.body.createtextrange.execCommand "Copy"
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
.Quit
End With
End Sub
SNAPSHOT
NOTE: Thanks to @tiQu answer below. The above code will work with new IE if you replace .document.body.createtextrange.execCommand "Copy"
with .ExecWB 17, 0: .ExecWB 12, 2
as suggested by him.
Check out Refit for making calls to REST services from .NET. I've found it very easy to use:
Refit: The automatic type-safe REST library for .NET Core, Xamarin and .NET
Refit is a library heavily inspired by Square's Retrofit library, and it turns your REST API into a live interface:
public interface IGitHubApi {
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
// The RestService class generates an implementation of IGitHubApi
// that uses HttpClient to make its calls:
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
<!DOCTYPE html>
without this tag border-radius doesn't works in IE9, no need of meta tags.
In your home folder /.android/avd//config.ini add the line hw.keyboard=yes
One more way that might be helpful - to use some kind of "alias". For example:
public enum Status
{
New = 10,
Old = 20,
Actual = 30,
// Use Status.Default to specify default status in your code.
Default = New
}
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
You can set in the config.inc.php file of your phpMyAdmin installation.
$cfg['Servers'][$i]['host'] = '';
Bit off-topic, but I use this:
template<typename T>
constexpr int sgn(const T &a, const T &b) noexcept{
return (a > b) - (a < b);
}
template<typename T>
constexpr int sgn(const T &a) noexcept{
return sgn(a, T(0));
}
and I found first function - the one with two arguments, to be much more useful from "standard" sgn(), because it is most often used in code like this:
int comp(unsigned a, unsigned b){
return sgn( int(a) - int(b) );
}
vs.
int comp(unsigned a, unsigned b){
return sgn(a, b);
}
there is no cast for unsigned types and no additional minus.
in fact i have this piece of code using sgn()
template <class T>
int comp(const T &a, const T &b){
log__("all");
if (a < b)
return -1;
if (a > b)
return +1;
return 0;
}
inline int comp(int const a, int const b){
log__("int");
return a - b;
}
inline int comp(long int const a, long int const b){
log__("long");
return sgn(a, b);
}
I know this question has been answered, but just to point out what timeit
has to say about the solutions efficiency. Using these parameters:
size = 30
s = [str(random.randint(0, 9)) for i in range(size)] + (size/3) * ['-']
random.shuffle(s)
s = ''.join(['+'] + s)
timec = 1000
That is the "phone number" has 30 digits, 1 plus sing and 10 '-'. I've tested these approaches:
def justdigits(s):
justdigitsres = ""
for char in s:
if char.isdigit():
justdigitsres += str(char)
return justdigitsres
re_compiled = re.compile(r'\D')
print('Filter: %ss' % timeit.Timer(lambda : ''.join(filter(str.isdigit, s))).timeit(timec))
print('GE: %ss' % timeit.Timer(lambda : ''.join(n for n in s if n.isdigit())).timeit(timec))
print('LC: %ss' % timeit.Timer(lambda : ''.join([n for n in s if n.isdigit()])).timeit(timec))
print('For loop: %ss' % timeit.Timer(lambda : justdigits(s)).timeit(timec))
print('RE: %ss' % timeit.Timer(lambda : re.sub(r'\D', '', s)).timeit(timec))
print('REC: %ss' % timeit.Timer(lambda : re_compiled.sub('', s)).timeit(timec))
print('Translate: %ss' % timeit.Timer(lambda : s.translate(None, '+-')).timeit(timec))
And came out with these results:
Filter: 0.0145790576935s
GE: 0.0185861587524s
LC: 0.0151798725128s
For loop: 0.0242128372192s
RE: 0.0120108127594s
REC: 0.00868797302246s
Translate: 0.00118899345398s
Apparently GEs and LCs are still slower than a regex or a compiled regex. And apparently my CPython 2.6.6 didn't optimize the string addition that much. translate
appears to be the fastest (which is expected as the problem is stated as "ignore these two symbols", rather than "get these numbers" and I believe is quite low-level).
And for size = 100
:
Filter: 0.0357120037079s
GE: 0.0465779304504s
LC: 0.0428011417389s
For loop: 0.0733139514923s
RE: 0.0213229656219s
REC: 0.0103371143341s
Translate: 0.000978946685791s
And for size = 1000
:
Filter: 0.212141036987s
GE: 0.198996067047s
LC: 0.196880102158s
For loop: 0.365696907043s
RE: 0.0880808830261s
REC: 0.086804151535s
Translate: 0.00587010383606s
Your question is a a bit vague. This is a shell command that does what I think you want to do:
echo >> name_of_file
Use noConflict()
method
ex:jQuery.noConflict()
and Use jQuery via jQuery() instead of via $()
Ex:jQuery('#id').val()
; instead of $('#id').val()
;
This is an improvement on the ".localized" approach. Start with adding the class extension as this will help with any strings you were setting programatically:
extension String {
func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
}
}
Example use for strings you set programmatically:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Now Xcode's storyboard translation files make the file manager messy and don't handle updates to the storyboard well either. A better approach is to create a new basic label class and assign it to all your storyboard labels:
class BasicLabel: UILabel {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.text
text = storyboardText?.localized()
}
}
Now every label you add and provide default default for in the storyboard will automatically get translated, assuming you've provide a translation for it.
You could do the same for UIButton:
class BasicBtn: UIButton {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.titleLabel?.text
let lclTxt = storyboardText?.localized()
setTitle(lclTxt, for: .normal)
}
}
Just grep the ID from docker images
:
docker build -t creack/node:latest .
ID="$(docker images | grep 'creak/node' | head -n 1 | awk '{print $3}')"
docker tag "$ID" creack/node:0.10.24
docker tag "$ID" creack/node:latest
Needs no temporary file and gives full build output. You still can redirect it to /dev/null
or a log file.
I stole the logging code from virtualenv for a project of mine. Look in main()
of virtualenv.py
to see how it's initialized. The code is sprinkled with logger.notify()
, logger.info()
, logger.warn()
, and the like. Which methods actually emit output is determined by whether virtualenv was invoked with -v
, -vv
, -vvv
, or -q
.
If you already have a wheel file (.whl) on your pc, then just go with the following code:
cd ../user
pip install file.whl
If you want to download a file from web, and then install it, go with the following in command line:
pip install package_name
or, if you have the url:
pip install http//websiteurl.com/filename.whl
This will for sure install the required file.
Note: I had to type pip2 instead of pip while using Python 2.
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> k = sorted(k)
>>> k
[[1, 2], [1, 2], [3], [4], [4], [5, 6, 2]]
>>> dedup = [k[i] for i in range(len(k)) if i == 0 or k[i] != k[i-1]]
>>> dedup
[[1, 2], [3], [4], [5, 6, 2]]
I don't know if it's necessarily faster, but you don't have to use to tuples and sets.
None of the above answers worked for me. Whatever I find on Internet focuses on: hide errors. None properly handles the process return-code / exit-code. I use command find within bash scripts to locate some directories and then inspect their content. I evaluate command find success using the exit-code: a value zero works, otherwise fails.
The answer provided above by Michael Brux works sometimes. But I have one scenario in which it fails! I discovered the problem and fixed it myself. I need to prune files when:
it is a directory AND has no read access AND/OR has no execute access
See the key issue here is: AND/OR. One good suggested condition sequence I read is:
-type d ! -readable ! -executable -prune
This does not work always. This means a prune is triggered when a match is:
it is directory AND no read access AND no execute access
This sequence of expressions fails when read access is granted but no execute access is.
After some testing I realized about that and changed my shell script solution to:
nice find /home*/ -maxdepth 5 -follow \
\( -type d -a ! \( -readable -a -executable \) \) -prune \
-o \
\( -type d -a -readable -a -executable -a -name "${m_find_name}" \) -print
The key here is to place the "not true" for a combined expression:
has read access AND has execute access
Otherwise it has not full access, which means: prune it. This proved to work for me in one scenario which previous suggested solutions failed.
I provide below technical details for questions in the comments section. I apologize if details are excessive.
In versions of Python after 3.7, the best answer is to use time.perf_counter_ns()
. As stated in the docs:
time.perf_counter() -> float
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
time.perf_counter_ns() -> int
Similar to perf_counter(), but return time as nanoseconds
As it says, this is going to use the best counter your system has to offer, and it is specifically designed for using in measuring performance (and therefore tries to avoid the common pitfalls of other timers).
It also gives you a nice integer number of nanoseconds, so just divide by 1000000 to get your milliseconds:
start = time.perf_counter_ns()
# do some work
duration = time.perf_counter_ns() - start
print(f"Your duration was {duration // 1000000}ms.")
There's another way with post
instead of ajax
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
echo "" > filename
I believe this works on Windows/DOS, but my last hands-on experience with either is quite a while ago. I do know for a fact that it works on basically any POSIX compliant OS.
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]