Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content.
You can pass $event
with ng-click (ng-dblclick, and ng- mouse events), then you can determine which element caused the event:
<a ng-click="doSomething($event)">do something</a>
Controller:
$scope.doSomething = function(ev) {
var element = ev.srcElement ? ev.srcElement : ev.target;
console.log(element, angular.element(element))
...
}
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
steps 1 in the user variable and system variable
C:\Program Files\nodejs
then check both node -v
and the npm -v
then try to update the the npm i -g npm
writing data in tables declared declare @tb
and after joining with other tables, I realized that the response time compared to temporary tables tempdb .. # tb
is much higher.
When I join them with @tb the time is much longer to return the result, unlike #tm, the return is almost instantaneous.
I did tests with a 10,000 rows join and join with 5 other tables
What about
ls {*.py,*.html}
It lists out all the files ending with .py or .html in their filenames
I don't think "Ruby has X and Python doesn't, while Python has Y and Ruby doesn't" is the most useful way to look at it. They're quite similar languages, with many shared abilities.
To a large degree, the difference is what the language makes elegant and readable. To use an example you brought up, both do theoretically have lambdas, but Python programmers tend to avoid them, and constructs made using them do not look anywhere near as readable or idiomatic as in Ruby. So in Python, a good programmer will want to take a different route to solving the problem than he would in Ruby, just because it actually is the better way to do it.
The Comments of @crates work for me,
Step 1: Simply press on ctrl+H
Step 2: press on RegEX key
Step 3: write this in the Find: ^[\s]*?[\n\r]+
Step 4: replace all
=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)
yyww as the given week exp:week 51 year 2014 will be 1451
Move DropDownList1.Items.Add(new ListItem("Select", "0", true)); After bindStatusDropDownList();
so:
if (!IsPostBack)
{
bindStatusDropDownList(); //first create structure
DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
}
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
On macOS, one option is to install FUSE for macOS and use sshfs
to mount a remote directory:
mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir
Some caveats apply with mounting network volumes, so YMMV.
You can try this: CovenantSQL/GNTE just write YAML like this:
group:
-
name: china
nodes:
-
ip: 10.250.1.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.1.3
cmd: "cd /scripts && ./YourBin args"
delay: "100ms 10ms 30%"
loss: "1% 10%"
-
name: us
nodes:
-
ip: 10.250.2.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.2.3
cmd: "cd /scripts && ./YourBin args"
delay: "1000ms 10ms 30%"
loss: "1% 10%"
network:
-
groups:
- china
- us
delay: "200ms 10ms 1%"
corrupt: "0.2%"
rate: "10mbit"
run ./generate scripts/your.yaml
Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:
exestub.sh:
#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
case $1 in
-Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
-D*) JAVA_OPT="$JAVA_OPT $1" ;;
*) PROG_OPT="$PROG_OPT $1" ;;
esac
shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT
Then you create your runnable file from your jar:
$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable
It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>
, as <myexe>
is a valid zip/jar file.
Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.
remote: error: GH003: Sorry, force-pushing to master is not allowed.
If you get an error message like this one please try the following steps.
To effectively reset your fork you need to follow these steps :
git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin
Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :
git checkout master
git push --force origin
Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :
git push origin --delete tmp_master
git branch -D tmp_master
Other answers warning about lossing your change still apply, be carreful.
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
CSS:
.blue-icon{
color:blue !important;
}
HTML
<i class="fa fa-wrench blue-icon"></i>
Glyphicons are removed in 4.0, i recommend Font-awesome 4 or newer :)
Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname
to display the commit it points to.
In your case you have at least these two alternatives:
Reset the current branch to specific tag:
git reset --hard tagname
Generate revert commit on top to get you to the state of the tag:
git revert tag
This might introduce some conflicts if you have merge commits though.
I fixed this error on Android by making the project I was importing a library, as described here http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject
Previously, I was just referencing the project (not making it a library) and I was getting this strange VerifyError.
Hope it helps someone.
push is a native javascript method. You could use it like this:
var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]
SELECT
convert(numeric(18,5),Col1), Col2
FROM DBname.dbo.TableName
WHERE isnumeric(isnull(Col1,1)) <> 0
I wanted to open the Bluetooth Menu in the Settings Application and the above path (prefs:root=General&path=Bluetooth) didn't work for me. What ended up working for me was
UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=Bluetooth")!)
Make sure you have the prefs
URL Scheme defined first.
Well a really base-level method to use could go through every pixel colour and compare it with the corresponding pixel colour on the second image - but that's a probably a very very slow solution.
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
try this ,hope it helps
select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
CASE
WHEN invitee_status=1 THEN "attending"
WHEN invitee_status=2 THEN "unsure"
WHEN invitee_status=3 THEN "declined"
WHEN invitee_status=0 THEN "notreviwed" END
) AS invitee_status
FROM your_tbl
facing same error while add repository to git hun using git bash on windows
git remote add origin https://github.com/axaysushir/netflix_page_clone.git
fatal: remote origin already exists.
fatal: remote origin already exists.
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/axaysushir/meditation_app_using_js.git'
Update repository by following command
$ git remote set-url origin https://github.com/axaysushir/netflix_page_clone.git
then add repository using git remote add github instead git remote add origin
$ git remote add github https://github.com/axaysushir/netflix_page_clone.git
And then write following command instead of git push origin master this will upload your repository to github
$ git push github master
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
Be careful when you take the exception object or the traceback object out of the exception handler, since this causes circular references and gc.collect()
will fail to collect. This appears to be of a particular problem in the ipython/jupyter notebook environment where the traceback object doesn't get cleared at the right time and even an explicit call to gc.collect()
in finally
section does nothing. And that's a huge problem if you have some huge objects that don't get their memory reclaimed because of that (e.g. CUDA out of memory exceptions that w/o this solution require a complete kernel restart to recover).
In general if you want to save the traceback object, you need to clear it from references to locals()
, like so:
import sys, traceback, gc
type, val, tb = None, None, None
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
# some cleanup code
gc.collect()
# and then use the tb:
if tb:
raise type(val).with_traceback(tb)
In the case of jupyter notebook, you have to do that at the very least inside the exception handler:
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
raise type(val).with_traceback(tb)
finally:
# cleanup code in here
gc.collect()
Tested with python 3.7.
p.s. the problem with ipython or jupyter notebook env is that it has %tb
magic which saves the traceback and makes it available at any point later. And as a result any locals()
in all frames participating in the traceback will not be freed until the notebook exits or another exception will overwrite the previously stored backtrace. This is very problematic. It should not store the traceback w/o cleaning its frames. Fix submitted here.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
This will also give external links an absolute path without having to use php.ini
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>
In my case, there was no code change at all and suddenly one of the servers started getting this and only this exception (all servers have the same code, but only one started having issues):
System.MissingMethodException: Method not found: '?'.
Stack:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.searchtPhone(String ID, String HashID, searchtPhone Phone1)
at WS.MyValidation(String AccountNumber, String PhoneNumber)
The issue I believe was corrupted AppPool - we have automated AppPool recycling going on every day at 3 am and the issue started at 3 am and then ended on its own at 3 am the next day.
Sounds like log4j picks up another configuration file than the one you think it does.
Put a breakpoint in log4j where the file is opened and have a look at the files getAbsolutePath().
memset(msg, 0, 65546)
If one wants to have the conf\logging.properties
read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\
folder and then add the lines :
-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
to the VM arguments of the launch configuration one is using.
This may have taken a restart or two (or not) but finally I saw in the console in bright red :
FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc
I still don't know when exactly this EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".FINE
warning appears - does not appear immediately on tomcat launch
Bonus: To make the warning go away add in catalina.properties
:
# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar
You can cast it to a list, insert the item, then cast it back to a tuple.
a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a
>> ('Product', '500.00', '1200.00', 'foobar')
This Code is to parse the XML wraps the JSON Response and display in the front end using ajax.
Required JavaScript code.
_x000D_
<script type="text/javascript">_x000D_
$.ajax({_x000D_
method:"GET",_x000D_
url: "javatpoint.html", _x000D_
_x000D_
success : function(data) { _x000D_
_x000D_
var json=JSON.parse(data); _x000D_
var tbody=$('tbody');_x000D_
for(var i in json){_x000D_
tbody.append('<tr><td>'+json[i].id+'</td>'+_x000D_
'<td>'+json[i].firstName+'</td>'+_x000D_
'<td>'+json[i].lastName+'</td>'+_x000D_
'<td>'+json[i].Download_DateTime+'</td>'+_x000D_
'<td>'+json[i].photo+'</td></tr>')_x000D_
} _x000D_
},_x000D_
error : function () {_x000D_
alert('errorrrrr');_x000D_
}_x000D_
});_x000D_
_x000D_
</script>
_x000D_
[{ "id": "1", "firstName": "Tom", "lastName": "Cruise", "photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg" }, { "id": "2", "firstName": "Maria", "lastName": "Sharapova", "photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg" }, { "id": "3", "firstName": "James", "lastName": "Bond", "photo": "https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg" }] `
URL url=new URL("www.example.com");
URLConnection si=url.openConnection();
InputStream is=si.getInputStream();
String str="";
int i;
while((i=is.read())!=-1){
str +=str.valueOf((char)i);
}
str =str.replace("</string>", "");
str=str.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
str = str.replace("<string xmlns=\"http://tempuri.org/\">", "");
PrintWriter out=resp.getWriter();
out.println(str);
`
A bit late to the party, but none of the previously mentioned locations worked for me - for some reason the back up/autorecovery files were saved under VS15 folder on my PC (this is for SQL Server 2016 Management Studio)
C:\Users\YOURUSERNAME\Documents\Visual Studio 2015\Backup Files\Solution1
You might want to check your Tools-Options-Environment-Import and Export Settings, the location of the settings files could point you to your back up folder - I would never have looked under the VS15 folder for this.
I also needed what you've been searching for and did some research.
I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.
Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.
Call decode()
on a bytes
instance to get the text which it encodes.
str = bytes.decode()
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
You need %in%
instead of ==
:
library(dplyr)
target <- c("Tom", "Lynn")
filter(dat, name %in% target) # equivalently, dat %>% filter(name %in% target)
Produces
days name
1 88 Lynn
2 11 Tom
3 1 Tom
4 222 Lynn
5 2 Lynn
To understand why, consider what happens here:
dat$name == target
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
Basically, we're recycling the two length target
vector four times to match the length of dat$name
. In other words, we are doing:
Lynn == Tom
Tom == Lynn
Chris == Tom
Lisa == Lynn
... continue repeating Tom and Lynn until end of data frame
In this case we don't get an error because I suspect your data frame actually has a different number of rows that don't allow recycling, but the sample you provide does (8 rows). If the sample had had an odd number of rows I would have gotten the same error as you. But even when recycling works, this is clearly not what you want. Basically, the statement dat$name == target
is equivalent to saying:
return
TRUE
for every odd value that is equal to "Tom" or every even value that is equal to "Lynn".
It so happens that the last value in your sample data frame is even and equal to "Lynn", hence the one TRUE
above.
To contrast, dat$name %in% target
says:
for each value in
dat$name
, check that it exists intarget
.
Very different. Here is the result:
[1] TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE
Note your problem has nothing to do with dplyr
, just the mis-use of ==
.
To fix the blank PDF issue in post request to get stream data like PDF, we need to add response type as 'arraybuffer' or 'blob' in request
$.ajax({
url: '<URL>',
type: "POST",
dataType: 'arraybuffer',
success: function(data) {
let blob = new Blob([data], {type: 'arraybuffer'});
let link = document.createElement('a');
let objectURL = window.URL.createObjectURL(blob);
link.href = objectURL;
link.target = '_self';
link.download = "fileName.pdf";
(document.body || document.documentElement).appendChild(link);
link.click();
setTimeout(()=>{
window.URL.revokeObjectURL(objectURL);
link.remove();
}, 100);
}
});
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
Hint is displayed correctly with
android:inputType="textPassword"
and
android:gravity="center"
if you set also
android:ellipsize="start"
Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken
with async
methods.
To summarize, you pass a CancellationToken
into each method that supports cancellation, and that method must check it periodically.
private async Task TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(1));
Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);
// (A canceled task will raise an exception when awaited).
await task;
}
private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
if (i % 1000 == 0)
cancellationToken.ThrowIfCancellationRequested();
}
return a + b;
}
If you have this listener:
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/>
on your server.xml, remove it and try. You can not use a keystore if you are using the APR connector
A simple array assignment works... Note that the first element of a bash
array can be addressed by just the name
without the [0]
index, ie, $md5
contains only the 32 chars of the md5sum.
md5=($(md5sum file))
echo $md5
# 53c8fdfcbb60cf8e1a1ee90601cc8fe2
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
toCharArray
followed by Arrays.sort
followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
just saw this now, if you are working with a list of object you can try this
public class user
{
public string username { get; set; }
public string password { get; set; }
}
List<user> userlist = new List<user>();
userlist.Add(new user { username = "macbruno", password = "1234" });
userlist.Add(new user { username = "james", password = "5678" });
string myusername = "james";
string mypassword = "23432";
user theUser = userlist.Find(
delegate (user thisuser)
{
return thisuser.username== myusername && thisuser.password == mypassword;
}
);
if (theUser != null)
{
Dosomething();
}
else
{
DoSomethingElse();
}
You just need to post the form data to the insert php file function, see below :)
class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;
public function connect()
{
try
{
$this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "It seems there was an error. Please refresh your browser and try again. ".$e->getMessage();
}
}
public function store($email)
{
$stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
$stm->bindValue(1, $email);
return $stm->execute();
}
}
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
As of python 2.7
, optparse
is deprecated, and will hopefully go away in the future.
argparse
is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):
+
and /
More information is also in PEP 389, which is the vehicle by which argparse
made it into the standard library.
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
Using
$("a").attr("href", "http://www.google.com/")
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
...Then you probably don't want to accidentally add href
attributes to them. For safety then, we can specify that our selector will only match <a>
tags with an existing href
attribute:
$("a[href]") //...
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href
, you might use something like this:
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
This will find links where the href
exactly matches the string http://www.google.com/
. A more involved task might be matching, then updating only part of the href
:
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
The first part selects only links where the href starts with http://stackoverflow.com
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
for(var i = 0; i < BoardMessages.length;i++){
(function(j){
console.log("Loading message %d".green, j);
htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
})(i);
}
That should work; however, you should never create a function in a loop. Therefore,
for(var i = 0; i < BoardMessages.length;i++){
composeMessage(BoardMessages[i]);
}
function composeMessage(message){
console.log("Loading message %d".green, message);
htmlMessageboardString += MessageToHTMLString(message);
}
urllib and urllib2 are both Python modules that do URL request related stuff but offer different functionalities.
1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL.
2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.
Requests - Requests’ is a simple, easy-to-use HTTP library written in Python.
1) Python Requests encodes the parameters automatically so you just pass them as simple arguments, unlike in the case of urllib, where you need to use the method urllib.encode() to encode the parameters before passing them.
2) It automatically decoded the response into Unicode.
3) Requests also has far more convenient error handling.If your authentication failed, urllib2 would raise a urllib2.URLError, while Requests would return a normal response object, as expected. All you have to see if the request was successful by boolean response.ok
I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).
<input type="text" value="<script>alert('test');</script>" />
Produces:
You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value
attribute.
var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";
Hey hey thanks from Xamarin user! :) Here it goes translated to c#
//***************************************************************************
public static class ImageExtensions
//***************************************************************************
{
//-------------------------------------------------------------
public static UIImage WithAlpha(this UIImage image, float alpha)
//-------------------------------------------------------------
{
UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale);
image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
}
Usage example:
var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);
#include<stdio.h>
int main(void) {
int n,y;
int ly=0;
int mon;
printf("enter the date\n");
scanf("%d",&n);
printf("enter the month in integer\n");
scanf("%d",&mon);
mon=mon-1;
printf("enter year\n");
scanf("%d",&y);
int dayT;
dayT=n%7;
if((y%4==0&&y%100!=0)|(y%4==0&&y%100==0&&y%400==0))
{
ly=y;
printf("the given year is a leap year\n");
}
char a[12]={6,2,2,5,0,3,5,1,4,6,2,4};
if(ly!=0)
{
a[0]=5;
a[1]=1;
}
int m,p;
m=a[mon];
int i,j=0,t=1;
for(i=1600;i<=3000;i++)
{
i=i+99;
if(i<y)
{
if(t==1)
{
p=5;t++;
}
else if(t==2)
{
p=3;
t++;
}
else if(t==3)
{
p=1;
t++;
}
else
{
p=0;
t=1;
}
}}
int q,r,s;
q=y%100;
r=q%7;
s=q/4;
int yTerm;
yTerm=p+r+s;
int w=dayT+m+yTerm;
w=w%7;
if(w==0)
printf("SUNDAY");
else if(w==1)
printf("MONDAY");
else if(w==2)
printf("TUESDAY");
else if(w==3)
printf("WEDNESDAY");
else if(w==4)
printf("THURSDAY");
else if(w==5)
printf("FRIDAY");
else
printf("SATURDAY");
return 0;
}
Here an implementation that uses a System.Threading.Timer
. Maybe a bit much for its purpose.
private static bool StartProcess(string filePath, string processName)
{
if (!File.Exists(filePath))
throw new InvalidOperationException($"Unknown filepath: {(string.IsNullOrEmpty(filePath) ? "EMPTY PATH" : filePath)}");
var isRunning = false;
using (var resetEvent = new ManualResetEvent(false))
{
void Callback(object state)
{
if (!IsProcessActive(processName)) return;
isRunning = true;
// ReSharper disable once AccessToDisposedClosure
resetEvent.Set();
}
using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
{
Process.Start(filePath);
WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
}
}
return isRunning;
}
private static bool StopProcess(string processName)
{
if (!IsProcessActive(processName)) return true;
var isRunning = true;
using (var resetEvent = new ManualResetEvent(false))
{
void Callback(object state)
{
if (IsProcessActive(processName)) return;
isRunning = false;
// ReSharper disable once AccessToDisposedClosure
resetEvent.Set();
}
using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
{
foreach (var process in Process.GetProcessesByName(processName))
process.Kill();
WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
}
}
return isRunning;
}
private static bool IsProcessActive(string processName)
{
return Process.GetProcessesByName(processName).Any();
}
Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Binarize (make it black and white) an image with Python."""
from PIL import Image
from scipy.misc import imsave
import numpy
def binarize_image(img_path, target_path, threshold):
"""Binarize an image."""
image_file = Image.open(img_path)
image = image_file.convert('L') # convert image to monochrome
image = numpy.array(image)
image = binarize_array(image, threshold)
imsave(target_path, image)
def binarize_array(numpy_array, threshold=200):
"""Binarize a numpy array."""
for i in range(len(numpy_array)):
for j in range(len(numpy_array[0])):
if numpy_array[i][j] > threshold:
numpy_array[i][j] = 255
else:
numpy_array[i][j] = 0
return numpy_array
def get_parser():
"""Get parser object for script xy.py."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--input",
dest="input",
help="read this file",
metavar="FILE",
required=True)
parser.add_argument("-o", "--output",
dest="output",
help="write binarized file hre",
metavar="FILE",
required=True)
parser.add_argument("--threshold",
dest="threshold",
default=200,
type=int,
help="Threshold when to show white")
return parser
if __name__ == "__main__":
args = get_parser().parse_args()
binarize_image(args.input, args.output, args.threshold)
It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200
:
In Xcode 9 there is a new "Actual Size" option. In the Simulator to the Window menu and choose Scale > Actual Size to trigger it. This takes into account your current screen resolution to ensure the on-screen device matches the physical dimensions of a real device.
It is actually very easy to do this using the "set" and "get" methods available on an express object.
Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:
In app.js:
var config = require('./config');
app.configure(function() {
...
app.set('config', config);
...
}
In routes/index.js
exports.index = function(req, res){
var config = req.app.get('config');
// config is now available
...
}
In your example, you can just go:
chomp(@lines);
Or:
$_=join("", @lines);
s/[\r\n]+//g;
Or:
@lines = split /[\r\n]+/, join("", @lines);
Using these directly on a file:
perl -e '$_=join("",<>); s/[\r\n]+//g; print' <a.txt |less
perl -e 'chomp(@a=<>);print @a' <a.txt |less
<style>
.left-column
{
float:left;
width:30%;
background-color:red;
}
.right-column
{
float:right;
width:30%;
background-color:green;
}
.center-column
{
margin:auto;
width:30%;
background-color:blue;
}
</style>
<div id="container">
<section class="left-column">THIS IS COLUMN 1 LEFT</section>
<section class="right-column">THIS IS COLUMN 3 RIGHT</section>
<section class="center-column">THIS IS COLUMN 2 CENTER</section>
</div>
the advantage of this way is you can set each column width independant of the other as long as you keep it under 100%, if you use 3 x 30% the remaining 10% is split as a 5% divider space between the collumns
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
After some research I was able to find a good solution for converting UTC to local time, have a a look at the fiddle. Hope it help
https://jsfiddle.net/way2ajay19/2kramzng/20/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
{{date | date:'yyyy-mm-dd hh:mm:ss' }}
</div>
<script>
function MyCtrl($scope) {
$scope.d = "2017-07-21 19:47:00";
$scope.d = $scope.d.replace(" ", 'T') + 'Z';
$scope.date = new Date($scope.d);
}
</script>
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
The correct solution to get the Prompt
value in a non-templated control context is:
@Html.TextBoxFor(model => model.Email,
new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)
This will also not double-escape the watermark text.
Paste following link to directly under link button click event, otherwise use javascript to call code behind function
Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Diagnostics.Process.Start(FilePath)
End Sub
You have not one, but many mistakes. It should be:
int[] tall = new int[28123];
for (int j=0;j<28123;j++){
tall[j] = j+1;
}
Your code is putting a 0 in all the positions of the array.
Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Iteration vs Space, usage could be an issue. In different situations profiling may show either to be "faster" and/or "less memory" intensive.
# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]
# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]
The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None
entries.
The second approach goes through the list once, and then again each time until a None
is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None
entries in the front, but the worst case would be if lots of None
entries were in the back.
The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.
Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.
Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy
(example if L is numpy.array: L = L[L != numpy.array(None)
(from here)) or cython
may be worthwhile alternatives instead of attempting to micromanage Python optimizations.
What Harry S says is exactly right, but
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
would also do the trick. (We Resharper users can always spot each other in crowds...)
It just means that either alter > ncol( reach_mat )
or i > nrow( reach_mat )
, in other words, your indices exceed the array boundary (i is greater than the number of rows, or alter is greater than the number of columns).
Just run the above tests to see what and when is happening.
If you want to have a picture next to an url from your website someone shared on WhatsApp, you have to put a metatag on the page where the URL links to, like this:
<meta property="og:image" content="http://unrestrictedstock.com/wp-content/uploads/Unrestricted-Stock-Small.png"/>
A lot of the answers in this thread get the point of using refs, but I think a complete example would be good. Since you're operating on an actual DOM node by using the event listener and stepping out of the React context, a ref should be considered the standard solution. Here's a complete example:
class someComponent extends Component {
constructor(props) {
super(props)
this.node = null
}
render() {
return (
<div ref={node => { this.node = node }}>Content</div>
)
}
handleEvent(event) {
if (this.node) {
this.setState({...})
}
}
componentDidMount() {
//as soon as render completes, the node will be registered.
const handleEvent = this.handleEvent.bind(this)
this.node.addEventListener('click', handleEvent)
}
componentWillUnmount() {
const handleEvent = this.handleEvent.bind(this)
this.node.removeEventListener('click', handleEvent)
}
}
Ok I've done it. I'm sharing this code in case someone else will need it:
super.draw(canvas, mapView, true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point point1_draw = new Point();
Point point2_draw = new Point();
Point point3_draw = new Point();
mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();
canvas.drawPath(path, paint);
//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);
return true;
Thanks for the hint Nicolas!
Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static
directory? If you move it to your static directory and update your HTML as such:
<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">
It should work.
Also, it is worth noting, there is a better way to structure this.
File structure:
app.py
static
|----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
|----index.html
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return render_template('index.html')
if __name__ == '__main__':
app.run()
templates/index.html
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />
</body>
</html>
Doing it this way ensures that you are not hard-coding a URL path for your static assets.
for (int i = 0; i < clbIncludes.Items.Count; i++)
if (clbIncludes.GetItemChecked(i))
// Do selected stuff
else
// Do unselected stuff
If the the check is in indeterminate state, this will still return true. You may want to replace
if (clbIncludes.GetItemChecked(i))
with
if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)
if you want to only include actually checked items.
I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.
getimagesize() returns an array containing the image properties.
list($width, $height) = getimagesize("path/to/image.jpg");
to just get the width and height or
list($width, $height, $type, $attr)
to get some more information.
You need
.abc,.ab {
display: none;
}
#f:hover ~ .ab {
display: block;
}
#s:hover ~ .abc {
display: block;
}
#s:hover ~ .a,
#f:hover ~ .a{
display: none;
}
Updated demo at http://jsfiddle.net/gaby/n5fzB/2/
The problem in your original CSS was that the ,
in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a
means #f:hover ~ .abc
and .a
. You set that to display:none
so it was always set to be hidden for all .a
elements.
Once you have a json object
obj.valueOf(Object.keys(obj).indexOf('String_to_Find'))
This was caused because of something like this in my case:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<include-prelude>/headerfooter/header.jsp</include-prelude>
<include-coda>/headerfooter/footer.jsp</include-coda>
</jsp-property-group>
</jsp-config>
The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
border-radius
of 50% which will make it circular in shape. (note: no prefix has been required for a long time)background-color
/ gradients / (even pseudo elements
) to create something like this:.red {_x000D_
background-color: red;_x000D_
}_x000D_
.green {_x000D_
background-color: green;_x000D_
}_x000D_
.blue {_x000D_
background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border-radius: 50%;_x000D_
text-align: center;_x000D_
vertical-align: middle;_x000D_
font-size: 500%;_x000D_
position: relative;_x000D_
box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
display: inline-block;_x000D_
margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
background-color: rgba(255, 255, 255, 0.3);_x000D_
content: '';_x000D_
height: 45%;_x000D_
width: 12%;_x000D_
position: absolute;_x000D_
top: 4%;_x000D_
left: 15%;_x000D_
border-radius: 50%;_x000D_
transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
In your case, you can use root
directive, because $uri
part of the location
directive is the same with last root
directive part.
Nginx documentation advices it as well:
When location matches the last part of the directive’s value:location /images/ { alias /data/w3/images/; }
it is better to use the root directive instead:
location /images/ { root /data/w3; }
and root
directive will append $uri
to the path.
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like
textview.append("Step Two: fry egg");
rsvndump
worked great for me migrating a repository from svnrepository.com to an Ubuntu server that I control.
Install missing dependencies ("APR" and Subversion libraries)
sudo apt-get install apache2-threaded-dev
sudo apt-get install libsvn-dev
Install rsvndump
wget http://prdownloads.sourceforge.net/rsvndump/rsvndump-0.5.5.tar.gz
tar xvfz rsvndump-0.5.5.tar.gz
cd rsvndump-0.5.5
./configure
make
sudo make install
Dump the remote SVN repository to a local file
rsvndump http://my.svnrepository.com/svn/old_repo > old_repo_dump
Create a new repository and load in the local dump file
sudo svnadmin create /opt/subversion/my_new_rep
sudo svnadmin load --force-uuid /opt/subversion/my_new_repo < old_repo_dump
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
Because we make UI into XML but view objects is what we display so we somehow need to convert xml into view objects so inflating means we are converting xml into view objects so that it can be displayed, for this we need a service called layout inflator service and give it an xml and it will be convert for you.
From @NHG comment — works perfectly
{% for post in posts|slice(0,10) %}
You can also simply use @NonNull
with the lombok library instead, at least for the @NotNull
scenario. More details: https://projectlombok.org/api/lombok/NonNull.html
you could use inherit
#one {width:500px;height:300px;}
#two {width:inherit;height:inherit;}
#three {width:inherit;height:inherit;}
Neither UIImageView not UIImage holds on to the filename of the image loaded.
You can either
1: (as suggested by Kenny Winker above) subclass UIImageView to have a fileName property or
2: name the image files with numbers (image1.jpg, image2.jpg etc) and tag those images with the corresponding number (tag=1 for image1.jpg, tag=2 for image2.jpg etc) or
3: Have a class level variable (eg. NSString *currentFileName) which updates whenever you update the UIImageView's image
Please have a look at http://jsfiddle.net/2dJAN/59/
$("#submit").click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1)
tool can be used to diagnose SELinux denials from the log:
(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc: denied { write }
for pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
scontext=system_u:system_r:httpd_t:s0
tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
tclass=file permissive=0
Was caused by:
The boolean httpd_unified was set incorrectly.
Description:
Allow httpd to unified
Allow access by executing:
# setsebool -P httpd_unified 1
Sure enough, running sudo setsebool -P httpd_unified 1
resolved the issue.
Looking into what httpd_unified
is for, I came across a fedora-selinux-list post which explains:
This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.
So turning on httpd_unified
lets you circumvent the default behaviour that prevents multiple httpd
instances on the same server - all running as user apache
- messing with each others' stuff.
In my case, I am only running one httpd
, so it was fine for me to turn on httpd_unified
. If you cannot do this, I suppose some more fine-grained labelling is needed.
$http.get(url).success(successCallback).error(errorCallback);
Replace successCallback and errorCallback with your functions.
Edit: Laurent's answer is more correct considering he is using then
. Yet I'm leaving this here as an alternative for the folks who will visit this question.
As mentioned, but with a code sample:
foreach(var item in collection.ToArray())
collection.Add(new Item...);
If the above doesn't work for you, try this:
.btn:focus {outline: none;box-shadow: none;border:2px solid transparent;}
As user1933897 pointed out, this might be specific to MacOS with Chrome.
For me the with NPP V7.6.6 (x64) this worked:
Download the plugin, and unzip to some local folder (e.g. Downloads). Make sure you download the correct plugin for your Notepad++ (64 or 32 bit - e.g. see ? -> About Notepad++ to find if you are 64-bit)
Check each DLL to ensure it is unblocked (right-click, Properties, and check/select Unblock.
Run Notepad++. If you have UAC enabled, use "Run as Administrator" to run Notepad++ (Hold Shift key down, right-click Notepad++ icon, and select "Run as Administrator").
Go to menu Settings -> Import -> Import plugins...
Use dialog displayed to locate you local copy of the plugin DLL.
Once plugin DLL has been selected, Notepad++ should tell you you need to restart. If it doesn't, then Notepad++ has had some problem - though it doesn't tell you what...!
Restart Notepad++.
The above causes a copy of the plugin DLL to be copied under a subfolder of the same name in C:\Program Files\Notepad++\plugins.
Putting plugins directly into one of the following folders (or sub-folders for each plugin), as suggested in other answers, did not work for me:
a) %PROGRAMDATA%\Notepad++\plugins. b) %ALLDATA%\Notepad++\plugins.
the button 'Use same account' below thee main window will fill in all the textboxes automatically. this worked fpr me.
If you want to update multiple rows using limit in MySQL you can use this construct:
UPDATE table_name SET name='test'
WHERE id IN (
SELECT id FROM (
SELECT id FROM table_name
ORDER BY id ASC
LIMIT 0, 10
) tmp
)
if you used List object and passed to the adapter you can remove the value from the List object and than call the notifyDataSetChanged() using adapter object.
for e.g.
List<String> list = new ArrayList<String>();
ArrayAdapter adapter;
adapter = new ArrayAdapter<String>(DeleteManyTask.this,
android.R.layout.simple_list_item_1,
(String[])list.toArray(new String[0]));
listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
listview.setAdapter(listAdapter);
for remove do this way
list.remove(index); //or
list.clear();
adpater.notifyDataSetChanged();
or without list object remove item from list.
adapter.clear();
adpater.notifyDataSetChanged();
Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:
const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
Our accumulator acc
, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!
ALTER DATABASE [DatabaseName] SET READ_WRITE
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.
I had a small success by doing the following after creating the dialog on element $dlg
.
$dlg.closest('.ui-dialog').css('zIndex',adjustment);
Since each dialog has a different starting z-index
(they incrementally get larger) I make adjustment
a string with a boost value, like this:
const adjustment = "+=99";
However, jQuery just keeps increasing the zIndex
value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:
CoverAll = {};
CoverAll.modalDiv = null;
CoverAll.modalCloak = function(zIndex) {
var div = CoverAll.modalDiv;
if(!CoverAll.modalDiv) {
div = CoverAll.modalDiv = document.createElement('div');
div.style.background = '#aaaaaa';
div.style.opacity = '0.3';
div.style.position = 'fixed';
div.style.top = '0';
div.style.left = '0';
div.style.width = '100%';
div.style.height = '100%';
}
if(!div.parentElement) {
document.body.appendChild(div);
}
if(zIndex == null)
zIndex = 100;
div.style.zIndex = zIndex;
return div;
}
CoverAll.modalUncloak = function() {
var div = CoverAll.modalDiv;
if(div && div.parentElement) {
document.body.removeChild(div);
}
return div;
}
There is no way to create an array of a predefined size without also supplying values for the elements of that array.
The best way to initialize an array like that is array_fill
. By far preferable over the various loop-and-insert solutions.
$my_array = array_fill(0, $size_of_the_array, $some_data);
Every position in the $my_array
will contain $some_data
.
The first zero in array_fill
just indicates the index from where the array needs to be filled with the value.
Yes. Google Chrome has deprecated the feature in version 50. If you tried to use it in chrome the error is:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.
So, you have to add SSL certificate. Well, that's the only way.
And it's quite easy now using Let's Encrypt. Here's guide
And for testing purpose you could try this:
1.localhost is treated as a secure origin over HTTP, so if you're able to run your server from localhost, you should be able to test the feature on that server.
2.You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.
I think Firefox also restricted user from accessing GeoLocation API requests from http
. Here's the webkit changelog: https://trac.webkit.org/changeset/200686
checker = None
if some_decision:
checker = True
if checker:
# some stuff
[Edit]
For more information: http://docs.python.org/library/functions.html#bool
Your code works too, since 1
is converted to True
when necessary.
Actually Python didn't have a boolean type for a long time (as in old C), and some programmers still use integers instead of booleans.
In the code below, Class A
implements the interface IShow
and implements its method ShowData
. Class B
inherits Class A
. In order to use ShowData
method in Class B
, we have to use keyword new
in the ShowData
method in order to hide the base class Class A
method and use override
keyword in order to extend the method.
interface IShow
{
protected void ShowData();
}
class A : IShow
{
protected void ShowData()
{
Console.WriteLine("This is Class A");
}
}
class B : A
{
protected new void ShowData()
{
Console.WriteLine("This is Class B");
}
}
Add new column to Table
ALTER TABLE [table]
ADD Column1 Datatype
E.g
ALTER TABLE [test]
ADD ID Int
If User wants to make it auto incremented then
ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL
Here is how I would do it using vanilla JS
<form id="myform" method="POST" action="xxx">
<!-- your stuff here -->
<a href="javascript:void()" onclick="document.getElementById('myform').submit();>Ponies await!</a>
</form>
You can play with the return false
s and href="#"
vs void and whatever you need to but this method worked for me in Chrome 18, IE 9 and Firefox 14 and the rest depends on your javascript mostly.
You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects
I believe I have a much simpeler solution for this.
public class MyFragment extends Fragment{
private String mTitle;
private List<MyObject> mObjects;
public static MyFragment newInstance(String title, List<MyObject> objects)
MyFragment myFrag = new MyFragment();
myFrag.mTitle = title;
myFrag.mObjects = objects;
return myFrag;
}
I have done a quick test:
import sys
str = e = "a xxxxxxxxxx very xxxxxxxxxx long xxxxxxxxxx string xxxxxxxxxx\n"
for i in range(int(sys.argv[1])):
str = str + e
and timed it:
mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py 8000000
8000000 times
real 0m2.165s
user 0m1.620s
sys 0m0.540s
mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py 16000000
16000000 times
real 0m4.360s
user 0m3.480s
sys 0m0.870s
There is apparently an optimisation for the a = a + b
case. It does not exhibit O(n^2) time as one might suspect.
So at least in terms of performance, using +
is fine.
try this short & sweet code -
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
Output -
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
To disable password checks in mariadb-10.1.24 (Fedora 24) I had to comment out a line in /etc/my.cnf.d/cracklib_password_check.cnf file:
;plugin-load-add=cracklib_password_check.so
then restart mariadb service:
systemctl restart mariadb.service
The Mark Dickinson answer, although complete, didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:
import decimal
def value_to_decimal(value, decimal_places):
decimal.getcontext().rounding = decimal.ROUND_HALF_UP # define rounding method
return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))
(The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)
Hope this helps anyone.
view.layer.cornerRadius = 25
view.layer.masksToBounds = true
I did this solution: if you want plot more than one plot in one figure, make sure before plotting next plots you have set right matplotlib.pyplot.hold(True)
to able adding another plots.
Concerning the datetime values on the X axis, a solution using the alignment of bars works for me. When you create another bar plot with matplotlib.pyplot.bar()
, just use align='edge|center'
and set width='+|-distance'
.
When you set all bars (plots) right, you will see the bars fine.
I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.
I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.
This code worked for me
public static void main(String[] args) {
try {
java.net.URL myUr = new java.net.URL("http://path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
Instantiated new URL: http://path
you might want to start with max(trans_seq_no) + 1.
watch:
SQL> create table my_numbers(my_number number not null primary key);
Table created.
SQL> insert into my_numbers(select rownum from user_objects);
260 rows created.
SQL> select max(my_number) from my_numbers;
MAX(MY_NUMBER)
--------------
260
SQL> create sequence my_number_sn start with 260;
Sequence created.
SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
insert into my_numbers(my_number) values (my_number_sn.NEXTVAL)
*
ERROR at line 1:
ORA-00001: unique constraint (NEIL.SYS_C00102439) violated
When you create a sequence with a number, you have to remember that the first time you select against the sequence, Oracle will return the initial value that you assigned it.
SQL> drop sequence my_number_sn;
Sequence dropped.
SQL> create sequence my_number_sn start with 261;
Sequence created.
SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
1 row created.
If you're trying to do the 'gapless' thing, I strongly advise you to
In ASCII text file each character is just one byte
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
If you have a Red Hat server use yum. apt-get is only for Debian, Ubuntu and some other related linux.
Why would you want to use apt-get anyway? (It seems like you know what yum is.)
You should also be careful with your case. Let me explain: doing Blah.valueOf("A")
works, but Blah.valueOf("a")
will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH))
would work.
edit
Changed toUpperCase
to toUpperCase(Locale.ENGLISH)
based on tc. comment and the java docs
edit2
On android you should use Locale.US
, as sulai points out.
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
shutil.copy
and shutil.copy2
are copying files.
shutil.copytree
copies a folder with all the files and all subfolders. shutil.copytree
is using shutil.copy2
to copy the files.
So the analog to cp -r
you are saying is the shutil.copytree
because cp -r
targets and copies a folder and its files/subfolders like shutil.copytree
. Without the -r
cp
copies files like shutil.copy
and shutil.copy2
do.
This is the jQuery solution that worked for me. offsetWidth
etc. didn't work.
function is_overflowing(element, extra_width) {
return element.position().left + element.width() + extra_width > element.parent().width();
}
If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent())
. position
is relative to the parent. I've also included extra_width
because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:
var extra_width = 0;
$(".tag:visible").each(function() {
if (!$(this).find("img:visible").width()) {
// tag image might not be visible at this point,
// so we add its future width to the overflow calculation
// the goal is to hide tags that do not fit one line
extra_width += 28;
}
if (is_overflowing($(this), extra_width)) {
$(this).hide();
}
});
Hope this helps.
If you're using Gated builds, when a build is triggered, it creates a shelveset of your workspace that is submitted for build. If the build fails, the shelveset is rejected. If the build is successful, a changeset is created and committed to TFS. In either event, the person doing that check-in/build will have to reconcile the workspace, which is as simple as performing a Get Latest.
reverse()
| Django documentation
Let's suppose that in your urls.py
you have defined this:
url(r'^foo$', some_view, name='url_name'),
In a template you can then refer to this url as:
<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>
<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>
This will be rendered as:
<a href="/foo/">link which calls some_view</a>
Now say you want to do something similar in your views.py
- e.g. you are handling some other url (not /foo/
) in some other view (not some_view
) and you want to redirect the user to /foo/
(often the case on successful form submission).
You could just do:
return HttpResponseRedirect('/foo/')
But what if you want to change the url in future? You'd have to update your urls.py
and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.
Instead, you can say:
from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))
This looks through all urls defined in your project for the url defined with the name url_name
and returns the actual url /foo/
.
This means that you refer to the url only by its name
attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py
.
As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:
new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)
Note that Brad Abrams from Microsoft wrote in 2004:
there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance
I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info
on the console.
To get INFO
, WARNING
, and ERROR
messages in the console, the dictConfig
object can be used to create logging configuration for all logs (source):
from logging.config import dictConfig
from flask import Flask
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO',
'handlers': ['wsgi']
}
})
app = Flask(__name__)
@app.route('/')
def index():
return "Hello from Flask's test environment"
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
Check out the range
documentation, you have to define a negative step:
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));
If you want to query the results from a temporary table inside the same query, you can use # temp tables, or @ table variables (I personally prefer @), for querying outside of the scope you would either want to use ## global temp tables or create a new table with the results.
DECLARE
@ProjectID int = 3,
@Year int = 2010,
@MeterTypeID int = 1,
@StartDate datetime,
@EndDate datetime
SET @StartDate = '07/01/' + CAST(@Year as VARCHAR)
SET @EndDate = '06/30/' + CAST(@Year+1 as VARCHAR)
DECLARE @MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)
INSERT INTO @MyTempTable (SiteName, BillingMonth, Consumption)
SELECT tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects
When I do what explains some answers:
The result is:
So, anybody can explain really really how to delete an old App ID?
My opinion is: Apple does not let you remove them. I suppose it is a way to maintain the traceability or the historical of the published.
And of course: application is no longer available in the App Store. It was available (in the past), yes.
In controllers action add:
public ActionResult Index()
{
try
{
int a, b, c;
a = 2; b = 2;
c = a / b;
ViewBag.ShowMessage = false;
}
catch (Exception e)
{
ViewBag.ShowMessage = true;
ViewBag.data = e.Message.ToString();
}
return View(); // return View();
}
in Index.cshtml
Place at the bottom:
<input type="hidden" value="@ViewBag.data" id="hdnFlag" />
@if (ViewBag.ShowMessage)
{
<script type="text/javascript">
var h1 = document.getElementById('hdnFlag');
alert(h1.value);
</script>
<div class="message-box">Some Message here</div>
}
textarea#note {
width:100%;
direction:rtl;
display:block;
max-width:100%;
line-height:1.5;
padding:15px 15px 30px;
border-radius:3px;
border:1px solid #F7E98D;
font:13px Tahoma, cursive;
transition:box-shadow 0.5s ease;
box-shadow:0 4px 6px rgba(0,0,0,0.1);
font-smoothing:subpixel-antialiased;
background:-o-linear-gradient(#F9EFAF, #F7E98D);
background:-ms-linear-gradient(#F9EFAF, #F7E98D);
background:-moz-linear-gradient(#F9EFAF, #F7E98D);
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
background:linear-gradient(#F9EFAF, #F7E98D);
height:100%;
}
html{
height:100%;
}
body{
height:100%;
}
or javascript
var s_height = document.getElementById('note').scrollHeight;
document.getElementById('note').setAttribute('style','height:'+s_height+'px');
I had similar issue, this is how it was solved
xyz@ip :~/formsProject_SVN$ svn resolved formsProj/templates/search
Resolved conflicted state of 'formsProj/templates/search'
Now update your project
xyz@ip:~/formsProject_SVN$ svn update
Updating '.':
Select: (mc) keep affected local moves, (r) mark resolved (breaks moves), (p) postpone, (q) quit resolution, (h) help: r (select "r" option to resolve)
Resolved conflicted state of 'formsProj/templates/search'
Summary of conflicts: Tree conflicts: 0 remaining (and 1 already resolved)
Try this code:
<?php
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=hasil-export.xls");
include 'view-lap.php';
?>
Declare a prototype to get first array element as:
Array.prototype.first = function () {
return this[0];
};
Then use it as:
var array = [0, 1, 2, 3];
var first = array.first();
var _first = [0, 1, 2, 3].first();
Or simply (:
first = array[0];
Although this answer is a bit verbose it does allow you to create a single commit branch by doing a single merge with another branch. (No rebasing/squashing/merging individual commits).
Since we don't care about the in-between commits we can use a simple solution:
# Merge and resolve conflicts
git merge origin/master
# Soft reset and create a HEAD with the version you want
git reset --soft origin/master
git commit -m "Commit message"
git push origin your-branch -f
... then to remove the history...
# Get the most up-to-date master
git checkout master
git reset --hard
# Create a temporary branch
git checkout -b temp-branch
# Retrieve the diff between master and your-branch and commit with a single commit
git checkout origin/your-branch
git commit -m "Feature commit"
# Force push to the feature branch
git push origin temp-branch:your-branch -f
# Clean up
git checkout your-branch
git branch -D temp-branch
This can all be put into a bash function with 3 params like so squashall --their master --mine your-branch --msg "Feature commit"
and it will work as long as you have the correct version of files locally.
I imagine that there are not many browsers supporting extension. Indeed, I have been interested in this question for the last year and I only found Dolphin supporting add-ons and other cool features announced few days ago. I want to test it soon.
If you need only change url but prevent change state:
Change location with (add .replace if you want to replace in history):
this.$location.path([Your path]).replace();
Prevent redirect to your state:
$transitions.onBefore({}, function($transition$) {
if ($transition$.$to().name === '[state name]') {
return false;
}
});
The answer here is very simple:
You're already containing it in double quotes, so there's no need to escape it with \
.
If you want to escape single quotes in a single quote string:
var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
// ^ ^ same types, hence we need to escape it with a backslash
or if you want to escape \'
, you can escape the bashslash to \\
and the quote to \'
like so:
var string = 'this isn\\\'t a double quoted string';
// vvvv
// \ ' (the escaped characters)
However, if you contain the string with a different quote type, you don't need to escape:
var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
// ^ ^ different types, hence we don't need escaping
The Oracle/PLSQL
CONCAT
function allows to concatenate two strings together.
CONCAT( string1, string2 )
string1
The first string to concatenate.
string2
The second string to concatenate.
E.g.
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake FROM table;
I had that same problem but in case that I was adding en element into iterated list. I made it this way
public static void remove(Integer remove) {
for(int i=0; i<integerList.size(); i++) {
//here is maybe fine to deal with integerList.get(i)==null
if(integerList.get(i).equals(remove)) {
integerList.remove(i);
}
}
}
Now everything goes fine because you don't create any iterator over your list, you iterate over it "manually". And condition i < integerList.size()
will never fool you because when you remove/add something into List size of the List decrement/increment..
Hope it helps, for me that was solution.
Try :
This is fine :
@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
but for performance wise you don't need to iterate @attachments twice :
@logos , @images = [], []
@attachments.each do |attachment|
@logos << attachment if attachment.file_type == 'logo'
@images << attachment if attachment.file_type == 'image'
end
could also use following as per the php manual comment
$_SERVER['REDIRECT_URL']
Please note this is working only for certain PHP environment only and follow the bellow comment from that page for more information;
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
the join()
function must work for you:
$array = array('apple','banana','ananas');
$string = join(',', $array);
echo $string;
Output :
apple,banana,ananas
Please check if you are were passing method as POST
instead as GET
.
if so you will get same error as a you posted above.
$http({
method: 'GET',
The request entity's media type 'text/plain' is not supported for this resource.
If you want to parse the format yourself you could do it easily with a regex such as
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}
However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.
You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().
Even though its not directly related. But I found that the CALC code won't work if you do not put spaces properly.
So this did not work for me calc(#{$a}+7px)
But this worked calc(#{$a} + 7px)
Took me sometime to figure this out.
If your coloumn is text
and not varchar
, then you can use this:
SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))
Here an option using a list written on some range, populating an array that will be fiiltered. The information will be erased then the columns sorted.
Sub Filter_Out_Values()
'Automation to remove some codes from the list
Dim ws, ws1 As Worksheet
Dim myArray() As Variant
Dim x, lastrow As Long
Dim cell As Range
Set ws = Worksheets("List")
Set ws1 = Worksheets(8)
lastrow = ws.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Go through the list of codes to exclude
For Each cell In ws.Range("A2:A" & lastrow)
If cell.Offset(0, 2).Value = "X" Then 'If the Code is associated with "X"
ReDim Preserve myArray(x) 'Initiate array
myArray(x) = CStr(cell.Value) 'Populate the array with the code
x = x + 1 'Increase array capacity
ReDim Preserve myArray(x) 'Redim array
End If
Next cell
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
ws1.Range("C2:C" & lastrow).AutoFilter field:=3, Criteria1:=myArray, Operator:=xlFilterValues
ws1.Range("A2:Z" & lastrow).SpecialCells(xlCellTypeVisible).ClearContents
ws1.Range("A2:Z" & lastrow).AutoFilter field:=3
'Sort columns
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Sort with 2 criteria
With ws1.Range("A1:Z" & lastrow)
.Resize(lastrow).Sort _
key1:=ws1.Columns("B"), order1:=xlAscending, DataOption1:=xlSortNormal, _
key2:=ws1.Columns("D"), order1:=xlAscending, DataOption1:=xlSortNormal, _
Header:=xlYes, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod:=xlPinYin
End With
End Sub
ole@T:~$ docker run -it --rm alpine /bin/ash
(inside container) / #
Options used above:
/bin/ash
is Ash (Almquist Shell) provided by BusyBox--rm
Automatically remove the container when it exits (docker run --help
)-i
Interactive mode (Keep STDIN open even if not attached)-t
Allocate a pseudo-TTYNo one mentioned Stream
so far, so here it is:
if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))
I don't think it's possible.
You can use mysqldump
to dump the data and then create a schema with your new name and then dump the data into that new database.
sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
echo ${a%%;*}
a=${a#*;}
done
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" />
<item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>
From the Perldoc page on sleep:
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().
Actually, it provides usleep()
(which sleeps in microseconds) and nanosleep()
(which sleeps in nanoseconds). You may want usleep()
, which should let you deal with easier numbers. 1 millisecond sleep (using each):
use strict;
use warnings;
use Time::HiRes qw(usleep nanosleep);
# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);
If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select()
function:
# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
Define function in protocol and create extension for that protocol, then create empty implementation for function which you want to use as optional.
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
I've found that this can happen due to a number of various reasons.
In my case when I scroll to the end of the SQL import "Report", under the "Post-execute (Success)" heading it will tell me how many rows were copied and it's usually the next row in sheet which has the issue. Also you can tell which column by the import messages (in your case it was "Copy of F2") so you can generally find out which was the offending cell in Excel.
I've seen this happen for very silly reasons such as the date format in Excel being different than previous rows. For example cell A2 being "05/02/2017" while A3 being "5/2/2017" or even "05-02-2017". It seems the import wants things to be perfectly consistent.
It even happens if the Excel formats are different so if B2 is "512" but an Excel "Number" format and B3 is "512" but an Excel "Text" format then the Cell will cause an error.
I've also had situations where I literally had to delete all the "empty" rows below my data rows in the Excel sheet. Sometimes they appear empty but Excel considers them having "blank" data or something like that so the import tries to import them as well. This usually happens if you've had previous data in your Excel sheet which you've cleared but haven't properly deleted the rows.
And then there's the obvious reasons of trying to import text value into an integer column or insert a NULL into a NOT NULL column as mentioned by the others.
0
and 7
both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.
Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON
, THU
, etc:
0 - Sun Sunday
1 - Mon Monday
2 - Tue Tuesday
3 - Wed Wednesday
4 - Thu Thursday
5 - Fri Friday
6 - Sat Saturday
7 - Sun Sunday
Graphically:
+---------- minute (0 - 59)
¦ +-------- hour (0 - 23)
¦ ¦ +------ day of month (1 - 31)
¦ ¦ ¦ +---- month (1 - 12)
¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
¦ ¦ ¦ ¦ ¦ 1 - 7 => Monday - Sunday)
? ? ? ? ?
* * * * * command to be executed
Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU
will exectute the command only on sundays, mondays on thursdays.
You can read further details in Wikipedia's article about Cron.
If you are running spring cloud application, make sure your boot version matches cloud version. You can check the version compatibility matrix at the bottom of this page : https://spring.io/projects/spring-cloud.
Use Sheets rather than Sheet and activate them sequentially:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
fixed position is a bit tricky (indeed impossible), but position: sticky is doing the trick beautifully:
<div class='container'>
<header>This is the header</header>
<section>
... long lorem ipsum
</section>
</div>
body {
text-align: center;
}
.container {
text-align: left;
max-width: 30%;
margin: 0 auto;
}
header {
line-height: 2rem;
outline: 1px solid red;
background: #fff;
padding: 1rem;
position: sticky;
top: 0;
}
The simplest way to do this is:
git tag v1.0.0 f4ba1fc
git push origin --tags
with f4ba1fc
being the beginning of the hash of the commit you want to tag and v1.0.0
being the version you want to tag.
BTW, if you want some semantics such as only put if this key is not exist. you can use concurrentHashMap
with putIfAbsent()
function.
Check this out:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#put(K,%20V)
concurrentHashMap
is thread safe with high performance since it uses "lock striping" mechanism to improve the throughput.
If you want to switch only for once use this
nvm use 12.x
Else if you want to switch the default node version then use
nvm use default 12.x
int[] scores = { 100, 90, 90, 80, 75, 60 };
int[] alice = { 50, 65, 77, 90, 102 };
int[] scoreBoard = new int[scores.Length + alice.Length];
int j = 0;
for (int i=0;i<(scores.Length+alice.Length);i++) // to combine two arrays
{
if(i<scores.Length)
{
scoreBoard[i] = scores[i];
}
else
{
scoreBoard[i] = alice[j];
j = j + 1;
}
}
for (int l = 0; l < (scores.Length + alice.Length); l++)
{
Console.WriteLine(scoreBoard[l]);
}
While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.
It was, however, the attribute imeOptions="actionUnspecified"
that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager
. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions
. You can specify a "Send" button or "Next" button. The full list can be found here.
With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListener
for the EditText
element. As in your example:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
Now in my example I had android:imeOptions="actionUnspecified"
attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.
EDIT:
There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):
The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.
At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.
few more ways:
1.Robocopy not available in XP but can be downloaded form with win 2003 resource tool kit .Also might depend on localization:
@echo off
setlocal
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
set "dow=%%D"
set "month=%%E"
set "day=%%F"
set "HH=%%G"
set "MM=%%H"
set "SS=%%I"
set "year=%%J"
)
echo Day of the week: %dow%
endlocal
2.MAKECAB - works on every windows machine (but creates a small temp file).Function provided by carlos:
@Echo Off
Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
Echo weekday:%weekday%
Goto :EOF
:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof
:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof
3.W32TM - uses command switches introduced in Vista so will not work on windows 2003/XP:
@echo off
setlocal
call :w32dow day_ow
echo %day_ow%
pause
exit /b 0
endlocal
:w32dow [RrnVar]
setlocal
rem :: prints the day of the week
rem :: works on Vista and above
rem :: getting ansi date ( days passed from 1st jan 1601 ) , timer server hour and current hour
FOR /F "tokens=4,5 delims=:( " %%D in ('w32tm /stripchart /computer:localhost /samples:1 /period:1 /dataonly /packetinfo^|find "Transmit Timestamp:" ') do (
set "ANSI_DATE=%%D"
set "TIMESERVER_HOURS=%%E"
)
set "LOCAL_HOURS=%TIME:~0,2%"
if "%TIMESERVER_HOURS:~0,1%0" EQU "00" set TIMESERVER_HOURS=%TIMESERVER_HOURS:~1,1%
if "%LOCAL_HOURS:~0,1%0" EQU "00" set LOCAL_HOURS=%LOCAL_HOURS:~1,1%
set /a OFFSET=TIMESERVER_HOURS-LOCAL_HOURS
rem :: day of the week will be the modulus of 7 of local ansi date +1
rem :: we need need +1 because Monday will be calculated as 0
rem :: 1st jan 1601 was Monday
rem :: if abs(offset)>12 we are in different days with the time server
IF %OFFSET%0 GTR 120 set /a DOW=(ANSI_DATE+1)%%7+1
IF %OFFSET%0 LSS -120 set /a DOW=(ANSI_DATE-1)%%7+1
IF %OFFSET%0 LEQ 120 IF %OFFSET%0 GEQ -120 set /a DOW=ANSI_DATE%%7+1
rem echo Day of the week: %DOW%
endlocal & if "%~1" neq "" (set "%~1=%DOW%") else echo %DOW%
4..bat/jscript hybrid (must be saved as .bat):
@if (@x)==(@y) @end /***** jscript comment ******
@echo off
for /f %%d in ('cscript //E:JScript //nologo "%~f0"') do echo %%d
exit /b 0
***** end comment *********/
WScript.Echo((new Date).getDay());
5..bat/vbscript hybrid (must be saved as .bat)
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul
'& echo/
'& for /f %%w in ('cscript /nologo /E:vbscript %~dpfn0') do echo day of the week %%w
'& echo/
'& del /q "'.exe" >nul 2>&1
'& exit /b
WScript.Echo Weekday(Date)
WScript.Quit
6.powershell can be downloaded from microsoft.Available by default in everything form win7 and above:
@echo off
setlocal
for /f %%d in ('"powershell (Get-Date).DayOfWeek.Value__"') do set dow=%%d
echo day of the week : %dow%
endlocal
7.WMIC already used as an answer but just want to have a full reference.And with cleared <CR>
:
@echo off
setlocal
for /f "delims=" %%a in ('wmic path win32_localtime get dayofweek /format:list ') do for /f "delims=" %%d in ("%%a") do set %%d
echo day of the week : %dayofweek%
endlocal
9.Selfcompiled jscript.net (must be saved as .bat
):
@if (@X)==(@Y) @end /****** silent line that start jscript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
"%~n0.exe"
exit /b 0
****** end of jscript comment ******/
import System;
import System.IO;
var dt=DateTime.Now;
Console.WriteLine(dt.DayOfWeek);
I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
The solutions provided above will work in the most cases, but checking the scrollHeight and overflow is sometimes not enough and can fail for body and html elements as seen here: https://codepen.io/anon/pen/EvzXZw
function isScrollableY (element) {
return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--));
}
Note: elements with overflow: hidden
are also treated as scrollable (more info), so you might add a condition against that too if needed:
function isScrollableY (element) {
let style = window.getComputedStyle(element);
return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--))
&& style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden";
}
As far as I know this method only fails if the element has scroll-behavior: smooth
.
Explanation: The trick is, that the attempt of scrolling down and reverting it won't be rendered by the browser. The topmost function can also be written like the following:
function isScrollableY (element) {
// if scrollTop is not 0 / larger than 0, then the element is scrolled and therefore must be scrollable
// -> true
if (element.scrollTop === 0) {
// if the element is zero it may be scrollable
// -> try scrolling about 1 pixel
element.scrollTop++;
// if the element is zero then scrolling did not succeed and therefore it is not scrollable
// -> false
if (element.scrollTop === 0) return false;
// else the element is scrollable; reset the scrollTop property
// -> true
element.scrollTop--;
}
return true;
}
_x000D_
function isScrollableY (element) {
const style = window.getComputedStyle(element);
if (element.scrollHeight > element.clientHeight &&
style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden" &&
style["overflow"] !== "clip" && style["overflow-y"] !== "clip"
) {
if (element === document.scrollingElement) return true;
else if (style["overflow"] !== "visible" && style["overflow-y"] !== "visible") {
// special check for body element (https://drafts.csswg.org/cssom-view/#potentially-scrollable)
if (element === document.body) {
const parentStyle = window.getComputedStyle(element.parentElement);
if (parentStyle["overflow"] !== "visible" && parentStyle["overflow-y"] !== "visible" &&
parentStyle["overflow"] !== "clip" && parentStyle["overflow-y"] !== "clip"
) {
return true;
}
}
else return true;
}
}
return false;
}
body
has default margins: http://www.w3.org/TR/CSS2/sample.html
body { margin:0; } /* Remove body margins */
Or you could use this useful Global reset
* { margin:0; padding:0; box-sizing:border-box; }
If you want something less *
global than:
html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
some other CSS Reset:
http://yui.yahooapis.com/3.5.0/build/cssreset/cssreset-min.css
http://meyerweb.com/eric/tools/css/reset/
https://github.com/necolas/normalize.css/
http://html5doctor.com/html-5-reset-stylesheet/
…
yum -y install texlive
was not enough for my centos distro to get the latex command.
This site https://gist.github.com/melvincabatuan/350f86611bc012a5c1c6 contains additional packages. In particular:
yum -y install texlive texlive-latex texlive-xetex
was enough but the author also points out these as well:
yum -y install texlive-collection-latex
yum -y install texlive-collection-latexrecommended
yum -y install texlive-xetex-def
yum -y install texlive-collection-xetex
Only if needed:
yum -y install texlive-collection-latexextra
I like to use this;
$('#container').prop('outerHTML');
Use proper escaping: string.split("\\|")
Or, in Java 5+, use the helper Pattern.quote()
which has been created for exactly this purpose:
string.split(Pattern.quote("|"))
which works with arbitrary input strings. Very useful when you need to quote / escape user input.