Integrated Security
and User ID
\ Password
authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID
and Password
from your connection string:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect with specific credentials, remove Integrated Security
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code
scGetruntotals.CommandTimeout = 180;
Note : the parameter value is in seconds.
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)() ddl2.DataSource = sql2 ddl2.DataBind() End Sub
and it worked just fine
I had the same issue. Running exec sp_updatestats
did work sometimes, but not always. I decided to use the NOLOCK
statement in my queries to speed up the queries.
Just add NOLOCK
after your FROM clause, e.g.:
SELECT clicks.entryURL, clicks.entryTime, sessions.userID
FROM sessions, clicks WITH (NOLOCK)
WHERE sessions.sessionID = clicks.sessionID AND clicks.entryTime > DATEADD(day, -1, GETDATE())
Read the full article here.
If you store an object in session state, that object must be serializable.
edit:
In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.
First approach with Windows Service is not easy..
A long time ago, I wrote a C# service.
This is the logic of the Service class (tested, works fine):
namespace MyServiceApp
{
public class MyService : ServiceBase
{
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(30000D); // 30000 milliseconds = 30 seconds
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MyServiceApp.ServiceWork.Main(); // my separate static method for do work
}
public MyService()
{
this.ServiceName = "MyService";
}
// service entry point
static void Main()
{
System.ServiceProcess.ServiceBase.Run(new MyService());
}
}
}
I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.
Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.
Hope this helps!
After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.
This caused the app pool to give up and reply with the exception noted in the question.
Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.
after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.
With current Angular 4 and 5 versions, there is an IDE for that.
Go to eclipse market place any search for 'Angular'. You will see the IDE and install it.
After that restart eclipse and follow the welcome messages to choose preferences.
How to start using eclipse with angular projects?
Considering you already have angular project and you want to import it into eclipse.
go to file > import > choose Angular Project
and It would be better to have your projects in a separate working set so that you will not confuse it with other kind of (like java)projects.
With Angular IDE You will have a terminal window too.
To open this type terminal in eclipse search box(quick access) on the top right corner.
This code creates a nice vertical scrollbar for me in Firefox and Chrome:
#answerform {
position: absolute;
border: 5px solid gray;
padding: 5px;
background: white;
width: 300px;
height: 400px;
overflow-y: scroll;
}
_x000D_
<div id='answerform'>
badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
<br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
Here is a JS fiddle demo proving the above works.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary
Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype - Scopes a single bean definition to any number of object instances.
request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
Check following link. This would be helpful too..
In Parent Window:
function OpenChildAsPopup() {
var childWindow = window.open("ChildWindow.aspx", "_blank",
"width=200px,height=350px,left=200,top=100");
childWindow.focus();
}
function ChangeBackgroudColor() {
var para = document.getElementById('samplePara');
if (para !="undefied") {
para.style.backgroundColor = '#6CDBF5';
}
}
Parent Window HTML Markup:
<div>
<p id="samplePara" style="width: 350px;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p><br />
<asp:Button ID="Button1" Text="Open Child Window"
runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>
In Child Window:
// This will be called when the child window is closed.
window.onunload = function (e) {
opener.ChangeBackgroudColor();
//or you can do
//var para = opener.document.getElementById('samplePara');
//if (para != "undefied") {
// para.style.backgroundColor = '#6CDBF5';
//}
};
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
For most cases (long for floats, long long for double and long double):
long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll
There are a lot of ways to do so, for example:
in case you have not pushed the commit publicly yet:
git reset HEAD~1 --soft
That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man
In case you did push publicly (on a branch called 'master'):
git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )
revert commit normally and push
git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master
now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit
option:
git revert --no-commit 86b48ba (hash of the revert commit).
I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master
Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty()
method. This is generally a good idea when using for...in
loops:
var user = {};
function setUsers(data) {
for (var k in data) {
if (data.hasOwnProperty(k)) {
user[k] = data[k];
}
}
}
For anyone still experiencing this, I found that images served on Amazon S3 do not work for WhatsApp mobile app (both Android and iOS, but Mac desktop app was fine). It's very possible that our AWS settings cause this, but I noticed the pattern in other sites as well (e.g. this one with an og:image
hitting a domain like https://s3.amazonaws.com
).
There were no problems on any other platform I tried, just WhatsApp mobile apps. As soon as I pointed my <meta property="og:image" content="https://some-non-aws-location" />
to another public URL like a Google Drive file (shared publicly of course), it worked fine.
I also tried committing the image in our repo, which is hosted and deployed on AWS with a custom domain, and that didn't work either. So AWS still seems to be the culprit. Hope this helps someone!
found a way at http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx this does not require purchase of a pdf library
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:
...
var signature = Get(url); // base64_encoded signature received from server
var inputtext= "inputtext"; // this is main text signature was created for
bool result = VerifySignature(inputtext, signature);
...
private bool VerifySignature(string input, string signature)
{
var result = false;
using (var cps=new RSACryptoServiceProvider())
{
// converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
byte[] signatureBytes = Convert.FromBase64String(signature);
cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes );
}
return result;
}
Obligatory jQuery solution. Finds and sets the title
attribute to foo
. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
To start Jenkins from command line
Go to the directory where your war file is placed and run the following command:
java -jar jenkins.war
To stop
Ctrl + C
Build solution: Compiles code files (DLL and EXE) which are changed.
Rebuild: Deletes all compiled files and compiles them again irrespective if the code has changed or not.
Clean solution: Deletes all compiled files (DLL and EXE file).
You can see this YouTube video (Visual Studio Build vs. Rebuild vs. Clean (C# interview questions with answers)) where I have demonstrated the differences and below are visual representations which will help you to analyze the same in more detail.
The difference between Rebuild vs. (Clean + Build), because there seems to be some confusion around this as well:
The difference is the way the build and clean sequence happens for every project. Let’s say your solution has two projects, “proj1” and “proj2”. If you do a rebuild it will take “proj1”, clean (delete) the compiled files for “proj1” and build it. After that it will take the second project “proj2”, clean compiled files for “proj2” and compile “proj2”.
But if you do a “clean” and build”, it will first delete all compiled files for “proj1” and “proj2” and then it will build “proj1” first followed by “proj2”.
I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.
View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
I ran into the same problem a couple of years ago and funded the development of a plugin to help me in my work. I've released the plugin as open-source so others can benefit from it as well, and you can grab it on Github: https://github.com/eqcss/eqcss
There are a few ways we could apply different responsive styles based on what we can know about an element on the page. Here are a few element queries that the EQCSS plugin will let you write in CSS:
@element 'div' and (condition) {
$this {
/* Do something to the 'div' that meets the condition */
}
.other {
/* Also apply this CSS to .other when 'div' meets this condition */
}
}
So what conditions are supported for responsive styles with EQCSS?
px
%
px
%
px
%
px
%
Inside EQCSS element queries you can also use three special selectors that allow you to more specifically apply your styles:
$this
(the element(s) matching the query)$parent
(the parent element(s) of the element(s) matching the query)$root
(the root element of the document, <html>
)Element queries allow you to compose your layout out of individually responsive design modules, each with a bit of 'self-awareness' of how they are being displayed on the page.
With EQCSS you can design one widget to look good from 150px wide all the way up to 1000px wide, then you can confidently drop that widget into any sidebar in any page using any template (on any site) and
First of all, REST is not a religion and should not be approached as such. While there are advantages to RESTful services, you should only follow the tenets of REST as far as they make sense for your application.
That said, authentication and client side state do not violate REST principles. While REST requires that state transitions be stateless, this is referring to the server itself. At the heart, all of REST is about documents. The idea behind statelessness is that the SERVER is stateless, not the clients. Any client issuing an identical request (same headers, cookies, URI, etc) should be taken to the same place in the application. If the website stored the current location of the user and managed navigation by updating this server side navigation variable, then REST would be violated. Another client with identical request information would be taken to a different location depending on the server-side state.
Google's web services are a fantastic example of a RESTful system. They require an authentication header with the user's authentication key to be passed upon every request. This does violate REST principles slightly, because the server is tracking the state of the authentication key. The state of this key must be maintained and it has some sort of expiration date/time after which it no longer grants access. However, as I mentioned at the top of my post, sacrifices must be made to allow an application to actually work. That said, authentication tokens must be stored in a way that allows all possible clients to continue granting access during their valid times. If one server is managing the state of the authentication key to the point that another load balanced server cannot take over fulfilling requests based on that key, you have started to really violate the principles of REST. Google's services ensure that, at any time, you can take an authentication token you were using on your phone against load balance server A and hit load balance server B from your desktop and still have access to the system and be directed to the same resources if the requests were identical.
What it all boils down to is that you need to make sure your authentication tokens are validated against a backing store of some sort (database, cache, whatever) to ensure that you preserve as many of the REST properties as possible.
I hope all of that made sense. You should also check out the Constraints section of the wikipedia article on Representational State Transfer if you haven't already. It is particularly enlightening with regard to what the tenets of REST are actually arguing for and why.
I have to offer this as a better approach - you don't always have the luxury of an identity field:
UPDATE m
SET [status]=10
FROM (
Select TOP (10) *
FROM messages
WHERE [status]=0
ORDER BY [priority] DESC
) m
You can also make the sub-query as complicated as you want - joining multiple tables, etc...
Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages
table. It can be used to update the top N rows from any table, even if that table has no unique key at all.
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:
ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);
LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();
localServer.start();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509Certificate cert: chain) {
System.err.println(cert);
}
return false;
}
};
SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
trustStrategy, new AllowAllHostnameVerifier());
Scheme https = new Scheme("https", 443, sslsf);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
InetSocketAddress address = localServer.getServiceAddress();
HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
HttpGet httpget1 = new HttpGet("/random/100");
HttpResponse response1 = httpclient.execute(target1, httpget1);
System.err.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
HttpGet httpget2 = new HttpGet("/");
HttpResponse response2 = httpclient.execute(target2, httpget2);
System.err.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
localServer.stop();
}
Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.
Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.
[
[
Version: V1
Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
y:
f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e
Validity: [From: Sat Dec 11 14:48:35 CET 2004,
To: Tue Dec 09 14:48:35 CET 2014]
Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 41bafab3]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3
]
HTTP/1.1 200 OK
[
[
Version: V3
Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
public exponent: 65537
Validity: [From: Wed May 26 02:00:00 CEST 2010,
To: Sat May 26 01:59:59 CEST 2012]
Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[accessMethod: 1.3.6.1.5.5.7.48.1
accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]
...
]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...
I solved this by overriding the default Content-Type:
const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
...
});
Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.
for C use in gcc. #include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
The quickest fix is upgrate the pip. Did worked for me:
pip install --upgrade pip
This worked for me
/**
* Convert Date type to "YYYY/MM/DD" string
* - AKA ISO format?
* - It's logical and sortable :)
* - 20200227
* @param Date eg. new Date()
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
*/
static DateToYYYYMMDD(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
return DS
}
You can certainly add HH:MM something like this...
static DateToYYYYMMDD_HHMM(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
+ ' ' + ('0' + Date.getHours()).slice(-2)
+ ':' + ('0' + Date.getMinutes()).slice(-2)
return DS
}
If you're using MySQL, you can use
SELECT GREATEST(col1, col2 ...) FROM table
Swift 5 Very Easy way
//MARK:- First you need to encoded your arr or what ever object you want to save in UserDefaults
//in my case i want to save Picture (NMutableArray) in the User Defaults in
//in this array some objects are UIImage & Strings
//first i have to encoded the NMutableArray
let encodedData = NSKeyedArchiver.archivedData(withRootObject: yourArrayName)
//MARK:- Array save in UserDefaults
defaults.set(encodedData, forKey: "YourKeyName")
//MARK:- When you want to retreive data from UserDefaults
let decoded = defaults.object(forKey: "YourKeyName") as! Data
yourArrayName = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! NSMutableArray
//MARK: Enjoy this arrry "yourArrayName"
An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.
$output = array();
foreach( new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {
if ( $value->isFile() ) {
$output[] = array( $value->getMTime(), $value->getRealPath() );
}
}
usort ( $output, function( $a, $b ) {
return $a[0] > $b[0];
});
I converted the code in Anomie's answer here (copy-pasted above by suvish valsan) into Swift:
func fixOrientation() -> UIImage {
if self.imageOrientation == UIImageOrientation.Up {
return self
}
var transform = CGAffineTransformIdentity
switch self.imageOrientation {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI));
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));
case .Up, .UpMirrored:
break
}
switch self.imageOrientation {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGBitmapContextCreate(
nil,
Int(self.size.width),
Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage),
0,
CGImageGetColorSpace(self.CGImage),
UInt32(CGImageGetBitmapInfo(self.CGImage).rawValue)
)
CGContextConcatCTM(ctx, transform);
switch self.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height,self.size.width), self.CGImage);
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width,self.size.height), self.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = CGBitmapContextCreateImage(ctx)
let img = UIImage(CGImage: cgimg!)
return img;
}
(I replaced all occurencies of the parameter image
with self
, because my code is an extension on UIImage
).
EDIT: Swift 3 version.
The method returns an optional, because many of the intermediate calls can fail and I don't like to use !
.
func fixOrientation() -> UIImage? {
guard let cgImage = self.cgImage else {
return nil
}
if self.imageOrientation == UIImageOrientation.up {
return self
}
let width = self.size.width
let height = self.size.height
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: width, y: height)
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.rotated(by: 0.5*CGFloat.pi)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: height)
transform = transform.rotated(by: -0.5*CGFloat.pi)
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
guard let colorSpace = cgImage.colorSpace else {
return nil
}
guard let context = CGContext(
data: nil,
width: Int(width),
height: Int(height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue)
) else {
return nil
}
context.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))
default:
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
}
// And now we just create a new UIImage from the drawing context
guard let newCGImg = context.makeImage() else {
return nil
}
let img = UIImage(cgImage: newCGImg)
return img;
}
(Note: Swift 3 version odes compile under Xcode 8.1, but haven't tested it actually works. There might be a typo somewhere, mixed up width/height, etc. Feel free to point/fix any errors).
Although solution to this problem is hardly coded in regeneration of your .htaccess file; indeed it din't worked for most of you specially when the site is migrated to some new server.
Let's dive into some basics.
Let's assume that for most of us, WordPress environment is running on a PHP server APACHE where this server is controlling most of our environment's initial dependencies. Meanwhile .htaccess generation is also mainly dependent on Apache configurations.
So if that been said, the contribution of .htaccess creation conflict mainly occurs when a WordPress website is migrated from a server running the WordPress environment on old version of Apache and PHP to a newer version of PHP and Apache.
Because dependencies of nrwer and older versions are different that's why the newer version of Apache2 won't allow the .htaccess directives to create a .htaccess file by default; because of which we have to manually set the WordPress website's root directory permissions from "AllowOverride None" to "AllowOverride All".
Comparatively, AllowOverride directive is used to allow the use of .htaccess within the web server to allow overriding of the Apache config on a per directory basis.
Use the following fix to change the apache2.conf directory permission settings:
Look at Linked List as a data structure. It's mechanism to represent self-aggregation in OOD. And you may think of it as real world object (for some people it is reality)
Let me just add a warning to all the existing answers:
When using the SELECT ... FROM syntax, you should keep in mind that it is proprietary syntax for T-SQL and is non-deterministic. The worst part is, that you get no warning or error, it just executes smoothly.
Full explanation with example is in the documentation:
Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.
I'm not sure what your first question is, but if you want to save a dictionary to file you should use the json
library. Look up the documentation of the loads and puts functions.
For scoop users:
"terminal.integrated.shell.windows": "C:\\Users\\[YOUR-NAME]\\scoop\\apps\\git\\current\\usr\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": [
"-l",
"-i"
],
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
Java versions before version 7 allow for these three combinations of try-catch-finally...
try - catch
try - catch - finally
try - finally
finally
block will be always executed no matter of what's going on in the try
or/and catch
block. so if there is no catch
block, the exception won't be handled here.
However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.
- Java try block must be followed by either catch or finally block.
- For each try block there can be zero or more catch blocks, but only one finally block.
- The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
This is quite old question, but I have had the exact same annoying issue where everything worked fine for Chrome/Edge (with object-fit property) but same css property did not work in IE11 (since its unsupported in IE11), I ended up using HTML5 "figure" element which solved all my problems.
I personally did not use the outer DIV tag since that did not help at all in my case, so I avoided the outer DIV and simply replaced with 'figure' element.
The below code forces the image to reduce/scale down nicely (without changing the original aspect ratio).
<figure class="figure-class">
<img class="image-class" src="{{photoURL}}" />
</figure>
and css classes:
.image-class {
border: 6px solid #E8E8E8;
max-width: 189px;
max-height: 189px;
}
.figure-class {
width: 189px;
height: 189px;
}
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
There's a plugin out there that extends jQuery's getScript method. Allows for asynchronous and synchronous loading and uses jQuery's caching mechanism. Full disclosure, I wrote this. Please feel free to contribute if you find a better method.
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
undo git rm
git rm file # delete file & update index
git checkout HEAD file # restore file & index from HEAD
undo git rm -r
git rm -r dir # delete tracked files in dir & update index
git checkout HEAD dir # restore file & index from HEAD
undo git rm -rf
git rm -r dir # delete tracked files & delete uncommitted changes
not possible # `uncommitted changes` can not be restored.
Uncommitted changes
includes not staged changes
, staged changes but not committed
.
the window
contains everything, so you can call window.screen
and window.document
to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/
You can also see the contents of the object in firebug/dev tools like this:
console.dir(window);
console.dir(document);
console.dir(screen);
window
is the root of everything, screen
just has screen dimensions, and document
is top DOM object. so you can think of it as window
being like a super-document
...
Steps:
1)Add the required permissions in the Manifest.xml
file.
<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
2)Create a listener for the phone state changes.
public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
//wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
//when this state occurs, and your flag is set, restart your app
Intent i = context.getPackageManager().getLaunchIntentForPackage(
context.getPackageName());
//For resuming the application from the previous state
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//Uncomment the following if you want to restart the application instead of bring to front.
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
}
}
}
3)Initialize the listener in your OnCreate
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP
with FLAG_ACTIVITY_SINGLE_TOP
Reference this Answer
As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way
1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"
password was also updated successfully.
Is this what your after?
my $string = 'USCAGoleta9311734.5021-120.1287855805';
my $first_two_chars = substr $string, 0, 2;
ref: substr
info frame
to show the stack frame info
To read the memory at given addresses you should take a look at x
x/x $esp
for hex x/d $esp
for signed x/u $esp
for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip
etc.
List<String> list = new ArrayList<String>(listOfTopicAuthors);
Either of the latter two, since val
could potentially be of a type that defines __eq__()
to return true when passed None
.
TL;DR: also ensure that your id_rsa.pub
is in ascii / UTF-8.
I had the same problem, however the accepted answer alone did not work because of the text encoding, which was an additional, easy-to-miss issue.
When I run
ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub
in Windows PowerShell, it saves the output to id_rsa.pub
in UTF-16 LE BOM encoding, not in UTF-8. This is a property of some installations of PowerShell, which was discussed in Using PowerShell to write a file in UTF-8 without the BOM. Apparently, OpenSSH does not recognise the former text encoding and produces an identical error:
key_load_public: invalid format
Copying and pasting the output of ssh-keygen -f ~/.ssh/id_rsa -y
into a text editor is the simplest way to solve this.
P.S. This could be an addition to the accepted answer, but I don't have enough karma to comment here yet.
I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.
Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.
NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)
A lot of the given answers fail on one or more of:
Here's what I wrote:
static int countMatches(Pattern pattern, String string)
{
Matcher matcher = pattern.matcher(string);
int count = 0;
int pos = 0;
while (matcher.find(pos))
{
count++;
pos = matcher.start() + 1;
}
return count;
}
Example call:
Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2
If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL
flag:
Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click
wb_apple.Document.GetElementById("phoneNumber").Focus()
wb_apple.Document.GetElementById("phoneNumber").InnerText = tb_phonenumber.Text
wb_apple.Document.GetElementById("reservationCode").Focus()
wb_apple.Document.GetElementById("reservationCode").InnerText = tb_regcode.Text
'SendKeys.Send("{Tab}{Tab}{Tab}")
'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName("a")
'If Element.OuterHtml.Contains("iReserve.sms.submitButtonLabel") Then
'Element.InvokeMember("click")
'Exit For
' End If
'Next Element
wb_apple.Document.GetElementById("smsPageForm").Focus()
wb_apple.Document.GetElementById("smsPageForm").InvokeMember("submit")
End Sub
I like Imagemagick. http://www.imagemagick.org/script/api.php
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
. "$PSScriptRoot\MyFunctions.ps1"
MyA1Func
Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.
P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).
You can use
value.ToString(CultureInfo.InvariantCulture)
to get exact double value without putting precision.
You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.
inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024]; //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
System.out.println(read);
// Your code to handle the data
}
Like @BillKotsias, I used inheritance, and it worked for me.
I changed this mess (which required all the boost headers in my declaration *.h)
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
typedef boost::accumulators::accumulator_set<float,
boost::accumulators::features<
boost::accumulators::tag::median,
boost::accumulators::tag::mean,
boost::accumulators::tag::min,
boost::accumulators::tag::max
>> VanillaAccumulator_t ;
std::unique_ptr<VanillaAccumulator_t> acc;
into this declaration (*.h)
class VanillaAccumulator;
std::unique_ptr<VanillaAccumulator> acc;
and the implementation (*.cpp) was
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
class VanillaAccumulator : public
boost::accumulators::accumulator_set<float,
boost::accumulators::features<
boost::accumulators::tag::median,
boost::accumulators::tag::mean,
boost::accumulators::tag::min,
boost::accumulators::tag::max
>>
{
};
log4j.jar
filelog4j.jar
file to build pathCall logger by:
private static org.apache.log4j.Logger log
= Logger.getLogger(<class-where-this-is-used>.class);
if log4j properties does not exist, create new file log4j.properties file new file in bin directory:
/workspace/projectdirectory/bin/
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%t %-5p %c{2} - %m%n
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
declarative program is just a data for its some more-or-less "universal" imperative implementation/vm.
pluses: specifying just a data, in some hardcoded (and checked) format, is simpler and less error-prone than specifying variant of some imperative algorithm directly. some complex specifications just cant be written directly, only in some DSL form. best and freq used in DSLs data structures is sets and tables. because you not have dependencies between elements/rows. and when you havent dependencies you have freedom to modify and ease of support. (compare for example modules with classes - with modules you happy and with classes you have fragile base class problem) all goods of declarativeness and DSL follows immediately from benefits of that data structures (tables and sets). another plus - you can change implementation of declarative language vm, if DSL is more-or-less abstract (well designed). make parallel implementation, for example. or port it to other os etc. all good specifed modular isolating interfaces or protocols gives you such freedom and easyness of support.
minuses: you guess right. generic (and parameterized by DSL) imperative algorithm/vm implementation may be slower and/or memory hungry than specific one. in some cases. if that cases is rare - just forget about it, let it be slow. if it's frequient - you always can extend your DSL/vm for that case. somewhere slowing down all other cases, sure...
P.S. Frameworks is half-way between DSL and imperative. and as all halfway solutions ... they combines deficiences, not benefits. they not so safe AND not so fast :) look at jack-of-all-trades haskell - it's halfway between strong simple ML and flexible metaprog Prolog and... what a monster it is. you can look at Prolog as a Haskell with boolean-only functions/predicates. and how simple its flexibility is against Haskell...
The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:
IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
SELECT Division =
CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND @Numerator != 0 AND @Numerator is NOT NULL THEN
@Numerator / @Denominator
ELSE
0
END
RETURN
END
GO
Exec ##fn_Divide 6,4
This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.
A SELECT INTO
statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found
exception. If it returns more than 1 row, you'll get a too_many_rows
exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO
statement here.
Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID
column in both tables)
BEGIN
FOR rec IN (SELECT EMPLOYEE.EMPID,
EMPLOYEE.ENAME,
EMPLOYEE.DESIGNATION,
EMPLOYEE.SALARY,
DEPARTMENT.DEPT_NAME
FROM EMPLOYEE,
DEPARTMENT
WHERE employee.departmentID = department.departmentID
AND EMPLOYEE.SALARY > 3000)
LOOP
DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
END LOOP;
END;
I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output
like this and would not depend on anyone seeing data that you write to the dbms_output
buffer.
You can filter the array and then just pick the first element, as shown in Find Object with Property in Array.
Or you define a custom extension
extension Array {
// Returns the first element satisfying the predicate, or `nil`
// if there is no matching element.
func findFirstMatching<L : BooleanType>(predicate: T -> L) -> T? {
for item in self {
if predicate(item) {
return item // found
}
}
return nil // not found
}
}
Usage example:
struct T {
var name : String
}
let array = [T(name: "bar"), T(name: "baz"), T(name: "foo")]
if let item = array.findFirstMatching( { $0.name == "foo" } ) {
// item is the first matching array element
} else {
// not found
}
In Swift 3 you can use the existing first(where:)
method
(as mentioned in a comment):
if let item = array.first(where: { $0.name == "foo" }) {
// item is the first matching array element
} else {
// not found
}
With JUnit5 and @DataJpaTest
test will look like (kotlin code):
@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {
@Autowired
lateinit var entityManager: TestEntityManager
@Autowired
lateinit var myEntityRepository: MyEntityRepository
@Test
fun shouldSaveEntity() {
// when
val savedEntity = myEntityRepository.save(MyEntity(1, "test")
// then
Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
}
}
You could use TestEntityManager
from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
package in order to validate entity state.
Another solution is to borrow this indent
function, for use with the ElementTree library that's built in to Python since 2.5.
Here's what that would look like:
from xml.etree import ElementTree
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
root = ElementTree.parse('/tmp/xmlfile').getroot()
indent(root)
ElementTree.dump(root)
Update for iOS9.2.1 and Xcode 7.2.1
If you get this error when building to a device in Xcode:
On your device, tap the app icon that would have just been added from your attempt at building the app and you should see this:
Next, on your device, go to Settings --> General --> Device Management, and you will see this page:
Select the profile you are using with Xcode, and you should see this page:
Click Trust "[email protected]" then click Trust on the next popup.
Go back to Xcode and re-run your project and it should build the app to your device.
You can get accurate Carousel effect using iCarousel SDK.
You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from https://github.com/nicklockwood/iCarousel and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).
If you haven't added Objective-C code to a Swift project before, follow these steps:
Swift 3 Sample Code:
override func viewDidLoad() {
super.viewDidLoad()
let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
carousel.dataSource = self
carousel.type = .coverFlow
view.addSubview(carousel)
}
func numberOfItems(in carousel: iCarousel) -> Int {
return 10
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let imageView: UIImageView
if view != nil {
imageView = view as! UIImageView
} else {
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
}
imageView.image = UIImage(named: "example")
return imageView
}
You can write a simple readable solution to this by using both map
and filter
:
const nanoIndexes = Cars
.map((car, i) => car === 'Nano' ? i : -1)
.filter(index => index !== -1);
EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:
const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);
I know this is a little off the OPs original request but I came across this while looking for a way to use Invoke-WebRequest against a site requiring basic authentication.
The difference is, I did not want to record the password in the script. Instead, I wanted to prompt the script runner for credentials for the site.
Here's how I handled it
$creds = Get-Credential
$basicCreds = [pscredential]::new($Creds.UserName,$Creds.Password)
Invoke-WebRequest -Uri $URL -Credential $basicCreds
The result is the script runner is prompted with a login dialog for the U/P then, Invoke-WebRequest is able to access the site with those credentials. This works because $Creds.Password is already an encrypted string.
I hope this helps someone looking for a similar solution to the above question but without saving the username or PW in the script
I had a similar problem recently and found an interesting solution. Basically I needed to deserialize following nested JSON String into my POJO:
"{\"restaurant\":{\"id\":\"abc-012\",\"name\":\"good restaurant\",\"foodType\":\"American\",\"phoneNumber\":\"123-456-7890\",\"currency\":\"USD\",\"website\":\"website.com\",\"location\":{\"address\":{\"street\":\" Good Street\",\"city\":\"Good City\",\"state\":\"CA\",\"country\":\"USA\",\"postalCode\":\"12345\"},\"coordinates\":{\"latitude\":\"00.7904692\",\"longitude\":\"-000.4047208\"}},\"restaurantUser\":{\"firstName\":\"test\",\"lastName\":\"test\",\"email\":\"[email protected]\",\"title\":\"server\",\"phone\":\"0000000000\"}}}"
I ended up using regex to remove the open quotes from beginning and the end of JSON and then used apache.commons unescapeJava() method to unescape it. Basically passed the unclean JSON into following method to get back a cleansed one:
private String removeQuotesAndUnescape(String uncleanJson) {
String noQuotes = uncleanJson.replaceAll("^\"|\"$", "");
return StringEscapeUtils.unescapeJava(noQuotes);
}
then used Google GSON to parse it into my own Object:
MyObject myObject = new.Gson().fromJson(this.removeQuotesAndUnescape(uncleanJson));
No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE
permission and just make a connected method
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
You can also use requestRouteToHost
if you have a particualr host and connection type (wifi/mobile) in mind.
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
for more detail go here
You can do it with java.nio.charset.Charset.
import java.nio.charset.Charset;
public class StringUtils {
public static boolean isPureAscii(String v) {
return Charset.forName("US-ASCII").newEncoder().canEncode(v);
// or "ISO-8859-1" for ISO Latin 1
// or StandardCharsets.US_ASCII with JDK1.7+
}
public static void main (String args[])
throws Exception {
String test = "Réal";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
test = "Real";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
/*
* output :
* Réal isPureAscii() : false
* Real isPureAscii() : true
*/
}
}
Navigate to the base directory of your git repo and execute the following command:
echo '\\.*' >> .gitignore
All dot files will be ignored, including that pesky .DS_Store if you're on a mac.
If you run the above as they are, they will appear to run simultaenously.
Here's some test code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function () {
$('#first').animate({ width: 200 }, 200);
$('#second').animate({ width: 600 }, 200);
});
</script>
<div id="first" style="border:1px solid black; height:50px; width:50px"></div>
<div id="second" style="border:1px solid black; height:50px; width:50px"></div>
A simple, newbie friendly way for looking into a file:
git gui browser <branch>
which lets you explore the contents of any file.
It's also there in the File menu of git gui
. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.
It's a function which is a member of a class:
class C:
def my_method(self):
print("I am a C")
c = C()
c.my_method() # Prints("I am a C")
Simple as that!
(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)
What about
30.seconds.ago
2.days.ago
Or something else you were shooting for?
Easiest & Responsive.
<video src="full.mp4" autoplay muted loop></video>
<style>
video {
height: 100vh;
width: 100%;
object-fit: fill; // use "cover" to avoid distortion
position: absolute;
}
</style>
in 2020, this behavior still present with VS2019. (even if I clean projects from the solution explorer in VS2019, this not solves the problem)
The solution that worked for me was to open the folder of the project, and manually remove the \bin and \obj directories.
On Windows:
tl;dr: Try opening the file again.
Our system was suffering this problem, and it definitely wasn't a permissions issue, since the program itself would be able to open the database as writable from many threads most of the time, but occasionally (only on Windows, not on OSX), a thread would get these errors even though all the other threads in the program were having no difficulties.
We eventually discovered that the threads that were failing were only those that were trying to open the database immediately after another thread had closed it (within 3 ms). We speculated that the problem was due to the fact that Windows (or the sqlite implementation under windows) doesn't always immediately clean up up file resources upon closing of a file. We got around this by running a test write query against the db upon opening (e.g., creating then dropping a table with a silly name). If the create/drop failed, we waited for 50 ms and tried again, repeating until we succeeded or 5 seconds elapsed.
It worked; apparently there just needed to be enough time for the resources to flush out to disk.
This is exactly what I needed for my MVC site configuration!
I added a little modification to the OnException
method to handle multiple HandleErrorAttribute
instances, as suggested by Atif Aziz:
bear in mind that you may have to take care that if multiple
HandleErrorAttribute
instances are in effect then duplicate logging does not occur.
I simply check context.ExceptionHandled
before invoking the base class, just to know if someone else handled the exception before current handler.
It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.
Hope it is useful:
public override void OnException(ExceptionContext context)
{
bool exceptionHandledByPreviousHandler = context.ExceptionHandled;
base.OnException(context);
Exception e = context.Exception;
if (exceptionHandledByPreviousHandler
|| !context.ExceptionHandled // if unhandled, will be logged anyhow
|| RaiseErrorSignal(e) // prefer signaling, if possible
|| IsFiltered(context)) // filtered?
return;
LogException(e);
}
Everyone has pretty much answered this but here's a way you can remember what's what
Let will always say the same think of "let" as let this work for once and always as for "var" variable's can always change hence them being called variable's
As per the documentation, these are just synonyms. size()
is there to be consistent with other STL containers (like vector
, map
, etc.) and length()
is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length()
is there to make things more readable.
In java you can use setFetchSource like this :
client.prepareSearch(index).setTypes(type)
.setFetchSource(new String[] { "field1", "field2" }, null)
from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.
Good luck.
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
I use the counter variable like Fink suggests. If you want For Each and to pass ByRef (which can be more efficient for long strings) you have to cast your element as a string using CStr
Sub Example()
Dim vItm As Variant
Dim aStrings(1 To 4) As String
aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"
For Each vItm In aStrings
do_something CStr(vItm)
Next vItm
End Sub
Function do_something(ByRef sInput As String)
Debug.Print sInput
End Function
Straight out of the documentation for collections.OrderedDict
:
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
Adapted to the example in the original post:
>>> l=[2,3,1,4,5]
>>> OrderedDict(sorted(enumerate(l), key=lambda x: x[1])).keys()
[2, 0, 1, 3, 4]
See http://docs.python.org/library/collections.html#collections.OrderedDict for details.
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
Follow these steps
1>Download the *.jar file from here .
2>Put the *.jar file into the folder eclipse/dropins/ and Restart eclipse.
3>In the top right of eclipse, click the DDMS icon.
4>Select the proper emulator in the left panel.
5In the File Explorer tab on the main panel, go to /data/data/[YOUR.APP.NAMESPACE]/databases.
6>Underneath the DDMS icon, there should be a new blue icon of a Database light up when you select your database. Click it and you will see a Questoid Sqlite Manager tab open up to view your data.
*Note: If the database doesn't light up, it may be because your database doesn't have a *.db file extension. Be sure your database is called [DATABASE_NAME].db
*Note: if you want to use a DB without .db-Extension:
-Download this Questoid SqLiteBrowser: Download fro here.
-Unzip and put it into eclipse/dropins (not Plugins).
-Check this for more information Click here.
Here is the ZIP file that I had downloaded: mysql-5.7.15-winx64.zip
Here are the steps to start MYSQL Server (mysql-5.7.15-winx64) for the first time on Windows:
mysqld --initialize-insecure
or mysqld --initialize
depending on whether you want the server to generate a random initial password for the 'root'@'localhost' account.mysqld --console
You can see the start-up logs being printed.mysql -u root -p
. When prompted, Enter password if it has been set or else just hit "Enter" button to connectIf you use bootstrap just add form-control
class. For example:
class="form-control"
Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.
Answering to your question about standard I can cite the C++ Standard §8.3.2/4:
There shall be no references to references, no arrays of references, and no pointers to references.
If you're using it in several different places, you should turn it into a plugin.
jQuery.fn.fadeOutAndRemove = function(speed){
$(this).fadeOut(speed,function(){
$(this).remove();
})
}
And then:
// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');
Shorter version:
import inspect
def f1(): f2()
def f2():
print 'caller name:', inspect.stack()[1][3]
f1()
(with thanks to @Alex, and Stefaan Lippen)
I'm new to Android development and I do this:
1) Create a class:
import android.util.Log; public final class Debug{ private Debug (){} public static void out (Object msg){ Log.i ("info", msg.toString ()); } }
When you finish the project delete the class.
2) To print a message to the LogCat write:
Debug.out ("something");
3) Create a filter in the LogCat and write "info" in the input "by Log Tag". All your messages will be written here. :)
Tip: Create another filter to filter all errors to debug easily.
You can configure it with the "XAMPP Shell" (command prompt). Open the shell and execute this command:
mysqladmin.exe -u root password secret
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
Class.cast()
is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class
objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).
It is not similar to reinterpret_cast
, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).
The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>()
with a reference type in Java (remember: Java has runtime type information).
Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).
If you are early into the development cycle you can try this -
Remove/comment that model and all its usages. Apply migrations. That would delete that model and then add the model again, run migrations and you have a clean model with the new field added.
If your compiler supports C++0x and using it is an option for you, then the new standard <random>
header is likely to meet your needs. It has a high quality uniform_int_distribution
which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.
Here is code that generates a million random int
s uniformly distributed in [-57, 365]. I've used the new std <chrono>
facilities to time it as you mentioned performance is a major concern for you.
#include <iostream>
#include <random>
#include <chrono>
int main()
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::duration<double> sec;
Clock::time_point t0 = Clock::now();
const int N = 10000000;
typedef std::minstd_rand G;
G g;
typedef std::uniform_int_distribution<> D;
D d(-57, 365);
int c = 0;
for (int i = 0; i < N; ++i)
c += d(g);
Clock::time_point t1 = Clock::now();
std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
return c;
}
For me (2.8 GHz Intel Core i5) this prints out:
2.10268e+07 random numbers per second.
You can seed the generator by passing in an int to its constructor:
G g(seed);
If you later find that int
doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution
like so (e.g. to long long
):
typedef std::uniform_int_distribution<long long> D;
If you later find that the minstd_rand
isn't a high enough quality generator, that can also easily be swapped out. E.g.:
typedef std::mt19937 G; // Now using mersenne_twister_engine
Having separate control over the random number generator, and the random distribution can be quite liberating.
I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand
) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:
min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001
(The x_
prefix refers to "expected")
You are probably missing the viewport meta tag in the html head:
<meta name="viewport" content="width=device-width, initial-scale=1">
Without it the device assumes and sets the viewport to full size.
More info here.
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
$("#availability option:selected").text();
This will give you the text value of your dropdown list. You can also use .val() instead of .text() depending on what you're looking to get. Follow the link to the jQuery documentation and examples.
sed
is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.
There are various versions of sed
with different levels of support for command line options and language features.
awk
is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if
/else
, while
, do
/while
and for
(C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf
and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk
.
GNU awk
(gawk
) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk
including mawk
and nawk
.
Both programs use regular expressions for selecting and processing text.
I would tend to use sed
where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):
sed 's/-\([0-9.]\+\)/(\1)/g' inputfile
I would use awk
when the text looks more like rows and columns or, as awk
refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:
awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile
Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled
by JS only. To do so, just move the script behind the <form>
and call checkform();
once.
The old code for asking location won't work in iOS 8. You can try this method for location authorization:
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}
}
Python
webdriver.get_screenshot_as_file(filepath)
The above method will take a screenshot and also store it as a file in the location provided as a parameter.
I use this simple function for JQuery based project
var pointerEventToXY = function(e){
var out = {x:0, y:0};
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
};
example:
$('a').on('mousedown touchstart', function(e){
console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})
hope this will be usefull for you ;)
If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:
import subprocess
command = ["ls", "-l"]
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
success = True
except subprocess.CalledProcessError as e:
output = e.output.decode()
success = False
print(output)
This is Python 2 and 3 compatible.
If your command is a string rather than an array, prefix this with:
import shlex
command = shlex.split(command)
encode it with JSON
No need to load up the bloated ActiveSupport or roll your own, you can use Rack::Utils.build_query
and Rack::Utils.build_nested_query
. Here's a blog post that gives a good example:
require 'rack'
Rack::Utils.build_query(
authorization_token: "foo",
access_level: "moderator",
previous: "index"
)
# => "authorization_token=foo&access_level=moderator&previous=index"
It even handles arrays:
Rack::Utils.build_query( {:a => "a", :b => ["c", "d", "e"]} )
# => "a=a&b=c&b=d&b=e"
Rack::Utils.parse_query _
# => {"a"=>"a", "b"=>["c", "d", "e"]}
Or the more difficult nested stuff:
Rack::Utils.build_nested_query( {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}] } )
# => "a=a&b[][c]=c&b[][d]=d&b[][e]=e&b[][f]=f"
Rack::Utils.parse_nested_query _
# => {"a"=>"a", "b"=>[{"c"=>"c", "d"=>"d", "e"=>"e", "f"=>"f"}]}
I had the same issue. However making the view 1px didn't seem to work on my original Nexus 7. I noticed that the screen density was 213 which is less than the 240 used in xhdpi. So it was thinking the device was an mdpi density.
My solution was to make it so the dimens
folder had a dividerHeight
parameter. I set it to 2dp
in the values-mdpi
folder but 1dp
in the values-hdpi
etc folders.
Here is an example to do that
cd /yourprojects/project-acme
git checkout efc11170c78 .
I used
Assert.IsTrue(myObject is ImyInterface);
for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.
Example:
Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ","; //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);
I got this error because I didn't specify the correct programmer in the avrdude command line. You have to specify "-c arduino" if you are using an Arduino board.
This example command reads the status of the hfuse:
avrdude -c arduino -P /dev/ttyACM0 -p atmega328p -U hfuse:r:-:h
If you are able to jump on breakpoints, it is ok to Reset Perspective.
On Eclipse Version: Luna Service Release 2 (4.4.2) Build id: 20150219-0600 I notived that not only the Variable View was empty, but also the buttons to navigate the execution (F5, F6, F8 functionality buttons) were disabled. In this case, go to Debug View, right click to the row with the yellow pause symbol, and choose an option like "Resume". On the next breakpoint, Variable View will be automagically fullfilled and execution navigation buttons will be enabled. Can't explain why
import pandas as pd
Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:
for ch in mystr:
code = ord(ch)
or the slightly faster:
for code in map(ord, mystr):
you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:
for code in mystr.encode('ascii'):
and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes
object (bytes
is an alias for str
, which iterates by character), but they do have bytearray
:
# If mystr is definitely str, not unicode
for code in bytearray(mystr):
# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):
Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str
to get its ASCII codes using map(ord, mystr)
starts off taking about twice as long for a len
10 str
than using bytearray(mystr)
on Py2 or mystr.encode('ascii')
on Py3, and as the str
gets longer, the multiplier paid for map(ord, mystr)
rises to ~6.5x-7x.
The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str
would have a proportionately large temporary bytes
/bytearray
, but unless this forces you into page thrashing, this isn't likely to matter.
I prefer ^[-+]?([1-9]\d*|0)$
because ^[-+]?[0-9]+$
allows the string starting with 0
.
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
class TestRE(unittest.TestCase):
def test_int(self):
self.assertFalse(RE_INT.match('+'))
self.assertFalse(RE_INT.match('-'))
self.assertTrue(RE_INT.match('1'))
self.assertTrue(RE_INT.match('+1'))
self.assertTrue(RE_INT.match('-1'))
self.assertTrue(RE_INT.match('0'))
self.assertTrue(RE_INT.match('+0'))
self.assertTrue(RE_INT.match('-0'))
self.assertTrue(RE_INT.match('11'))
self.assertFalse(RE_INT.match('00'))
self.assertFalse(RE_INT.match('01'))
self.assertTrue(RE_INT.match('+11'))
self.assertFalse(RE_INT.match('+00'))
self.assertFalse(RE_INT.match('+01'))
self.assertTrue(RE_INT.match('-11'))
self.assertFalse(RE_INT.match('-00'))
self.assertFalse(RE_INT.match('-01'))
self.assertTrue(RE_INT.match('1234567890'))
self.assertTrue(RE_INT.match('+1234567890'))
self.assertTrue(RE_INT.match('-1234567890'))
If I understand correctly you want to exclude files from the vscode fuzzy finder. If that is the case, I am guessing the above answers are for older versions of vscode. What worked for me is adding:
"files.exclude": {
"**/directory-you-want-to-exclude": true,
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
}
to my settings.json
. This file can be opened through File
>Preferences
>Settings
Solving this using Vim editor
cd <path_to_your_directory>
). Ex: cd /home/vineeshvs/work
.vim <file_name>
). Ex: vim myfile.txt
.:set hlsearch
):<line_number>
). Ex: :53
in Vim editor after pressing ESC button once.:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc
). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc
after pressing ESC button once). This process is interactive. You may give y
to replace the tab with spaces and n
to skip a particular replacement. Press ESC when you are done with the required replacements.The CSS below stops users from being able to select text.
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */
To target IE9 downwards the html attribute unselectable
must be used instead:
<p unselectable="on">Test Text</p>
You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.
To redirect to a simple 404 not found page for a specific location:
location /my_blog {
error_page 404 /blog_article_not_found.html;
}
A site wide 404 page:
server {
listen 80;
error_page 404 /website_page_not_found.html;
...
You can append standard error codes together to have a single page for several types of errors:
location /my_blog {
error_page 500 502 503 504 /server_error.html
}
To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:
upstream server2 {
server 10.0.0.1:80;
}
server {
location /my_blog {
error_page 404 @try_server2;
}
location @try_server2 {
proxy_pass http://server2;
}
The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.
To find the Unix Timestamp in seconds:
moment().unix()
The documentation is your friend. :)
For version 2.3 this works and it will get you the socket too, it seems to me that socketIo is changing too fast and to much with to little readable documentation after using it for a while.
ioSite.of('/').in(roomId).clients((error, clients) => {
if (error) throw error;
for (var i=0;i<clients.length;i++) {
clientId=clients[i];
console.log(clientId);
// load the socket of your namespace
var socket=ioSite.of('/').in(roomId).connected[clientId]
console.log(socket.constructor.name);
console.log(socket.id);
}
});
still this does not feel right, as I have always this feeling with socket Io somehow
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);
You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);
You just have to define the property below inside the activity element in your AndroidManifest.xml
file. It will restrict your orientation to portrait.
android:screenOrientation="portrait"
Example:
<activity
android:name="com.example.demo_spinner.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
if you want this to apply to the whole app define the property below inside the application tag like so:
<application>
android:screenOrientation="sensorPortrait"
</application>
Additionaly, as per Eduard Luca's comment below, you can also use screenOrientation="sensorPortrait"
if you want to enable rotation by 180 degrees.
=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)
I use this if my Lookup_Value
needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value
is "Eastbay District", but the Table_Array
list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".
I hope this helps!
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
try this:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// only for gingerbread and newer versions
}
This is working for me
string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();
If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function
textscan()
Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.
Include the port number with the IP address.
For example:
http://19.18.20.101:5566
where 5566 is the port number.
If your constraint is on a user type, then don't forget to see if there is a Default Constraint
, usually something like DF__TableName__ColumnName__6BAEFA67
, if so then you will need to drop the Default Constraint
, like this:
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
For more info see the comments by the brilliant Aaron Bertrand on this answer.
I had this problem and spent a few hours trying to fix it. I fixed the prefix error by changing the path but I still had an encoding import error. This was fixed by restarting my computer.
A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
The AWS-provided tools are not useful because they are not comprehensive.
In my own quest to mitigate this problem and pull a list of all of my AWS resources, I found this: https://github.com/JohannesEbke/aws_list_all
I have not tested it yet, but it looks legit.
Pressing ctrl+M causes the ? Tab key to move focus instead of inserting a ? Tab character.
Turn it off by pressing the shortcut again.
toggle tab key moves focus
.Remove Keybinding
.Instead of parsing it manually it's better to use pathinfo function:
$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];
html {
overflow-x: hidden;
margin-right: calc(-1 * (100vw - 100%));
}
Example. Click "change min-height" button.
With calc(100vw - 100%)
we can calculate the width of the scrollbar (and if it is not displayed, it will be 0). Idea: using negative margin-right, we can increase the width of <html>
to this width. You will see a horizontal scroll bar — it should be hidden using overflow-x: hidden
.
As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.
In here I am adding on matrix A
1 2 3
4 5 6
with a row
7 8 9
same usage in np.r_
A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)
>> array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
#or
np.r_[A,[[7,8,9]]]
Just to someone's intersted, if you would like to add a column,
array = np.c_[A,np.zeros(#A's row size)]
following what we did before on matrix A, adding a column to it
np.c_[A, [2,8]]
>> array([[1, 2, 3, 2],
[4, 5, 6, 8]])
I also tried using pymysql (on my Win7 x64 machine, Python 3.3), without too much luck. I downloaded the .tar.gz, extract, ran "setup.py install", and everything seemed fine. Until I tried connecting to a database, and got "KeyError [56]". An error which I was unable to find documented anywhere.
So I gave up on pymysql, and I settled on the Oracle MySQL connector.
It comes as a setup package, and works out of the box. And it also seems decently documented.
It worked well in my case. First, you download an image and rename it as iconimage, locates it in the drawable folder. You can change the size by setting android:layout_width
or android:layout_height
. Finally, we have
<ImageButton
android:id="@+id/answercall"
android:layout_width="120dp"
android:layout_height="80dp"
android:src="@drawable/iconimage"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:scaleType="fitCenter" />
Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:
Example.objects.all().update(unset__tags__words=1)
Try using download manager, which can help you download everything you want and save you time.
Check those to options:
Option 1 ->
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Option 2 ->
if(mWebview.getUrl().contains(".mp3") {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
The easiest way to send (simulate) KeyStrokes to any window is to use the SendKeys.Send method of .NET Framework.
Checkout this very intuitive MSDN article http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
Particularly for your case, if your browser window is in focus, sending F5 would just involve the following line of code:
SendKeys.Send("{F5}");
You can just write
input()
at the end of your code
therefore when you run you script it will wait for you to enter something
{ENTER for example}
As a professional Developer I'd say it depends. But I definitely follow GATS and OMG Ponies advice. Know What You are doing, know when it helps and when it hurts and
read hints and other poor ideas
what might make You understand the sql server deeper. I generally follow the rule that SQL Hints are EVIL, but unfortunately I use them every now and then when I get fed up with forcing SQL server do things... But these are rare cases.
luke
By omitting all parts of the head, the loop can also become infinite:
for (;;) {}
None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.
What I was missing is that lea
operations treat the use of parentheses different than how mov
does.
Think of C. Let's say I have an array of long
that I call array
. Now the expression array[i]
performs a dereference, loading the value from memory at the address array + i * sizeof(long)
[1].
On the other hand, consider the expression &array[i]
. This still contains the sub-expression array[i]
, but no dereferencing is performed! The meaning of array[i]
has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling &
what memory address we're looking for. If you like, you could alternatively think of the &
as "cancelling out" the dereference.
Because the two use-cases are similar in many ways, they share the syntax array[i]
, but the existence or absence of a &
changes how that syntax is interpreted. Without &
, it's a dereference and actually reads from the array. With &
, it's not. The value array + i * sizeof(long)
is still calculated, but it is not dereferenced.
The situation is very similar with mov
and lea
. With mov
, a dereference occurs that does not happen with lea
. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9
and leaq (%r8), %r9
. With mov
, these parentheses mean "dereference"; with lea
, they don't. This is similar to how array[i]
only means "dereference" when there is no &
.
An example is in order.
Consider the code
movq (%rdi, %rsi, 8), %rbp
This loads the value at the memory location %rdi + %rsi * 8
into the register %rbp
. That is: get the value in the register %rdi
and the value in the register %rsi
. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp
.
This code corresponds to the C line x = array[i];
, where array
becomes %rdi
and i
becomes %rsi
and x
becomes %rbp
. The 8
is the length of the data type contained in the array.
Now consider similar code that uses lea
:
leaq (%rdi, %rsi, 8), %rbp
Just as the use of movq
corresponded to dereferencing, the use of leaq
here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];
. Recall that &
changes the meaning of array[i]
from dereferencing to simply specifying a location. Likewise, the use of leaq
changes the meaning of (%rdi, %rsi, 8)
from dereferencing to specifying a location.
The semantics of this line of code are as follows: get the value in the register %rdi
and the value in the register %rsi
. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp
. No load from memory is involved, just arithmetic operations [2].
Note that the only difference between my descriptions of leaq
and movq
is that movq
does a dereference, and leaq
doesn't. In fact, to write the leaq
description, I basically copy+pasted the description of movq
, and then removed "Find the value at this location".
To summarize: movq
vs. leaq
is tricky because they treat the use of parentheses, as in (%rsi)
and (%rdi, %rsi, 8)
, differently. In movq
(and all other instruction except lea
), these parentheses denote a genuine dereference, whereas in leaq
they do not and are purely convenient syntax.
[1] I've said that when array
is an array of long
, the expression array[i]
loads the value from the address array + i * sizeof(long)
. This is true, but there's a subtlety that should be addressed. If I write the C code
long x = array[5];
this is not the same as typing
long x = *(array + 5 * sizeof(long));
It seems that it should be based on my previous statements, but it's not.
What's going on is that C pointer addition has a trick to it. Say I have a pointer p
pointing to values of type T
. The expression p + i
does not mean "the position at p
plus i
bytes". Instead, the expression p + i
actually means "the position at p
plus i * sizeof(T)
bytes".
The convenience of this is that to get "the next value" we just have to write p + 1
instead of p + 1 * sizeof(T)
.
This means that the C code long x = array[5];
is actually equivalent to
long x = *(array + 5)
because C will automatically multiply the 5
by sizeof(long)
.
So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)
", I do not mean for "array + i * sizeof(long)
" to be interpreted as a C expression. I am doing the multiplication by sizeof(long)
myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.
[2] Side note: because all lea
does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc
with -O2
optimization translates
long f(long x) {
return x * 5;
}
into the following (irrelevant lines removed):
f:
leaq (%rdi, %rdi, 4), %rax # set %rax to %rdi + %rdi * 4
ret
Solution for Jupyter notebook PIL image visualization with arbitrary number of images:
def show(*imgs, **kwargs):
'''Show in Jupyter notebook one or sequence of PIL images in a row. figsize - optional parameter, controlling size of the image.
Examples:
show(img)
show(img1,img2,img3)
show(img1,img2,figsize=[8,8])
'''
if 'figsize' not in kwargs:
figsize = [9,9]
else:
figsize = kwargs['figsize']
fig, ax = plt.subplots(1,len(imgs),figsize=figsize)
if len(imgs)==1:
ax=[ax]
for num,img in enumerate(imgs):
ax[num].imshow(img)
ax[num].axis('off')
tight_layout()
Here is how I solved my problem:
Directive
app.directive("directive_name", function(){
return {
restrict: 'E',
transclude: true,
template: function(elem, attr){
return '<div><h2>{{'+attr.scope+'}}</h2></div>';
},
replace: true
};
})
Controller
$scope.building = function(data){
var chart = angular.element(document.createElement('directive_name'));
chart.attr('scope', data);
$compile(chart)($scope);
angular.element(document.getElementById('wrapper')).append(chart);
}
I now can use different scopes through the same directive and append them dynamically.
This will
/\bword\b/.test("Thisword is not valid");
return false
, when this one
/\bword\b/.test("This word is valid");
will return true
.
You can use directly:
dict2 = eval(repr(dict1))
where object dict2 is an independent copy of dict1, so you can modify dict2 without affecting dict1.
This works for any kind of object.
Make Executable your jar and after that double click on it on Mac OS then it works successfully.
sudo chmod +x filename.jar
Try this, I hope this works.
The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function
func vendorIdentifierForDevice()->String {
//Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
let commonAppBundleID = getCommonPartOfApplicationBundleID()
//Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
if let vendorID = readFromKeyChain(commonAppBundleID) {
return vendorID
} else {
var vendorID = NSUUID().uuidString
//Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
saveToKeyChain(commonAppBundleID, vendorID)
return vendorID
}
}
May be I am late to answer this, but what solved my problem was to install the mysql-server
sudo apt-get install mysql-server
after spending more than 5 hours I found this solution which helped me to proceed. I hope this would help someone if the top answers won't help them
Postman
.http://{server:port}/json/metallica/post
.Headers
button and enter Content-Type
as header and application/json
in value.POST
from the dropdown next to the URL text box.raw
from the buttons available below URL text box.JSON
from the following dropdown.In the textarea available below, post your request object:
{
"title" : "test title",
"singer" : "some singer"
}
Hit Send
.
Refer to screenshot below:
Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.
For those not running a mac, or having a different setup and can't find this file, the file merely runs:
pip install --upgrade certifi
Hope that helps someone :)
Behavior differences
Some differences on Bash 4.3.11:
POSIX vs Bash extension:
[
is POSIX[[
is a Bash extension inspired from Korn shellregular command vs magic
[
is just a regular command with a weird name.
]
is just the last argument of [
.
Ubuntu 16.04 actually has an executable for it at /usr/bin/[
provided by coreutils, but the bash built-in version takes precedence.
Nothing is altered in the way that Bash parses the command.
In particular, <
is redirection, &&
and ||
concatenate multiple commands, ( )
generates subshells unless escaped by \
, and word expansion happens as usual.
[[ X ]]
is a single construct that makes X
be parsed magically. <
, &&
, ||
and ()
are treated specially, and word splitting rules are different.
There are also further differences like =
and =~
.
In Bashese: [
is a built-in command, and [[
is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword
<
[[ a < b ]]
: lexicographical comparison[ a \< b ]
: Same as above. \
required or else does redirection like for any other command. Bash extension.expr x"$x" \< x"$y" > /dev/null
or [ "$(expr x"$x" \< x"$y")" = 1 ]
: POSIX equivalents, see: How to test strings for lexicographic less than or equal in Bash?&&
and ||
[[ a = a && b = b ]]
: true, logical and[ a = a && b = b ]
: syntax error, &&
parsed as an AND command separator cmd1 && cmd2
[ a = a ] && [ b = b ]
: POSIX reliable equivalent[ a = a -a b = b ]
: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a
or b
like !
or (
which would be interpreted as logical operations(
[[ (a = a || a = b) && a = b ]]
: false. Without ( )
, would be true because [[ && ]]
has greater precedence than [[ || ]]
[ ( a = a ) ]
: syntax error, ()
is interpreted as a subshell[ \( a = a -o a = b \) -a a = b ]
: equivalent, but ()
, -a
, and -o
are deprecated by POSIX. Without \( \)
would be true because -a
has greater precedence than -o
{ [ a = a ] || [ a = b ]; } && [ a = b ]
non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ]
because the ||
and &&
shell operators have equal precedence unlike [[ || ]]
and [[ && ]]
and -o
, -a
and [
word splitting and filename generation upon expansions (split+glob)
x='a b'; [[ $x = 'a b' ]]
: true, quotes not neededx='a b'; [ $x = 'a b' ]
: syntax error, expands to [ a b = 'a b' ]
x='*'; [ $x = 'a b' ]
: syntax error if there's more than one file in the current directory.x='a b'; [ "$x" = 'a b' ]
: POSIX equivalent=
[[ ab = a? ]]
: true, because it does pattern matching (* ? [
are magic). Does not glob expand to files in current directory.[ ab = a? ]
: a?
glob expands. So may be true or false depending on the files in the current directory.[ ab = a\? ]
: false, not glob expansion=
and ==
are the same in both [
and [[
, but ==
is a Bash extension.case ab in (a?) echo match; esac
: POSIX equivalent[[ ab =~ 'ab?' ]]
: false, loses magic with ''
in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1
)[[ ab? =~ 'ab?' ]]
: true=~
[[ ab =~ ab? ]]
: true, POSIX extended regular expression match, ?
does not glob expand[ a =~ a ]
: syntax error. No bash equivalent.printf 'ab\n' | grep -Eq 'ab?'
: POSIX equivalent (single line data only)awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?'
: POSIX equivalent.Recommendation: always use []
There are POSIX equivalents for every [[ ]]
construct I've seen.
If you use [[ ]]
you:
[
is just a regular command with a weird name, no special semantics are involved.Thanks to Stéphane Chazelas for important corrections and additions.
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()
if (authUserList != null && _list.Count() > 0)
_list = _list.Where(l => authUserList.Contains(l.CreateUserId));
This is just an observation. "encode" seems to be a method for string objects
str_1 = 'a'
str_1.encode('utf-8')
>>> b'a'
However, if str1 is inspected for methods, an empty list is returned
inspect.getmember(str_1, predicate=inspect.ismethod)
>>> []
So, maybe I am wrong, but the issue seems to be not simple.
If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
Use this.
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
Create a new directory layout-land
, then create xml
file with same name in layout-land
as it was layout
directory and align there your content for Landscape mode.
Note that id of content in both xml
is same.
I had the same error. The problem was this extra symbol ">" added by mistake between the tags </ComboBox.SelectedValue> and </ComboBox>:
<ComboBox
ItemsSource="{Binding StatusTypes}"
DisplayMemberPath="StatusName"
SelectedValuePath="StatusID">
<ComboBox.SelectedValue>
<Binding Path="StatusID"/>
</ComboBox.SelectedValue>
>
</ComboBox>
and here is the correct code:
<ComboBox
ItemsSource="{Binding StatusTypes}"
DisplayMemberPath="StatusName"
SelectedValuePath="StatusID">
<ComboBox.SelectedValue>
<Binding Path="StatusID"/>
</ComboBox.SelectedValue>
</ComboBox>
Go to your Credential manager => git credentials Check your git credentials and check your password.
This worked for me.
I went through this when trying to get a clientcert and private key out of a keystore.
The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version
to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working
So export the keys into .p12
keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \ -srcstoretype JKS -deststoretype PKCS12 \ -srcstorepass $jkspassword -deststorepass $p12password -srcalias $myalias -destalias $myalias \ -srckeypass $keypass -destkeypass $keypass -noprompt
And generate the pem file that holds only the key
echo making ${fileroot}.key.pem openssl pkcs12 -in $p12 -out ${fileroot}.key.pem \ -passin pass:$p12password \ -passout pass:$p12password -nocerts
mkdir ~/nss chmod 700 ~/nss certutil -N -d ~/nss
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >
Now curl should work.
curl --insecure --cert <client cert alias>:<password for cert> \ --key ${fileroot}.key.pem <URL>
As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.
local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))
Output
string
number
Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*"
. But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.
<div class="col-sm-8 img-upload-section">
<input name="image3" type="file" accept="image/*" id="menu_images"/>
<img id="menu_image" class="preview_img" />
<input type="submit" value="Submit" />
</div>
Here on the change event we first check the size of the image. And in the second if
condition we check whether or not it is an image file.
this.files[0].type.indexOf("image")
will be -1
if it is not an image file.
document.getElementById("menu_images").onchange = function () {
var reader = new FileReader();
if(this.files[0].size>528385){
alert("Image Size should not be greater than 500Kb");
$("#menu_image").attr("src","blank");
$("#menu_image").hide();
$('#menu_images').wrap('<form>').closest('form').get(0).reset();
$('#menu_images').unwrap();
return false;
}
if(this.files[0].type.indexOf("image")==-1){
alert("Invalid Type");
$("#menu_image").attr("src","blank");
$("#menu_image").hide();
$('#menu_images').wrap('<form>').closest('form').get(0).reset();
$('#menu_images').unwrap();
return false;
}
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("menu_image").src = e.target.result;
$("#menu_image").show();
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
You could parse the output from the GPRESULT command.
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
How about this? (not my real IP Address!)
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
192.0.2.0
Note that using localhost would just return and IP of 127.0.0.1
PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
127.0.0.1
The IP Address object has to be expanded out to get the address string
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPV4Address
PS C:\> $ipV4
Address : 556228818
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 192.0.2.0
PS C:\> $ipV4.IPAddressToString
192.0.2.0
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
Here's a short one-liner with es6!
const nums = [
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC9233F2015",
"AC9233F2015",
"AC9233F2015",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E2",
"AC8818E2",
"AC8818E2",
"AC8818E2",
"AC9233F2015",
"AC9233F2015",
"AC9233F2015",
"AC9233F2015",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E2",
"AC8818E2",
"AC9233F2015",
"AC9233F2015",
"AC8818E1",
"AC8818E1",
"AC8818E1",
"AC8818E2",
"AC8818E2",
"AC8818E2",
"AC8818E2",
"ACB098F25",
"ACB098F25",
"ACB098F25",
"ACB098F25",
"AC8818E2",
"AC8818E2",
"AC8818E1",
"AC8818E1",
"AC8818E1",
]
Set is a new data object introduced in ES6. Because Set only lets you store unique values. When you pass in an array, it will remove any duplicate values.
export const $uniquenums = [...new Set(nums)].sort();
I was also facing this problem because when I run projects on the emulator its working fine but on a real device it gives this error. So I resolve this problem by the following solution
1st step: First of all open cmd and go to your SDK manager Platform-tools folder
cd C:Development\Android\Sdk\Platform-tools
2nd step: now run this command :
adb devices
after this command check your device listed in command prompt
3rd step: now run this
adb reverse tcp:8081 tcp:8081
Now your setup is done
4th step: Go to your project directory and run this command
react-native run-android
Let's say you have a Login
action which provides the user with a login screen, then receives the user name and password back after the user submits the form:
public ActionResult Login() {
return View();
}
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.
Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.
[HttpGet]
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
You can also combine the request method attributes if your action serves requests from multiple verbs:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
.
Using the instruction if
?
if(isset($something['say']) && $something['say'] === 'bla') {
// do something
}
By the way, you are assigning a value with the key say
twice, hence your array will result in an array with only one value.
The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.
Working with it is queit easy.
Using your Firefox, navigate to the website which you want to get your post request to it.
In your Firefox menu Tools->Live Http Headers
A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.
In the website, do an activity(log in, submit a form, etc.)
Look at your plug in window. It is all recorded.
Just remember you need to check the Capture.
2018 Update
In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName
to silently delete the directory .\DirName
with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
Thread t = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(10000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
@Override
public void run() {
SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("chat_list", "");
GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
String sam = "";
ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
listview.setAdapter(adapter);
// listview.setStackFromBottom(true);
// Util.showMessage(Chat.this,"Merhabalar");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
In case it needed it can be stoped by
@Override
protected void onDestroy() {
super.onDestroy();
Thread.interrupted();
//t.interrupted();
}
Just found another solutions worked for me. You can use '\' sign before your one special.
passwd=\@31\&3*J
Visual Studio looks for headers in this order:
In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).
You can apply Navigation Bar Image like below for Translucent.
Objective-C:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault]; //UIImageNamed:@"transparent.png"
self.navigationController.navigationBar.shadowImage = [UIImage new];////UIImageNamed:@"transparent.png"
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
Swift 3:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) //UIImage.init(named: "transparent.png")
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
If you use on click and only check if radio is checked and then deselect, you will never get the radio checked. So maybe easiest is to use classnames like this:
if($(this).hasClass('alreadyChecked')) {//it is already checked
$('.myRadios').removeClass('alreadyChecked');//remove from all radios
$(this).prop('checked', false);//deselect this
}
else {
$('.myRadios').removeClass('alreadyChecked');//remove from all
$(this).addClass('alreadyChecked');//add to only this
}
I had the same problem when I was writing Java application on Netbeans.Here is the solution:
Find your project in projects selection tab
Right click "Libraries"
Click "Add JAR/Folder..."
Choose "derbyclient.jar"
Click "Open", then you will see "derbyclient.jar" under your "Libraries"
Make sure your URL, user name, pass word is correct, and run your code:)
the difference is that max-device-width is all screen's width and max-width means the space used by the browser to show the pages. But another important difference is the support of android browsers, in fact if u're going to use max-device-width this will work only in Opera, instead I'm sure that max-width will work for every kind of mobile browser (I had test it in Chrome, firefox and opera for ANDROID).
I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.
public static String toTitleCase(String input) {
input = input.toLowerCase();
char c = input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}
Textdistance:
TextDistance – python library for comparing distance between two or more sequences by many algorithms. It has Textdistance
Example1:
import textdistance
textdistance.hamming('test', 'text')
Output:
1
Example2:
import textdistance
textdistance.hamming.normalized_similarity('test', 'text')
Output:
0.75
Thanks and Cheers!!!