to use sendmail from the shell script
subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"
root.configure(background='black')
or more generally
<widget>.configure(background='black')
Those are two different things, as others have mentioned.
When you specify # -*- coding: utf-8 -*-
, you're telling Python the source file you've saved is utf-8
. The default for Python 2 is ASCII (for Python 3 it's utf-8
). This just affects how the interpreter reads the characters in the file.
In general, it's probably not the best idea to embed high unicode characters into your file no matter what the encoding is; you can use string unicode escapes, which work in either encoding.
When you declare a string with a u
in front, like u'This is a string'
, it tells the Python compiler that the string is Unicode, not bytes. This is handled mostly transparently by the interpreter; the most obvious difference is that you can now embed unicode characters in the string (that is, u'\u2665'
is now legal). You can use from __future__ import unicode_literals
to make it the default.
This only applies to Python 2; in Python 3 the default is Unicode, and you need to specify a b
in front (like b'These are bytes'
, to declare a sequence of bytes).
You can define this during datatable initialization
"aoColumns": [{"bVisible": false},null,null,null]
It is a function that will halt program execution if the value it has evaluated is false. Usually it is surrounded by a macro so that it is not compiled into the resultant binary when compiled with release settings.
It is designed to be used for testing the assumptions you have made. For example:
void strcpy(char* dest, char* src){
//pointers shouldn't be null
assert(dest!=null);
assert(src!=null);
//copy string
while(*dest++ = *src++);
}
The ideal you want is that you can make an error in your program, like calling a function with invalid arguments, and you hit an assert before it segfaults (or fails to work as expected)
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
With small modifications to your code, you can achieve it in a more generic way.
final Handler responseHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
//txtView.setText((String) msg.obj);
Toast.makeText(MainActivity.this,
"Result from UIHandlerThread:"+(int)msg.obj,
Toast.LENGTH_LONG)
.show();
}
};
HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
public void run(){
Integer a = 2;
Message msg = new Message();
msg.obj = a;
responseHandler.sendMessage(msg);
System.out.println(a);
}
};
handlerThread.start();
Solution :
Handler
in UI Thread,which is called as responseHandler
Handler
from Looper
of UI Thread. HandlerThread
, post message on this responseHandler
handleMessgae
shows a Toast
with value received from message. This Message object is generic and you can send different type of attributes.With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable
objects on this HandlerThread
and each Runnable
can set value in Message
object, which can be received by UI Thread.
You use mysql_real_escape_string() in code similar to the following one.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password)
);
As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:
If binary data is to be inserted, this function must be used.
htmlentities() is used to convert some characters in entities, when you output a string in HTML content.
along with answer of this link
https://stackoverflow.com/a/19844531/6767365
rename these files. I renamed my project to MvcMovie and it works fine
It is the underlying urllib3
library that does the retrying. To set a different maximum retry count, use alternative transport adapters:
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))
The max_retries
argument takes an integer or a Retry()
object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry()
instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).
Old answer, predating the release of requests 1.2.1:
The requests
library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:
import requests
requests.adapters.DEFAULT_RETRIES = 5
This constant is not documented; use it at your own peril as future releases could change how this is handled.
Update: and this did change; in version 1.2.1 the option to set the max_retries
parameter on the HTTPAdapter()
class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__()
defaults (very much not recommended).
Simplest solution. For both Radio and Checkboxes.
$('body').on('click', 'input[type="checkbox"]', function(){
if ($(this).attr('checked')){
$( this ).attr( 'checked', false);
} else {
$( this ).attr( 'checked', true);
}
});
$('body').on('click', 'input[type="radio"]', function(){
var name = $(this).attr('name');
$("input[name="+name+"]:radio").attr('checked', false);
$( this ).attr( 'checked', true);
});
So it turns out that because AnyObject is the spiritual successor to id, you can call any message you want on AnyObject. That's the equivalent of sending a message to id. Ok, fair enough. But now we add in the concept that all methods are optional on AnyObject, and we have something we can work with.
Given the above, I was hopeful I could just cast UIApplication.sharedApplication() to AnyObject, then create a variable equal to the method signature, set that variable to the optional method, then test the variable. This didn't seem to work. My guess is that when compiled against the iOS 8.0 SDK, the compiler knows where it thinks that method should be, so it optimizes this all down to a memory lookup. Everything works fine until I try to test the variable, at which point I get a EXC_BAD_ACCESS.
However, in the same WWDC talk where I found the gem about all methods being optional, they use Optional Chaining to call an optional method - and this seems to work. The lame part is that you have to actually attempt to call the method in order to know if it exists, which in the case of registering for notifications is a problem because you're trying to figure out if this method exists before you go creating a UIUserNotificationSettings object. It seems like calling that method with nil though is okay, so the solution that seems to be working for me is:
var ao: AnyObject = UIApplication.sharedApplication()
if let x:Void = ao.registerUserNotificationSettings?(nil) {
// It's iOS 8
var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
// It's older
var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
}
After much searching related to this, the key info came from this WWDC talk https://developer.apple.com/videos/wwdc/2014/#407 right in the middle at the section about "Optional Methods in Protocols"
In Xcode 6.1 beta the above code does not work anymore, the code below works:
if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
// It's iOS 8
var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
// It's older
var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
}
You can try this:
char tab[7]={'a','b','t','u','a','y','t'};
printf("%d\n",sizeof(tab)/sizeof(tab[0]));
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
Or you can use temporary array and then delete the real one if you want to change it while in cycle:
$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];
unset($array[1]);
array_unshift($array , $temp_array);
the output will be:
array(0 => 'b', 1 => 'a', 2 => 'c')
and when are doing it while in cycle, you should clean $temp_array
after appending item to array.
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
Here is one of the way in mongodb you can achieve this.
db.usercollection.find({ $where: 'this.name.length < 4' })
Can with defaulth value (T-SQL)
ALTER TABLE
Regions
ADD
HasPhotoInReadyStorage BIT NULL, --this column is nullable
HasPhotoInWorkStorage BIT NOT NULL, --this column is not nullable
HasPhotoInMaterialStorage BIT NOT NULL DEFAULT(0) --this column default value is false
GO
mongod --port portnumber --dbpath /path_to_your_folder
By default portnumber is 27017 and path is /var/lib/mongodb
You can set your own port number and path where you want to keep all your database.
To process line by line, this is an elegant solution:
def stream_lines(file_name):
file = open(file_name)
while True:
line = file.readline()
if not line:
file.close()
break
yield line
As long as there're no blank lines.
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture)
should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.
EDIT: To get the additional Z
at the end as the OP requires, use "o"
instead of "s"
.
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
In Ultra Edit and Crimson (or Emerald) Editor you can enable/disable the column mode with Alt + C
Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.
Switch to the develop branch:
$ git checkout develop
Creates feature/foo branch of develop.
$ git checkout -b feature/foo develop
merge the changes to develop without a fast-forward
$ git checkout develop
$ git merge --no-ff myFeature
Now push changes to the server
$ git push origin develop
$ git push origin feature/foo
Use @Spy
annotation
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Spy
private SomeService service = new RealServiceImpl();
@InjectMocks
private Demo demo;
/* ... */
}
Mockito will consider all fields having @Mock
or @Spy
annotation as potential candidates to be injected into the instance annotated with @InjectMocks
annotation. In the above case 'RealServiceImpl'
instance will get injected into the 'demo'
For more details refer
Try and retrieve the text property of the link button in the code behind:
protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
string val = ((LinkButton)sender).Text
}
If you have McAfee HIPS and if you see the following error in event viewer application log:
The Module DLL C:\Windows\System32\inetsrv\HipIISEngineStub.dll failed to load.
The data is the error.
Then the following resolved the issue in my case: https://kc.mcafee.com/corporate/index?page=content&id=KB72677&actp=LIST
Quote from the page:
- Click Start, Run, type explorer and click OK.
- Navigate to: %windir%\system32\inetsrv\config
- Open the file applicationHost.config as Administrator for editing in Notepad.
Edit the <globalModules> section and remove the following line:
<add name="MfeEngine" image="%windir%\System32\inetsrv\HipIISEngineStub.dll" />Edit the <modules> section and remove the following line:
<add name="MfeEngine" />- After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.
The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart
which always gives the full date and time the process started:
# ps -p 1 -wo pid,lstart,cmd
PID STARTED CMD
1 Mon Dec 23 00:31:43 2013 /sbin/init
# ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd
USER PID %CPU %MEM VSZ RSS TT STAT STARTED CMD
root 1 0.0 0.1 2800 1152 ? Ss Mon Dec 23 00:31:44 2013 /sbin/init
root 5151 0.3 0.1 4732 1980 pts/2 S Sat Mar 8 16:50:47 2014 bash
For a discussion of how the information is published in the /proc filesystem, see https://unix.stackexchange.com/questions/7870/how-to-check-how-long-a-process-has-been-running
(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:
# date; ls -ld /proc/1 /proc/$$
Sat Mar 8 17:14:21 EST 2014
dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1
dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151
Note that in this case I ran a "ps -p 1" command at about 16:50, then spawned a new bash shell, then ran the "ps -p 1 -p $$" command within that shell shortly afterward....)
The Event type input
did not work for me on <select>
but changing it to change
works
useEffect(() => {
var event = new Event('change', { bubbles: true });
selectRef.current.dispatchEvent(event); // ref to the select control
}, [props.items]);
I would vote no. Hibernate doesn't seem to understand when datatypes for columns have changed. Examples (using MySQL):
String with @Column(length=50) ==> varchar(50)
changed to
String with @Column(length=100) ==> still varchar(50), not changed to varchar(100)
@Temporal(TemporalType.TIMESTAMP,TIME,DATE) will not update the DB columns if changed
There are probably other examples as well, such as pushing the length of a String column up over 255 and seeing it convert to text, mediumtext, etc etc.
Granted, I don't think there is really a way to "convert datatypes" with without creating a new column, copying the data and blowing away the old column. But the minute your database has columns which don't reflect the current Hibernate mapping you are living very dangerously...
Flyway is a good option to deal with this problem:
I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.
Contrary to the answers in this question, my conclusion was not:
By all means use JSLint.
Or:
If you're looking for a very high standard for yourself or team, JSLint.
As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.
So the reasons to choose one over another are more political than technical.
We've finally decided to go with JSHint because of the following reasons:
We can use summary
on factor column:
summary(myDF$factorColumn)
Go to package manager console(in visual studio) and execute below command
C:\Users\<YOUR_USER>\.nuget\packages\Microsoft.EntityFrameworkCore.Tools\<YOUR_INSTALLED_VERSION>\tools\init.ps1
I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.
HTML
<ul>
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
</ul>
CSS
/* reset */
ul, li, a {
margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
display: inline-block;
text-align: center;
}
/* appearance styling */
ul {
/* hacks to make one side slant only */
overflow: hidden;
background: linear-gradient(to right, red, white, white, red);
}
li {
background-color: red;
transform:skewX(-20deg);
-ms-transform:skewX(-20deg);
-webkit-transform:skewX(-20deg);
}
li a {
padding: 3px 6px 3px 6px;
color: #ffffff;
text-decoration: none;
width: 80px;
transform:skewX(20deg);
-ms-transform:skewX(20deg);
-webkit-transform:skewX(20deg);
}
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:
$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")
You could then launch the script from the command line as per this example:
powershell.exe -noexit c:\scripts\test.ps1
Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage
command, making things easier.
Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.
Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Then, launch Outlook from the command line with the /autorun
parameter, as per this answer (alter path/macroname as necessary):
C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname
Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.
You can try this VBA program
Option Explicit
Sub CopyWorksheetsFomTemplate()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Sheet1", "Sheet2")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook", "New Copy")
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
OAuth is a protocol that is used from Resource Owner(facebook, google, tweeter, microsoft live and so on) to provide a needed information, or to provide a permission for write success to third party system(your site for example). Most likely without OAuth protocol the credentials should be available for the third part systems which will be inappropriate way of communication between those systems.
There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there.
But I would suggest to not use it. It is ugly and outdated IMO.
Simply & Easy : JavaScript code :
function JoinedOrNot(){
var cat = document.getElementById("mySelect");
if(cat.value == "yes"){
document.getElementById("mySelect1").disabled = false;
}else{
document.getElementById("mySelect1").disabled = true;
}
}
just add in this line [onChange="JoinedOrNot()"] : <select id="mySelect" onchange="JoinedOrNot()">
it's work fine ;)
This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem
package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:
\newenvironment{myitemize}
{ \begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt} }
{ \end{itemize} }
Which should be used like this:
\begin{myitemize}
\item one
\item two
\item three
\end{myitemize}
The URI "file:///android_asset/"
points to YourProject/app/src/main/assets/
.
Note: android_asset/
uses the singular (asset) and src/main/assets
uses the plural (assets).
Suppose you have a file YourProject/app/src/main/assets/web_thing.html
that you would like to display in a WebView. You can refer to it like this:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");
The snippet above could be located in your Activity class, possibly in the onCreate
method.
Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.
I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.
declare @myVal int;
set @myVal = isnull((select a from table1), 0);
Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.
Delegation is a technique where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object. This sounds at first very similar to the proxy pattern, but it serves a much different purpose. Delegation is an abstraction mechanism which centralizes object (method) behavior.
Generally spoken: use delegation as alternative to inheritance. Inheritance is a good strategy, when a close relationship exist in between parent and child object, however, inheritance couples objects very closely. Often, delegation is the more flexible way to express a relationship between classes.
This pattern is also known as "proxy chains". Several other design patterns use delegation - the State, Strategy and Visitor Patterns depend on it.
The answer from @ben almost works for me except that my dependencies are too big and I got the following error
Execution failed for task ':jar'.
> archive contains more than 65535 entries.
To build this archive, please enable the zip64 extension.
To fix this problem, I have to use the following code
mainClassName = "com.company.application.Main"
jar {
manifest {
attributes "Main-Class": "$mainClassName"
}
zip64 = true
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
Python's standard library has json
and urllib2
modules.
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:
Sub Pause()
WScript.Echo ("Press Enter to continue")
z = WScript.StdIn.ReadLine()
End Sub
More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx
If you use tf.train.MonitoredTrainingSession as the default session, you don't need to add extra code to do save/restore things. Just pass a checkpoint dir name to MonitoredTrainingSession's constructor, it will use session hooks to handle these.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.
You can call Grandpa::__construct from where you want and the $this keyword will refer to your current class instance. But be carefull with this method you cannot access to protected properties and methods of current instance from this other context, only to public elements. => All work and officialy supported.
Example
// main class that everything inherits
class Grandpa
{
public function __construct()
{
echo $this->one; // will print 1
echo $this->two; // error cannot access protected property
}
}
class Papa extends Grandpa
{
public function __construct()
{
// call Grandpa's constructor
parent::__construct();
}
}
class Kiddo extends Papa
{
public $one = 1;
protected $two = 2;
public function __construct()
{
Grandpa::__construct();
}
}
new Kiddo();
Try this:
// found on UglifyJS
variable = void 0;
For those who work with AX 2012 AIF services and try to call there C# or VB project inside AX (x++) and suffer from such errors of "could not find default endpoint"... or "no contract found" ... go back to your visual studio (c#) project and add these lines before defining your service client, then deploy the project and restart AX client and retry: Note, the example is for NetTcp adapter, you could easily use any other adapter instead according to your need.
Uri Address = new Uri("net.tcp://your-server:Port>/DynamicsAx/Services/your-port-name");
NetTcpBinding Binding = new NetTcpBinding();
EndpointAddress EndPointAddr = new EndpointAddress(Address);
SalesOrderServiceClient Client = new SalesOrderServiceClient(Binding, EndPointAddr);
Here is a complete example with output. psql (10.1, server 9.5.10).
You get 58, not some value less than 30.
Remove age() function, solved the problem that previous post mentioned.
drop table t;
create table t(
d1 date
);
insert into t values(current_date - interval '58 day');
select d1
, current_timestamp - d1::timestamp date_diff
, date_part('day', current_timestamp - d1::timestamp)
from t;
d1 | date_diff | date_part
------------+-------------------------+-----------
2018-05-21 | 58 days 21:41:07.992731 | 58
select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'
Surprisingly such conversions are solutions to many problems in MySQL.
Here's a slightly less complicated answer:
NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
You are writing to your memory stream twice, also you are not disposing the stream after use. You are also asking the image decoder to apply embedded color correction.
Try this instead:
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:
PrintStream ps = new PrintStream(baos);
ps.printf("there is a %s from %d %s", "hello", 3, "friends");
System.out.println(baos.toString());
baos.reset(); //need reset to write new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");
System.out.println(baos.toString());
baos.reset();
The string stream can be created like this ByteArrayOutputStream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
In Swift 3+:
button.contentHorizontalAlignment = .left
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
Here is a decent solution for this problem, and it does not require application restart.
https://github.com/cmaftuleac/BundleLocalization
This implementation works by tweaking inside NSBundle. The idea is that you override the method localizedStringForKey on the instance of NSBundle object, and then call this method on a different bundle with a different language. Simple and elegant fully compatible with all types of resources.
Faced the same problem as OP:
Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
It can be convenient to approach argument detection by evoking your function with an Object of optional properties:
function foo(options) {
var config = { // defaults
list: 'string value',
of: [a, b, c],
optional: {x: y},
objects: function(param){
// do stuff here
}
};
if(options !== undefined){
for (i in config) {
if (config.hasOwnProperty(i)){
if (options[i] !== undefined) { config[i] = options[i]; }
}
}
}
}
Use the PackageResourceViewer plugin installed via Package Control (as mentioned by MattDMo). This allows you to override the compressed resources by simply opening it in Sublime Text and saving the file. It automatically saves only the edited resources to %APPDATA%/Roaming/Sublime Text 3/Packages/ or ~/.config/sublime-text-3/Packages/.
Specific to the op, once the plugin is installed, execute the PackageResourceViewer: Open Resource
command. Then select JavaScript
followed by JavaScript.tmLanguage
. This will open an xml file in the editor. You can edit any of the language definitions and save the file. This will write an override copy of the JavaScript.tmLanguage file in the user directory.
The same method can be used to edit the language definition of any language in the system.
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
I had the same problem when I'm using spring-context version 4.0.6 and spring-security version 4.1.0.
When changing spring-security version to 4.0.4 (because 4.0.6 of spring-security not available) in my pom and security xml-->schemaLocation, it gets compiled without internet.
So that mean you can also solve this by:
changing spring-security to a older or same version than spring-context.
changing spring-context to a newer or same version than spring-security.
(any way spring-context to be newer or same version to spring-security)
The protection is a simple text comparison in Excel. Load Excel in your favourite debugger (Ollydbg being my tool of choice), find the code that does the comparison and fix it to always return true, this should let you access the macros.
numpy has a great tool for this task ("numpy.reshape") link to reshape documentation
a = [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
`numpy.reshape(a,(3,3))`
you can also use the "-1" trick
`a = a.reshape(-1,3)`
the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3
so yes.. this would also work:
a = a.reshape(3,-1)
and this:
a = a.reshape(-1,2)
would do nothing
and this:
a = a.reshape(-1,9)
would change the shape to (2,9)
For its base array class, 2d arrays are no more special than 1d or 3d ones. There are some operations the preserve the dimensions, some that reduce them, other combine or even expand them.
M=np.arange(9).reshape(3,3)
M[:,0].shape # (3,) selects one column, returns a 1d array
M[0,:].shape # same, one row, 1d array
M[:,[0]].shape # (3,1), index with a list (or array), returns 2d
M[:,[0,1]].shape # (3,2)
In [20]: np.dot(M[:,0].reshape(3,1),np.ones((1,3)))
Out[20]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
In [21]: np.dot(M[:,[0]],np.ones((1,3)))
Out[21]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
Other expressions that give the same array
np.dot(M[:,0][:,np.newaxis],np.ones((1,3)))
np.dot(np.atleast_2d(M[:,0]).T,np.ones((1,3)))
np.einsum('i,j',M[:,0],np.ones((3)))
M1=M[:,0]; R=np.ones((3)); np.dot(M1[:,None], R[None,:])
MATLAB started out with just 2D arrays. Newer versions allow more dimensions, but retain the lower bound of 2. But you still have to pay attention to the difference between a row matrix and column one, one with shape (1,3)
v (3,1)
. How often have you written [1,2,3].'
? I was going to write row vector
and column vector
, but with that 2d constraint, there aren't any vectors in MATLAB - at least not in the mathematical sense of vector as being 1d.
Have you looked at np.atleast_2d
(also _1d and _3d versions)?
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
One more cause for the "secret key not available" message: GPG version mismatch.
Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
Set setHasMenuOptions(true)
works if application has a theme with Actionbar
such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
Got the solution and it's working fine. Set the environment variables as:
CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59
(path where your Apache Tomcat is)JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25;
(path where your JDK is)JRE_Home=C:\Program Files\Java\jre1.8.0_25;
(path where your JRE is)CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib
We actually have some notification code in our product that uses TLS to send mail if it is available.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props)
.
ip route get 8.8.8.8| grep src| sed 's/.*src \(.* \)/\1/g'|cut -f1 -d ' '
Use combine
from moreutils
package, a sets utility that supports not
, and
, or
, xor
operations
combine file1 not file2
i.e give me lines that are in file1 but not in file2
OR give me lines in file1 minus lines in file2
Note: combine
sorts and finds unique lines in both files before performing any operation but diff
does not. So you might find differences between output of diff
and combine
.
So in effect you are saying
Find distinct lines in file1 and file2 and then give me lines in file1 minus lines in file2
In my experience, it's much faster than other options
I had a similar thing to work on, and this is how I did it.
import os
rootdir = os.getcwd()
for subdir, dirs, files in os.walk(rootdir):
for file in files:
#print os.path.join(subdir, file)
filepath = subdir + os.sep + file
if filepath.endswith(".html"):
print (filepath)
Hope this helps.
build gradle:
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
code:
interface MyCallback {
fun someMethod(value: String)
}
class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
test:
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()
val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
Your Eclipse software suite doesn't support Java 1.8
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
For a solution that worked well with third party controls like Telerik (ex.: RadComboBox) and DevExpress that use the Anchor tags for various reasons, consider using the following code, which is a slightly tweaked version of desm's code with a better selector for self targeting anchor tags:
var inFormOrLink;
$('a[href]:not([target]), a[href][target=_self]').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Try it the other way:
var start_date = $("#fit_start_time").val(); //05-09-2013
var end_date = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
var result= compareDates(start_date,format,end_date,format);
if(result==1)/// end date is less than start date
{
alert('End date should be greater than Start date');
}
OR:
if(new Date(start_date) >= new Date(end_date))
{
alert('End date should be greater than Start date');
}
If you're using .NET 3.5, you can use HashSet<T>
. It's true that .NET doesn't cater for sets as well as Java does though.
The Wintellect PowerCollections may help too.
Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.
The pure list comprehension algorithms are O(n^2), since in
on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.
#!/usr/bin/env python
''' Time list- vs set-based list intersection
See http://stackoverflow.com/q/3697432/4014959
Written by PM 2Ring 2015.10.16
'''
from __future__ import print_function, division
from timeit import Timer
setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'
cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'
cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'
reps = 3
loops = 50000
def do_timing(heading, cmd, setup):
t = Timer(cmd, setup)
r = t.repeat(reps, loops)
r.sort()
print(heading, r)
return r[0]
m = 10
nums = list(range(6 * m))
for n in range(1, m + 1):
a = nums[:6*n:2]
b = nums[:6*n:3]
print('\nn =', n, len(a), len(b))
#print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
la = do_timing('lista', cmd_lista, setup)
lb = do_timing('listb', cmd_listb, setup)
lc = do_timing('lcsa ', cmd_lcsa, setup)
sa = do_timing('seta ', cmd_seta, setup)
sb = do_timing('setb ', cmd_setb, setup)
print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)
output
n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214
n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462
n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902
n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493
n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847
n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495
n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951
n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871
n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594
n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523
Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).
These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.
I hope this answer is still useful, despite problem seems to be quite old.
If you have Anaconda installed, and your OpenCV does not support GTK+ (as in this case), you can simply type
conda install -c menpo opencv=2.4.11
It will install suitable OpenCV version that does not produce a mentioned error. Besides, it will reinstall previously installed OpenCV if there was one as a part of Anaconda.
@Aryan is correct Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)
A picture worth thousand words
This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.
Example: Suppose you defined in the REST definition
@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")
Then during the definition of the function, it should be
public ResponseEntity<List> getData(@PathVariable String appId)
This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:
public ResponseEntity<List> getData(@PathVariable String ID)
It will be better for you to write your code like this.
In your Controller Write this code.
function new_blank_order_summary() {
$query = $this->sales_model->order_summary_insert();
if($query) {
$this->load->view('sales/new_blank_order_summary');
} else {
$this->load->view('sales/data_insertion_failed');
}
}
and in your Model
function order_summary_insert() {
$orderLines = trim(xss_clean($this->input->post('orderlines')));
$customerName = trim(xss_clean($this->input->post('customer')));
$data = array(
'OrderLines'=>$orderLines,
'CustomerName'=>$customerName
);
$this->db->insert('Customer_Orders',$data);
return ($this->db->affected_rows() != 1) ? false : true;
}
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
You have to change the values in the CATALINA_OPTS option defined in the Tomcat Catalina start file. To increase the PermGen
memory change the value of the MaxPermSize
variable, otherwise change the value of the Xmx
variable.
Linux & Mac OS: Open or create setenv.sh
file placed in the "bin" directory. You have to apply the changes to this line:
export CATALINA_OPTS="$CATALINA_OPTS -server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"
Windows:
Open or create the setenv.bat
file placed in the "bin" directory:
set CATALINA_OPTS=-server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
class Test(object):
def _decorator(self, foo):
foo()
def bar(self):
pass
bar = self._decorator(bar)
It, of course, isn't valid since self
isn't defined at that point. The same goes for Test
as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into.
So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.
If you need class-level access, try this:
class Test(object):
@classmethod
def _decorator(cls, foo):
foo()
def bar(self):
pass
Test.bar = Test._decorator(Test.bar)
Subversion implicitly has the remote repository associated with it at all times. Git, on the other hand, allows many "remotes", each of which represents a single remote place you can push to or pull from.
You need to add a remote for the GitHub repository to your local repository, then use git push ${remote}
or git pull ${remote}
to push and pull respectively - or the GUI equivalents.
Pro Git discusses remotes here: http://git-scm.com/book/ch2-5.html
The GitHub help also discusses them in a more "task-focused" way here: http://help.github.com/remotes/
Once you have associated the two you will be able to push or pull branches.
You can probably use
new Date().setUTCHours(0,0,0,0)
if you need the value only once.
var response = taskwithresponse.Result;
var jsonString = response.ReadAsAsync<List<Job>>().Result;
I'am replying to a 3 year old link but I guess here's a more acceptable answer,
Create .css file as,
@media screen and (max-width: 1000px)
{
// things you want to trigger when the screen is zoomed
}
EG:-
@media screen and (max-width: 1000px)
{
.classname
{
font-size:10px;
}
}
The above code makes the size of the font '10px' when the screen is zoomed to approximately 125%. You can check for different zoom level by changing the value of '1000px'.
You need to specify workseet. Change line
If Worksheet.Cells(i, 1).Value = "X" Then
to
If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then
UPD:
Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):
Sub LastRowInOneColumn()
Dim LastRow As Long
Dim i As Long, j As Long
'Find the last used row in a Column: column A in this example
With Worksheets("Sheet2")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox (LastRow)
'first row number where you need to paste values in Sheet1'
With Worksheets("Sheet1")
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
For i = 1 To LastRow
With Worksheets("Sheet2")
If .Cells(i, 1).Value = "X" Then
.Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
j = j + 1
End If
End With
Next i
End Sub
sub last_filled_cell()
msgbox range("A65536").end(xlup).row
end sub
Here, A65536 is the last cell in the Column A this code was tested on excel 2003.
Use this easy method
$a='Link1';
$b='Link2';
echo "<a href=\"pass.php?link=$a\">Link 1</a>";
echo '<br/>';
echo "<a href=\"pass.php?link=$b\">Link 2</a>";
You can try with SqlBulkCopy
class.
Lets you efficiently bulk load a SQL Server table with data from another source.
There is a cool blog post about how you can use it.
While this is an old post, it is something that helped me solve the issue. So to keep others stumbling upon this to find a solution using the current Angular2 stack (2.0.0-rc.4 at this time), I downgraded my jQuery version to 2.2.4, added the bootstrap.js distributed under node_modules/bootstrap/dist/js to my InjectableDependencies (using gulp, and defining this in the project.config.ts file) and everything continues to work just fine.
Basically here we are dealing with communication between Fragments. Communication between fragments can never be directly possible. It involves activity under the context of which both the fragments are created.
You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.
This is how i registered my domain:
sudo letsencrypt --apache -d mydomain.com
Then it was possible to use the same command with additional domains and follow the instructions:
sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com
You can use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
But I don't know whether it should be considered more right than to use Calendar ...
buttion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
compile 'com.android.support:appcompat-v7:23.1.0'
}
For Windows Vista and Windows 7 you need to get the Remote Server Administration Tools (RSAT) - the Active Directory Users & Computers Snap-In is included in that pack. Download link: Remote Server Administration Tools for Windows 7.
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the
approval_prompt
parameter in the authorization code request, and set the value toforce
.
So, when you have already granted access, subsequent requests for a grant_type
of authorization_code
will not return the refresh_token
, even if access_type
was set to offline
in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token
after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt
to force
.
Cheers,
PS This change was announced in a blog post as well.
You can use an event listener to close the clip after it is played
import java.io.File;
import javax.sound.sampled.*;
public void play(File file)
{
try
{
final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
clip.addLineListener(new LineListener()
{
@Override
public void update(LineEvent event)
{
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}
So a recent question prompted me to notice a selector set hack for excluding IE 8 only.
.selector, #excludeIE8::before {}
will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the ::
selectors (::first-line, ::before, ::first-letter, ::selection
) will work, I've merely chosen ::before
so the line reads accurately. Note that the goal of the fake ::before
selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8
Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad ::
selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before
. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement
... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.
However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending \9
(the space is key; do NOT copypaste that inline as it uses an nbsp):
/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;
/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;
Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.
You can simply use target="_blank"
to open a page in a new tab
<a href="whatever.php" target="_blank">Opens On Another Tab</a>
Or you can simply use a javascript for onload
<body onload="window.open(url, '_blank');">
Remove the textnode, and replace the <b>
tag with whatever you need without ever touching the inputs :
$('#demoTable').find('tr > td').contents().filter(function() {
return this.nodeType===3;
}).remove().end().end()
.find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));
In my case, the view was not viewed in xib. in xib the View was size = none (4th tab right hand). I set size to Freeform and reload xCode. view was appealed and I set the proper link to View.
Per @Beau's answer, Chrome does not support localhost CORS requests, and there is unlikely any change in this direction.
I use the Allow-Control-Allow-Origin: * Chrome Extension to go around this issue. The extension will add the necessary HTTP Headers for CORS:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: "GET, PUT, POST, DELETE, HEAD, OPTIONS"
Access-Control-Expose-Headers: <you can add values here>
The source code is published on Github.
Note that the extension filter all URLs by default. This may break some websites (for example: Dropbox). I have changed it to filter only localhost URLs with the following URL filter
*://localhost:*/*
strtok()
is a bad ideaDo not use strtok()
in normal code, strtok()
uses static
variables which have some problems. There are some use cases on embedded microcontrollers where static
variables make sense but avoid them in most other cases. strtok()
behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok()
.
Consider this example:
#include <stdio.h>
#include <string.h>
//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
char *p = strtok(input, "/");
while(p)
{
printf("%s, ",p);
p = strtok(NULL, "/");
}
}
int main(void)
{
char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
char *p = strtok(buffer, ":");
while(p)
{
printContent(p);
puts(""); //print newline
p = strtok(NULL, ":");
}
return 0;
}
You may expect the output:
abc, def, ghi,
ABC, DEF, GHI,
But you will get
abc, def, ghi,
This is because you call strtok()
in printContent()
resting the internal state of strtok()
generated in main()
. After returning, the content of strtok()
is empty and the next call to strtok()
returns NULL
.
You could use strtok_r()
when you use a POSIX system, this versions does not need static
variables. If your library does not provide strtok_r()
you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
<div id="calendar"></div>
<script>
$(document).ready(function() {
var days = [];
$('#calendar').datepicker({
dateFormat: 'yymmdd',
showWeek: true, showOtherMonths: false, selectOtherMonths: false,
navigationAsDateFormat: true, prevText: 'MM', nextText: 'MM',
onSelect: function(d) {
var i = $.inArray(d, days);
if (i == -1)
days.push(d);
else
days.splice(i, 1);
},
beforeShowDay: function(d) {
return ([true, $.inArray($.datepicker.formatDate('yymmdd', d), days) == -1 ? 'ui-state-free' : 'ui-state-busy']);
}
});
});
</script>
NOTE: You can prefill days
with a list of dates like '20190101'
with a piece of code in PHP.
Add 2 lines to your CSS:
#calendar .ui-state-busy a {background:#e6e6e6 !important;}
#calendar .ui-state-free a {background:none !important;}
To get the list of days selected by the calendar in a <form>
:
<div id="calendar"></div>
<form method="post">
<input type="submit" name="calendar_get" id="calendar_get" value="Validate" />
</form>
Add this to the <script>
:
$('#calendar_get').click(function() {
$(this).append('<input type="hidden" name="calendar_days" value="' + days.join(',') + '" />');
});
Apply implode
on the string in $_POST['calendar_days']
and map strtotime
to all the formatted dates.
Here you go:
>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split() # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>>
Rather than sending as just an object .
Create a public class of properties that is accessible and send the data to the Webmethod.
[WebMethod]
public static void SaveTeam(useSomeClassHere user)
{
}
use same parameters names in ajax call to send data.
x[r,]
where r is the row you're interested in. Try this, for example:
#Add your data
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5 ),
B = c(4.25, 4, 4, 4.5, 4.5 ),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)
#Test that the items in the row match the vector you wanted
x[1,]==y
This page (from this useful site) has good information on indexing like this.
Core java is a sun term.It mentions the USE,it means it contains only basics of java and some principles and also contain some packages details.
It sounds like you need to make use of advanced where clauses.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
Try this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
There are few mistakes you are doing:
addRow
methodsplice
method to remove an element from an array at particular index.my-item
component, where this can be modified.You can see working code here.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
_WIN32 identifier is not defined.
use #include <SDKDDKVer.h>
MSVS generated projects wrap this include by generating a local "targetver.h"
which is included by "stdafx.h"
that is comiled into a precompiled-header through "stdafx.cpp"
.
EDIT : do you have a /D "WIN32" on your commandline ?
This worked for me Angular cli 6.x:
import {Router} from '@angular/router';
constructor(private artistService: ArtistService, private router: Router) { }
selectRow(id: number): void{
this.router.navigate([`./artist-detail/${id}`]);
}
If you're using IDLE, you can use Ctrl+]
to indent and Ctrl+[
to unindent.
if(navigator.app){
navigator.app.exitApp();
}else if(navigator.device){
navigator.device.exitApp();
}
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
You can have all the different styles to datetime conversion
:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
This has range of values :-
CONVERT(data_type(length),expression,style)
For style values,
Choose anyone you need like I needed 106.
Here's one way. The inner query gets the max date for each id. Then you can join that back to your main table to get the rows that match.
select
*
from
<your table>
inner join
(select id, max(<date col> as max_date) m
where yourtable.id = m.id
and yourtable.datecolumn = m.max_date)
Here is example how to remove NULL characters using ex
(in-place):
ex -s +"%s/\%x00//g" -cwq nulls.txt
and for multiple files:
ex -s +'bufdo!%s/\%x00//g' -cxa *.txt
For recursivity, you may use globbing option **/*.txt
(if it is supported by your shell).
Useful for scripting since sed
and its -i
parameter is a non-standard BSD extension.
See also: How to check if the file is a binary file and read all the files which are not?
Try this:
select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime
If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
This can be a browser behavior not jQuery plugin issue. Have you tried removing the focus programmatically after you open the popup.
$('#lnkAddReservation').click(function () {
dlg.dialog('open');
// you may want to change the selector below
$('input,textarea,select').blur();
return false;
});
Haven't tested that but should work ok.
They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.
Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.
Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
You can download the source from here(Display PDF file inside my android application)
Add this dependency in your gradle file:
compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark"
android:text="View PDF"
android:textColor="#ffffff"
android:id="@+id/tv_header"
android:textSize="18dp"
android:gravity="center"></TextView>
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_below="@+id/tv_header"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java
package pdfviewer.pdfviewer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;
public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView= (PDFView)findViewById(R.id.pdfView);
displayFromAsset(SAMPLE_FILE);
}
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
}
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
Valgrind is a nice option for Linux. Under MacOS X, you can enable the MallocDebug library which has several options for debugging memory allocation problems (see the malloc manpage, the "ENVIRONMENT" section has the relevant details). The OS X SDK also includes a tool called MallocDebug (usually installed in /Developer/Applications/Performance Tools/) that can help you to monitor usage and leaks.
If you are OK with using ES6 syntax, I find that the cleanest way to do this, as noted here and here is:
const data = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const { item2, ...newData } = data;
Now, newData
contains:
{
item1: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
Or, if you have the key stored as a string:
const key = 'item2';
const { [key]: _, ...newData } = data;
In the latter case, [key]
is converted to item2
but since you are using a const
assignment, you need to specify a name for the assignment. _
represents a throw away value.
More generally:
const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...
Not only does this reduce your operation to a one-liner but it also doesn't require you to know what the other keys are (those that you want to preserve).
A simple utility function would look like this:
function removePropFromObject(obj, prop) {
const { [prop]: _, ...rest } = obj
return { ...rest }
}
If you're running a recent-ish version of pandas then you can use the datetime attribute dt
to access the datetime components:
In [6]:
df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
EDIT
It looks like you're running an older version of pandas in which case the following would work:
In [18]:
df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
Regarding why it didn't parse this into a datetime in read_csv
you need to pass the ordinal position of your column ([0]
) because when True
it tries to parse columns [1,2,3]
see the docs
In [20]:
t="""date Count
6/30/2010 525
7/30/2010 136
8/31/2010 125
9/30/2010 84
10/29/2010 4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date 5 non-null datetime64[ns]
Count 5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes
So if you pass param parse_dates=[0]
to read_csv
there shouldn't be any need to call to_datetime
on the 'date' column after loading.
The following seems to work for me (on desktop, windows):
var openFile = function (mimeType, fileExtension) {
var defer = $q.defer();
var uploadInput = document.createElement("input");
uploadInput.type = 'file';
uploadInput.accept = '.' + fileExtension + ',' + mimeType;
var hasActivated = false;
var hasChangedBeenCalled = false;
var hasFocusBeenCalled = false;
var focusCallback = function () {
if (hasActivated) {
hasFocusBeenCalled = true;
document.removeEventListener('focus', focusCallback, true);
setTimeout(function () {
if (!hasChangedBeenCalled) {
uploadInput.removeEventListener('change', changedCallback, true);
defer.resolve(null);
}
}, 300);
}
};
var changedCallback = function () {
uploadInput.removeEventListener('change', changedCallback, true);
if (!hasFocusBeenCalled) {
document.removeEventListener('focus', focusCallback, true);
}
hasChangedBeenCalled = true;
if (uploadInput.files.length === 1) {
//File picked
var reader = new FileReader();
reader.onload = function (e) {
defer.resolve(e.target.result);
};
reader.readAsText(uploadInput.files[0]);
}
else {
defer.resolve(null);
}
};
document.addEventListener('focus', focusCallback, true); //Detect cancel
uploadInput.addEventListener('change', changedCallback, true); //Detect when a file is picked
uploadInput.click();
hasActivated = true;
return defer.promise;
}
This does use angularjs $q but you should be able to replace it with any other promise framework if needed.
Tested on IE11, Edge, Chrome, Firefox, but it does not seem to work on Chrome on a Android Tablet as it does not fire the Focus event.
Put it all in one document and use this:
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px)
only screen and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px)
only screen and (-webkit-device-pixel-ratio: 3) {
/*** You've spent way too much on a phone ***/
}
/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
/* Styles */
}
Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
At this point, I would definitely consider using em
values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
System.Reflection.Assembly.GetAssembly(type).Location
IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO
namespace to get the exact path of the file.
In my case, Environment.NewLine was working fine while previewing the report in Visual Studio. But when I tried to publish the rdl to Dynamics 365 CE, I received the error "The report server has RDLSandboxing enabled and the Value expression for the text box 'Textbox10' contains a reference to a type, namespace, or member 'Environment' that is not allowed."
So I had to replace Environment.NewLine with vbcrlf.
I tried the suggested solutions by everyone, but I had to improvise code myself to actually make it work. Following is my improvised code:
import signal
import sys
import time
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
print(signal) # Value is 2 for CTRL + C
print(frame) # Where your execution of program is at moment - the Line Number
sys.exit(0)
#Assign Handler Function
signal.signal(signal.SIGINT, signal_handler)
# Simple Time Loop of 5 Seconds
secondsCount = 5
print('Press Ctrl+C in next '+str(secondsCount))
timeLoopRun = True
while timeLoopRun:
time.sleep(1)
if secondsCount < 1:
timeLoopRun = False
print('Closing in '+ str(secondsCount)+ ' seconds')
secondsCount = secondsCount - 1
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client
executes Proxy.method()
.
(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)
Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function
and std::bind
:
#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
cout << "Handler added..." << endl;
// Let's pretend an event just occured
callback(1);
}
};
The addHandler
method now accepts a std::function
argument, and this "function object" have no return value and takes an integer as argument.
To bind it to a specific function, you use std::bind
:
class MyClass
{
public:
MyClass();
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};
MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`
private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}
You need to use std::bind
when adding the handler, as you explicitly needs to specify the otherwise implicit this
pointer as an argument. If you have a free-standing function, you don't have to use std::bind
:
void freeStandingCallback(int x)
{
// ...
}
int main()
{
// ...
handler->addHandler(freeStandingCallback);
}
Having the event handler use std::function
objects, also makes it possible to use the new C++11 lambda functions:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
Unfortunately I cant automate setting it to developer mode because of restrictions in width using the browser in iphone mode. I have found a dangerous workaround for now, install the dev channel version of chrome. It does not have the warning message, but im sure it will cause me more problems in the long run when problems are introduced. Still will hopefully give me a few days to find a workaround.
Follow this, it can be like what you are looking:
var obj = {_x000D_
Objone: 'one',_x000D_
Objtwo: 'two'_x000D_
};_x000D_
_x000D_
var key = "Objone";_x000D_
delete obj[key];_x000D_
console.log(obj); // prints { "objtwo": two}
_x000D_
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Using a script like that, you'd POST the contents of your web form to the script, using a function like this:
And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "="
in the scope. Here's three solutions depending on your situation.
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use $observe
or $watch
:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// observe changes in attribute - could also be scope.$watch
attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
scope.variable = value;
}
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// observe changes in attribute - could also be scope.$watch
$attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
$scope.variable = value;
}
});
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Note that you should not set the variable to "="
in the scope, if you are using the $observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout
to wait until the $apply
has run. Also we need to use $emit
to send it to the parent scope app controller (due to the isolated scope in the directive):
app.directive('yourDirective', ['$timeout', function ($timeout) {
return {
restrict: 'A',
// NB: isolated scope!!
scope: {
yourDirective: '='
},
link: function (scope, element, attrs) {
// wait until after $apply
$timeout(function(){
console.log(scope.yourDirective);
// use scope.$emit to pass it to controller
scope.$emit('notification', scope.yourDirective);
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: [ '$scope', function ($scope) {
// wait until after $apply
$timeout(function(){
console.log($scope.yourDirective);
// use $scope.$emit to pass it to controller
$scope.$emit('notification', scope.yourDirective);
});
}]
};
}])
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$on('notification', function (evt, value) {
console.log(value);
$scope.variable = value;
});
}]);
And here's the html (no brackets!):
<div ng-controller="MyCtrl">
<div your-directive="someObject.someVariable"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
If your variable is not changing and you need to evaluate it in your directive, you can use the $eval
function:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval(attrs.yourDirective);
console.log(scope.variable);
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval($attrs.yourDirective);
console.log($scope.variable);
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
Spent a great deal of time troubleshooting this issue myself.
Using PHP, and Nothing on this page worked for me. I eventually realized in my code that the 'secure' parameter to PHP's session_set_cookie_params() was always being set to TRUE.
Since I wasn't visiting localhost with https my browser would never accept the cookie. So, I modified that portion of my code to conditionally set the 'secure' param based on $_SERVER['HTTP_HOST'] being 'localhost' or not. Working well now.
I hope this helps someone.
I'm working on Oracle 12c 12.1. However, doesn't seem like it allows more than 30 characters for column/table names.
Read through an oracle page which mentions 30 bytes. https://docs.oracle.com/database/121/SQLRF/sql_elements008.htm#SQLRF00223
In 12c although the all_tab_columns do say VARCHAR2(128) for Table_Name, it does not allow more than 30 bytes name.
Found another article about 12c R2, which seems to be allowing this up to 128 characters. https://community.oracle.com/ideas/3338
This will direct everything from the old host to the root of the new host:
RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]
Here is the best Object to Array function I have - works recursively:
function object_to_array($obj, &$arr){
if(!is_object($obj) && !is_array($obj)){
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
object_to_array_v2($value, $arr[$key]);
}
else
{
$arr[$key] = $value;
}
}
return $arr;
}
$clean_array = object_to_array($object_data_here);
The proper solution is to set environment variable R_LIBS_USER
to the value of the file path to your desired library folder as opposed to getting RStudio to recognize a Rprofile.site file.
To set environment variable R_LIBS_USER
in Windows, go to the Control Panel (System Properties -> Advanced system properties -> Environment Variables -> User Variables) to a desired value (the path to your library folder), e.g.
Variable name: R_LIBS_USER
Variable value: C:/software/Rpackages
If for some reason you do not have access to the control panel, you can try running rundll32 sysdm.cpl,EditEnvironmentVariables
from the command line on Windows and add the environment variable from there.
Setting R_LIBS_USER will ensure that the library shows up first in .libPaths() regardless of starting RStudio directly or by right-clicking an file and "Open With" to start RStudio.
The Rprofile solution can work if RStudio is always started by clicking the RStudio shortcut. In this case, setting the default working directory to the directory that houses your Rprofile will be sufficient. The Rprofile solution does not work when clicking on a file to start RStudio because that changes the working directory away from the default working directory.
What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.jsonwebpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.
Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.
I always get confused with this, so here is a reminder test case; let's say we have this bash
script to test git
:
set -x
rm -rf test
mkdir test
cd test
git init
git config user.name test
git config user.email [email protected]
echo 1 > a.txt
echo 1 > b.txt
git add *
git commit -m "initial commit"
echo 2 >> b.txt
git add b.txt
git commit -m "second commit"
echo 3 >> b.txt
At this point, the change is not staged in the cache, so git status
is:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
If from this point, we do git checkout
, the result is this:
$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean
If instead we do git reset
, the result is:
$ git reset HEAD -- b.txt
Unstaged changes after reset:
M b.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
So, in this case - if the changes are not staged, git reset
makes no difference, while git checkout
overwrites the changes.
Now, let's say that the last change from the script above is staged/cached, that is to say we also did git add b.txt
at the end.
In this case, git status
at this point is:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: b.txt
If from this point, we do git checkout
, the result is this:
$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean
If instead we do git reset
, the result is:
$ git reset HEAD -- b.txt
Unstaged changes after reset:
M b.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: b.txt
no changes added to commit (use "git add" and/or "git commit -a")
So, in this case - if the changes are staged, git reset
will basically make staged changes into unstaged changes - while git checkout
will overwrite the changes completely.
FWIW with Ansible 2.2 one can use include_role:
playbook test.yml
:
- name: test
hosts:
- 127.0.0.1
connection: local
tasks:
- include_role:
name: test
tasks_from: other
then in roles/test/tasks/other.yml
:
- name: say something else
shell: echo "I'm the other guy"
And invoke the playbook with: ansible-playbook test.yml
to get:
TASK [test : say something else] *************
changed: [127.0.0.1]
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
To check the class in Swift, use "is" (as explained under "checking Type" in the chapter called Type Casting in the Swift Programming Guide)
if self.window.rootViewController is MyViewController {
//do something if it's an instance of that class
}
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
Just as an alternative to the '[ -d ]' and '[ -h ]' options, you can make use of stat
to obtain the file type and parse it.
#! /bin/bash
MY_DIR=$1
NODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)
case "${NODE_TYPE}" in
"directory") echo $MY_DIR;;
"symbolic link") echo $(readlink $MY_DIR);;
"") echo "$MY_DIR does not exist";;
*) echo "$NODE_TYPE is unsupported";;
esac
exit 0
Test data:
$ mkdir tmp
$ ln -s tmp derp
$ touch a.txt
$ ./dir.sh tmp
tmp
$ ./dir.sh derp
tmp
$ ./dir.sh a.txt
regular file is unsupported
$ ./dir.sh god
god does not exist
On Ubuntu 14 and Mysql 5.5.53 this setting seems to be enabled by default. To disable it you need to add secure-file-priv = ""
to your my.cnf file under the mysqld config group. eg:-
[mysqld]
secure-file-priv = ""
A variation on the answer by @tallgirltaadaa , draw your own button in the shape of a caret:
var a = $('.MyCarouselContainer').slick({
prevArrow: '<canvas class="prevArrowCanvas a-left control-c prev slick-prev" width="15" height="50"></canvas>',
nextArrow: '<canvas class="nextArrowCanvas a-right control-c next slick-next" width="15" height="50"></canvas>'
});
function drawNextPreviousArrows(strokeColor) {
var c = $(".prevArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(15, 0);
ctx.lineTo(0, 25);
ctx.lineTo(15, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
var c = $(".nextArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(0, 0);
ctx.lineTo(15, 25);
ctx.lineTo(0, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
}
drawNextPreviousArrows("#cccccc");
then add the css
.slick-prev, .slick-next
height: 50px;s
}
To list installed Python packages, you can use yolk -l
. You'll need to use easy_install yolk
first though.
My problem was with adding the
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
inside a
<!-- build:css assets/styles/main.css -->
<!-- endbuild -->
tag
I fixed it by placing it outside the tag.
Assuming you mean "list" where you say "array", you can do
if item in my_list:
# whatever
This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.
better tr command:
tr [:blank:] \\t
This will clean up the output of say, unzip -l , for further processing with grep, cut, etc.
e.g.,
unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
The problem seems to be that you expect plt.show()
to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.
To resolve that problem just call plt.show()
once after your loop. Then you get the complete plot. (But not a 'real-time plotting')
You can try setting the keyword-argument block
like this: plt.show(block=False)
once at the beginning and then use .draw()
to update.
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
You can set the background color of an object using CSS.
You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';
. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.
body {_x000D_
background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable
instance you create will internally be wrapped and executed as a thread.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
threadExecutor.execute(
new Runnable() {
@Override
public void run() {
System.out.println("blah");
}
}
);
} finally {
threadExecutor.shutdownNow();
}
For convenience, see the code on JDoodle.
Don't forget to set the delegate for the textView - otherwise resignfirstresponder won't work.
Try this
String[] arr = list.toArray(new String[list.size()]);
Your solution is nearly correct. You could add DISTINCT:
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
Here are the steps solved for me:
Done !
You could try a subquery:
SELECT DISTINCT TEST.* FROM (
SELECT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.
Here's the code I came up with to remove items selected by a user from a listbox It seems to work ok in a multiselect listbox (selectionmode prop is set to multiextended).:
Private Sub cmdRemoveList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemoveList.Click
Dim knt As Integer = lstwhatever.SelectedIndices.Count
Dim i As Integer
For i = 0 To knt - 1
lstwhatever.Items.RemoveAt(lstwhatever.SelectedIndex)
Next
End Sub