I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.
Error :
Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at hudson.Proc$LocalProc.<init>(Proc.java:250)
at hudson.Proc$LocalProc.<init>(Proc.java:219)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
at hudson.Launcher$ProcStarter.start(Launcher.java:455)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Solution :
1 - Install Cygwin and note the directory where it gets installed.
It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.
2 - Tell Jenkins where sh.exe is located.
Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.
That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.
vagrant plugin install vagrant-vbguest
vagrant destroy #clean rhel/yum repos
vagrant up
And on the config file:
config.vbguest.auto_update = false #important so that any changes to the base image don't affect on reload
Here is how you can fix it:
/var/lib/jenkins/config.xml
<useSecurity>true</useSecurity>
to false sudo service jenkins restart
allow anyone to do anything
, and allow user signup.www.yoursite.com/securityRealm/addUser
and create a userallow anyone to do anything
to whatever you actually want users to be able to do. In my case, it is allow logged in users to do anything
.I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:
Creating the JKS with the entire certificate chain.
Making sure the key in the JKS had the alias of the FQDN of the machine.
Renaming the alias of the certificate for my machine ${FQDN}.cert
This took endless experimentation with the java command line options:
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager
-Djava.security.debug=access:stack
My key and CSR were produced in OpenSSL so I had to import the key with:
openssl pkcs12 -export -in cert.pem -inkey cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12
keytool complains about the format so I converted the format followed by adding my cert chain:
keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
keytool -import -trustcacerts -alias 'DigiCert Global Root G2' -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.)
When I restarted the application with the resulting jks
file, things started to work.
Something else I figured out as part of this. You can check the certificate chain by using:
openssl x509 -in cert2.pem -noout -text
for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier:
and X509v3 Authority Key Identifier:
lines. The X509v3 Authority Key Identifier:
of one level matches the X509v3 Subject Key Identifier:
of the next higher level. You found the top of chain when the Issuer:
string matches the Subject:
string.
I hope this can save somebody some of the time it took me.
I had similar problem when using Tomcat6.x and none of the advices I found was helping.
At the end I deleted work
folder (of Tomcat) and the problem gone.
I know it is illogical but for documentation purpose...
PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.
PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes
RabbitMQ Management console:
PORT 5672
RabbitMQ main port.
For a cluster of nodes, they must be open to each other on 35197
, 4369
and 5672
.
For any servers that want to use the message queue, only 5672
is required.
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
I just had this issue building react-native app when I try to install Pod. I had to export 2 variables:
export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'
Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ?
is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.
What does the DUMP
function show is actually stored in the database?
SELECT column_name,
dump(column_name,1016)
FROM your_table
WHERE <<predicate that returns just the sample data you posted>>
What application are you using to view the data? What is the client's NLS_LANG
set to?
What is the database and national character set? Is the data stored in a VARCHAR2
column? Or NVARCHAR2
?
SELECT parameter, value
FROM v$nls_parameters
WHERE parameter LIKE '%CHARACTERSET';
If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE
would need to be something like
UPDATE table_name
SET column1 = REPLACE(column1, chr(25), q'[']'),
column2 = REPLACE(column2, chr(25), q'[']'),
...
columnN = REPLACE(columnN, chr(25), q'[']')
WHERE INSTR(column1,chr(25)) > 0
OR INSTR(column2,chr(25)) > 0
...
OR INSTR(columnN,chr(25)) > 0
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
The R-squared is not dependent on the number of variables in the model. The adjusted R-squared is.
The adjusted R-squared adds a penalty for adding variables to the model that are uncorrelated with the variable your trying to explain. You can use it to test if a variable is relevant to the thing your trying to explain.
Adjusted R-squared is R-squared with some divisions added to make it dependent on the number of variables in the model.
Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.
In Android Studio 0.8.9, I opened Android Device Monitor, selected my emulator from the Devices list and got the output in the LogCat tab.
After that, I went back to the main view of Android Studio and selected Restore Logcat view in the right of the Android DDMS tab and there it was!
If this doesn't work, you could see your logcat in the Android Device Monitor as I explained in the first sentence.
Try this
The entire code for drawing a circle or download project source code and test it on your android studio. Draw circle on canvas programmatically.
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.widget.ImageView;
public class Shape {
private Bitmap bmp;
private ImageView img;
public Shape(Bitmap bmp, ImageView img) {
this.bmp=bmp;
this.img=img;
onDraw();
}
private void onDraw(){
Canvas canvas=new Canvas();
if (bmp.getWidth() == 0 || bmp.getHeight() == 0) {
return;
}
int w = bmp.getWidth(), h = bmp.getHeight();
Bitmap roundBitmap = getRoundedCroppedBitmap(bmp, w);
img.setImageBitmap(roundBitmap);
}
public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f, finalBitmap.getWidth() / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
git config --global --unset http.proxy
This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.
The C10K problem page has a very good discussion of this issue.
You can try with IME_ACTION_DONE
.
This action performs a “done” operation for nothing to input and the IME will be closed.
Your_EditTextObj.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
/* Write your logic here that will be executed when user taps next button */
handled = true;
}
return handled;
}
});
In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)
It's the line after that match that you're interesting in, right? In sed, that could be accomplished like so:
sed -n '/ABC/{n;p}' infile
Alternatively, grep's A option might be what you're looking for.
-A NUM, Print NUM lines of trailing context after matching lines.
For example, given the following input file:
foo
bar
baz
bash
bongo
You could use the following:
$ grep -A 1 "bar" file
bar
baz
$ sed -n '/bar/{n;p}' file
baz
Hope that helps.
UPDATE: DELETE from a trigger works on both MSSql 7 and MSSql 2008.
I'm no relational guru, nor a SQL standards wonk. However - contrary to the accepted answer - MSSQL deals just fine with both recursive and nested trigger evaluation. I don't know about other RDBMSs.
The relevant options are 'recursive triggers' and 'nested triggers'. Nested triggers are limited to 32 levels, and default to 1. Recursive triggers are off by default, and there's no talk of a limit - but frankly, I've never turned them on, so I don't know what happens with the inevitable stack overflow. I suspect MSSQL would just kill your spid (or there is a recursive limit).
Of course, that just shows that the accepted answer has the wrong reason, not that it's incorrect. However, prior to INSTEAD OF triggers, I recall writing ON INSERT triggers that would merrily UPDATE the just inserted rows. This all worked fine, and as expected.
A quick test of DELETEing the just inserted row also works:
CREATE TABLE Test ( Id int IDENTITY(1,1), Column1 varchar(10) )
GO
CREATE TRIGGER trTest ON Test
FOR INSERT
AS
SET NOCOUNT ON
DELETE FROM Test WHERE Column1 = 'ABCDEF'
GO
INSERT INTO Test (Column1) VALUES ('ABCDEF')
--SCOPE_IDENTITY() should be the same, but doesn't exist in SQL 7
PRINT @@IDENTITY --Will print 1. Run it again, and it'll print 2, 3, etc.
GO
SELECT * FROM Test --No rows
GO
You have something else going on here.
Was playing with this today... I beleive you can also use @@ROWCOUNT, like this:
DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount
Then replace the 'SELECT 1 UNION SELECT 2' with your actual select without the count. I'd suggest just putting 1 in your select, like this:
SELECT 1
FROM dbo.Comm_Services
WHERE....
....
(as opposed to putting SELECT *)
Hope that helps.
Try
sys.exit("message")
It is like the perl
die("message")
if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function
Here is a good breakdown of the pros and cons:
So, it appears that constants should be used when it is very unlikely that the value will ever change, or if no external apps/libs will be using the constant. Static readonly fields should be used when run-time calculation is required, or if external consumers are a factor.
Here, using your notation:
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
if (file.isFile()) {
System.out.println(file.getName() + " " + file.length());
size += file.length();
}
else
size += getFolderSize(file);
}
return size;
}
There are two options for cross thread operations.
Control.InvokeRequired Property
and second one is to use
SynchronizationContext Post Method
Control.InvokeRequired is only useful when working controls inherited from Control class while SynchronizationContext can be used anywhere. Some useful information is as following links
In .htaccess add this line:
AddCharset utf-8 .html .css .php .txt .js
This is for those that do not have access to their server's conf file. It is just one more thing to try when other attempts failed.
As far as performance issues regarding the use of .htaccess I have not seen this. My typical page load times are 150-200 mS with or without .htaccess
What good is performance if your page does not render correctly. Most shared servers do not allow user access to the config file which is the preferred place to add a character set.
On Windows 10, with Python 3.6.X version I was facing same then after checking deliberately , I noticed I had Python-32 bit installation on my 64 bit machine. Remember TensorFlow is only compatible with 64bit installation of python. Not 32 bit of Python
If we download Python from python.org , the default installation would be 32 bit. So we have to download 64 bit installer manually to install Python 64 bit. And then add
Then run gpupdate /Force
on command prompt. If python command doesnt work for 64 bit restart your machine.
Then run python on command prompt. It should show 64 bit
C:\Users\YOURNAME>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Then run below command to install tensorflow CPU version(recommended)
pip3 install --upgrade tensorflow
Try this.
In this example, I'm targeting it with its input name and value
$("input[name=background][value='some value']").prop("checked",true);
Good to know: in case of multi-word value, it will work because of apostrophes, too.
You can get the maximum like this:
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
and so:
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If you know that "A" and "B" are the only columns, you could even get away with
>>> df["C"] = df.max(axis=1)
And you could use .apply(max, axis=1)
too, I guess.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
I encountered the same issue and was able to fix it by:
You can learn datetime formatting in sql server here
http://www.sql-server-helper.com/tips/date-formats.aspx
http://yrbyogi.wordpress.com/2009/11/16/date-and-time-types-in-sql-server/
Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:
// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");
For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open
options for customization.
Update:
You would need something along:
$(document).ready(function() {
$(".product-item").click(function() {
var productLink = $(this).find("a");
productLink.attr("target", "_blank");
window.open(productLink.attr("href"));
return false;
});
});
Note the usage of .attr()
:
$element.attr("attribute_name") // Get value of attribute.
$element.attr("attribute_name", attribute_value) // Set value of attribute.
You can use JSoup.
It's a very strong HTML parser
for java
ILSpy works great!
As far as I can tell it does everything that Reflector did and looks the same too.
If you want to keep python 3, you can follow these directions to create a python 2.7 environment, called py27.
Then you just need to activate py27:
$ conda activate py27
Then you can install spyder on this environment, e.g.:
$ conda install spyder
Then you can start spyder from the command line or navigate to 2.7 version of spyder.exe below the envs directory (e.g. C:\ProgramData\Anaconda3\envs\py27\Scripts)
>
selects immediate childrenFor example, if you have nested divs like such:
<div class='outer'>
<div class="middle">
<div class="inner">...</div>
</div>
<div class="middle">
<div class="inner">...</div>
</div>
</div>
and you declare a css rule in your stylesheet like such:
.outer > div {
...
}
your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.
div {_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
}_x000D_
.outer > div {_x000D_
border: 1px solid orange;_x000D_
}
_x000D_
<div class='outer'>_x000D_
div.outer - This is the parent._x000D_
<div class="middle">_x000D_
div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
<div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
</div>_x000D_
<div class="middle">_x000D_
div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
<div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p>Without Words</p>_x000D_
_x000D_
<div class='outer'>_x000D_
<div class="middle">_x000D_
<div class="inner">...</div>_x000D_
</div>_x000D_
<div class="middle">_x000D_
<div class="inner">...</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you, instead, had a space between selectors instead of
>
, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the >
does.
NOTE: The >
selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.
If you're looking into less-well-used CSS selectors, you may also want to look at +
, ~
, and [attr]
selectors, all of which can be very useful.
This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.
Yes, you can!))
Disclaimer: This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.
I found one way to make INSERT
, UPDATE
or DELETE
in function using xp_cmdshell
.
So you need just to replace the code inside @sql variable.
CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @sql varchar(4000), @cmd varchar(4000)
SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') '
SELECT @cmd = 'sqlcmd -S ' + @@servername +
' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
RETURN 1
END
I assume you mean the size of the bullet at the start of each list item. If that's the case, you can use an image instead of it:
list-style-image:url('bigger.gif');
list-style-type:none;
If you meant the actual size of the li
element, then you can change that as normal with width
and height
.
try this one :),
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
^M
in your git diff
?In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M
at the end of the lines I added in git diff
. I think the ^M
were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR
line endings, and in OS X it uses LF
line endings.
Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.
You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.
If you go for this option, you should however fix the current files (because they're still using the CR
line endings). I did this by following these steps:
Remove all files from the repository, but not from your filesystem.
git rm --cached -r .
Add a .gitattributes
file that enforces certain files to use a LF
as line endings. Put this in the file:
*.ext text eol=crlf
Replace .ext
with the file extensions you want to match.
Add all the files again.
git add .
This will show messages like this:
warning: CRLF will be replaced by LF in <filename>.
The file will have its original line endings in your working directory.
You could remove the .gitattributes
file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.
Commit and push it all.
Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:
The file will have its original line endings in your working directory.
You can do something like this to remove the files:
git ls | grep ".ext$" | xargs rm -f
And then this to get them back with the correct line endings:
git ls | grep ".ext$" | xargs git checkout
Of course replacing .ext
with the extension you want.
Now your project only uses LF
characters for the line endings, and the nasty CR
characters won't ever come back :).
The other option is to enforce windows style line endings. You can also use the .gitattributes
file for this.
More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all
Array can only be used for specific types, whereas lists can be used for any object.
Arrays can also only data of one type, whereas a list can have entries of various object types.
Arrays are also more efficient for some numerical computation.
You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)
let dict = ["c": 123, "d": 045, "a": 456]
for (index, entry) in enumerate(dict) {
println(index) // 0 1 2
println(entry) // (d, 45) (c, 123) (a, 456)
}
If you want to sort first..
var sortedKeysArray = sorted(dict) { $0.0 < $1.0 }
println(sortedKeysArray) // [(a, 456), (c, 123), (d, 45)]
var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]
then iterate.
for (index, entry) in enumerate(sortedKeysArray) {
println(index) // 0 1 2
println(entry.0) // a c d
println(entry.1) // 456 123 45
}
If you want to create an ordered dictionary, you should look into Generics.
Old style classes are still marginally faster for attribute lookup. This is not usually important, but it may be useful in performance-sensitive Python 2.x code:
In [3]: class A: ...: def __init__(self): ...: self.a = 'hi there' ...: In [4]: class B(object): ...: def __init__(self): ...: self.a = 'hi there' ...: In [6]: aobj = A() In [7]: bobj = B() In [8]: %timeit aobj.a 10000000 loops, best of 3: 78.7 ns per loop In [10]: %timeit bobj.a 10000000 loops, best of 3: 86.9 ns per loop
Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:
- debug:
msg: "{% for address in network.addresses.private_man %}\
{% if address.type == 'fixed' %}\
{{ address.addr }}\
{% endif %}\
{% endfor %}"
Or if you prefer to put it all on one line:
- debug:
msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"
Which returns:
ok: [localhost] => {
"msg": "172.16.1.100"
}
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
Use "This is' it".replace("'", "\\'")
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
For more detail you can refer the link.
I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:
CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;
Note, the temp table will be put into a schema like pg_temp_3.
This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:
ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;
If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".
While pidof
and pgrep
are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command
The output on Gentoo Linux:
14484 ? S 0:00 apache2 14667 ? S 0:00 apache2 19620 ? Sl 0:00 apache2 21132 ? Ss 0:04 apache2
The output on OS X:
42582 ?? Z 0:00.00 (smbclient) 46529 ?? Z 0:00.00 (smbclient) 46539 ?? Z 0:00.00 (smbclient) 46547 ?? Z 0:00.00 (smbclient) 46586 ?? Z 0:00.00 (smbclient) 46594 ?? Z 0:00.00 (smbclient)
On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:
#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
Furthermore, if you would like the list of PIDs, you could easily grep for those as well:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
3519 3521 3523 3524
The output of the following is an empty string, making this approach safe for processes that are not running:
echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'
This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.
#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
echo "Process not running." 1>&2
exit 1
else
for PID in $PIDS; do
echo $PID
done
fi
You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
Please keep in mind that you're simply parsing the output of ps ax
which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql"
will also match 'mysqld' processes). I highly recommend using which
to check against a full path where possible.
References:
If you're using go run
, do go run *.go
. It will automatically find all go files in the current working directory, compile and then run your main function.
Here's what I had to do to get it to work, and I think is necessary for anyone with a Number Pad for a keyboard (or any other ones without a done button:
I created a function called
-(IBAction)backgroundIsTapped:(id)sender
This was also defined in the .h file.
After this, I linked to to the 'touch down' bit for the ViewController in Interface Builder.
In the 'background is tapped' function, I put this:
[answerField resignFirstResponder];
Just remember to change 'answerField' to the name of the UITextField you want to remove the keyboard from (obviously make sure your UITextField is defined like below:)
IBOutlet UITextField * <nameoftextfieldhere>;
I know this topic probably died a long time ago... but I'm hoping this will help someone, somewhere!
BrixenDK is right.
.ajaxStop()
callback executed when all ajax call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
you can use style
<td colspan="2">
<div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>
<div style="float: right; width:100px">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
<div style="clear:both"></div>
</td>
I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:
List<List<String>> addresses = new ArrayList<List<String>>();
But honestly for addresses, I'd create a class to model them.
If you were to use arrays it would be:
List<String[]> addresses = new ArrayList<String[]>();
ie you can't declare the size of the array.
Lastly, don't declare your types as concrete types in instances like this (ie for addresses
). Use the interface as I've done above. This applies to member variables, return types and parameter types.
In addition to Ian's answer, I had to allow the font extensions in the request filtering module to make it work.
<system.webServer>
<staticContent>
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" />
</staticContent>
<security>
<requestFiltering>
<fileExtensions>
<add fileExtension=".woff" allowed="true" />
<add fileExtension=".ttf" allowed="true" />
<add fileExtension=".woff2" allowed="true" />
</fileExtensions>
</requestFiltering>
</security>
</system.webServer>
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
The ensurepip
module was added in version 3.4 and then backported to 2.7.9.
So make sure your Python version is at least 2.7.9 if using Python 2, and at least 3.4 if using Python 3.
Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....
Run again your problem will be solved
I needed to know the script name and where it is executing from.
Prefixing "$global:" to the MyInvocation structure returns the full path and script name when called from both the main script, and the main line of an imported .PSM1 library file. It also works from within a function in an imported library.
After much fiddling around, I settled on using $global:MyInvocation.InvocationName. It works reliably with CMD launch, Run With Powershell, and the ISE. Both local and UNC launches return the correct path.
Answering your question in this format is quite challenging.
On the other hand you ask about navigation and then about current $state
acting all weird.
For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)
Take the following controller:
app.controller('MainCtrl', function($scope, $state) {
$scope.state = $state;
});
Where app
is configured as:
app.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.state('main.thiscontent', {
url: '/thiscontent',
templateUrl: 'this.html',
controller: 'ThisCtrl'
})
.state('main.thatcontent', {
url: '/thatcontent',
templateUrl: 'that.html'
});
});
Then simple HTML template having
<div>
{{ state | json }}
</div>
Would "print out" e.g. the following
{
"params": {},
"current": {
"url": "/thatcontent",
"templateUrl": "that.html",
"name": "main.thatcontent"
},
"transition": null
}
I put up a small example showing this, using ui.router
and pascalprecht.translate
for the menus. I hope you find it useful and figure out what is it you are doing wrong.
Plunker here http://plnkr.co/edit/XIW4ZE
Screencap
You've staged the deletion so you need to do:
git checkout HEAD cc.properties store/README store/cc.properties
git checkout .
only checks out from the index where the deletion has already been staged.
I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.
CASE
WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))
WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))
WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))
ELSE
END
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
This one works: I took January 2006 as a reference. (It is a Sunday)
int isLeapYear(int year) {
if(((year%4==0)&&(year%100!=0))||((year%400==0)))
return 1;
else
return 0;
}
int isDateValid(int dd,int mm,int yyyy) {
int isValid=-1;
if(mm<0||mm>12) {
isValid=-1;
}
else {
if((mm==1)||(mm==3)||(mm==5)||(mm==7)||(mm==8)||(mm==10)||(mm==12)) {
if((dd>0)&&(dd<=31))
isValid=1;
} else if((mm==4)||(mm==6)||(mm==9)||(mm==11)) {
if((dd>0)&&(dd<=30))
isValid=1;
} else {
if(isLeapYear(yyyy)){
if((dd>0)&&dd<30)
isValid=1;
} else {
if((dd>0)&&dd<29)
isValid=1;
}
}
}
return isValid;
}
int calculateDayOfWeek(int dd,int mm,int yyyy) {
if(isDateValid(dd,mm,yyyy)==-1) {
return -1;
}
int days=0;
int i;
for(i=yyyy-1;i>=2006;i--) {
days+=(365+isLeapYear(i));
}
printf("days after years is %d\n",days);
for(i=mm-1;i>0;i--) {
if((i==1)||(i==3)||(i==5)||(i==7)||(i==8)||(i==10)) {
days+=31;
}
else if((i==4)||(i==6)||(i==9)||(i==11)) {
days+=30;
} else {
days+= (28+isLeapYear(i));
}
}
printf("days after months is %d\n",days);
days+=dd;
printf("days after days is %d\n",days);
return ((days-1)%7);
}
Why myList[1] is considered a 'str' object?
Because it is a string. What else is 'from form'
, if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well - but that's part of the str
class and doesn't make it a list or something).
mList[1]
returns the first item in the list'from form'
If you mean that myList
is 'from form'
, no it's not!!! The second (indexing starts at 0) element is 'from form'
. That's a BIG difference. It's the difference between a house and a person.
Also, myList
doesn't have to be a list
from your short code sample - it could be anything that accepts 1
as index - a dict with 1 as index, a list, a tuple, most other sequences, etc. But that's irrelevant.
but I cannot append to item 1 in the list
myList
Of course not, because it's a string and you can't append to string. String are immutable. You can concatenate (as in, "there's a new object that consists of these two") strings. But you cannot append
(as in, "this specific object now has this at the end") to them.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
Your statement matches any string that contains a letter or digit anywhere, even if it contains other non-alphanumeric characters. Try this:
SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$';
^
and $
require the entire string to match rather than just any portion of it, and +
looks for 1 or more alphanumberic characters.
You could also use a named character class if you prefer:
SELECT * FROM table WHERE column REGEXP '^[[:alnum:]]+$';
Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.
WebAsyncManagerIntegrationFilter
Provides integration between the SecurityContext and Spring Web's WebAsyncManager.
SecurityContextPersistenceFilter
This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.
HeaderWriterFilter
Filter implementation to add headers to the current response.
LogoutFilter
If request url is /logout
(for default configuration) or if request url mathces RequestMatcher
configured in LogoutConfigurer
then
LogoutConfigurer
/
or logout success url configured or invokes logoutSuccessHandler configured.UsernamePasswordAuthenticationFilter
HTTP POST
) default /login
or matches .loginProcessingUrl()
configured in FormLoginConfigurer
then UsernamePasswordAuthenticationFilter
attempts authentication.usernameParameter(String)
, passwordParameter(String)
..loginPage()
overrides defaults Authentication
object(UsernamePasswordAuthenticationToken
or any implementation of Authentication
in case of your custom auth filter) is created. authenticationManager.authenticate(authToken)
will be invokedAuthenticationProvider
authenticate method tries all auth providers and checks any of the auth provider supports
authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException
.authenticationSuccessHandler
will be invoked which redirects to the target url configured(default is /
)SecurityContextHolderAwareRequestFilter
, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
AnonymousAuthenticationFilter
Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication
object (AnonymousAuthenticationToken
) with granted authority ROLE_ANONYMOUS
. Here AnonymousAuthenticationToken
facilitates identifying un-authenticated users subsequent requests.
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
ExceptionTranslationFilter
, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor
There will be FilterSecurityInterceptor
which comes almost last in the filter chain which gets Authentication object from SecurityContext
and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers
configured in HttpSecurityConfiguration
.
Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain
Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter
,RequestCacheAwareFilter
,SessionManagementFilter
...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter
.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter
it will become entirely different case.
From Documentation ordering of filters is given as
- ChannelProcessingFilter
- ConcurrentSessionFilter
- SecurityContextPersistenceFilter
- LogoutFilter
- X509AuthenticationFilter
- AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
- UsernamePasswordAuthenticationFilter
- ConcurrentSessionFilter
- OpenIDAuthenticationFilter
- DefaultLoginPageGeneratingFilter
- DefaultLogoutPageGeneratingFilter
- ConcurrentSessionFilter
- DigestAuthenticationFilter
- BearerTokenAuthenticationFilter
- BasicAuthenticationFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
- SwitchUserFilter
You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.
When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.
Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.
Here's how I would do it. I'll leave range checking on the int month
up to you.
import java.text.DateFormatSymbols;
public String formatMonth(int month, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
return monthNames[month - 1];
}
For very large output logs it could be difficult to open (network delay, scrolling). This is the solution I'm using to check big log files:
https://${URL}/jenkins/job/${jobName}/${buildNumber}/
in the left column you see: View as plain text
. Do a right mouse click on it and choose save links as
. Now you can save your big log as .txt file. Open it with notepad++ and you can go through your logs easily without network delays during scrolling.
Element.prototype.getA = function (a) {
if (a) {
return this.getAttribute(a);
} else {
var o = {};
for(let a of this.attributes){
o[a.name]=a.value;
}
return o;
}
}
having <div id="mydiv" a='1' b='2'>...</div>
can use
mydiv.getA() // {id:"mydiv",a:'1',b:'2'}
Try this: http://jsfiddle.net/8fv6e/8/
It is another version of the answers.
HTML:
<label for="aboutDescription" id="aboutHeading">About</label>
<textarea rows="15" cols="50" id="aboutDescription"
style="max-height:100px;min-height:100px; resize: none"></textarea>
<a id="imageURLId" target="_blank">Go to
HomePage</a>
CSS:
#imageURLId{
font-size: 14px;
font-weight: normal;
resize: none;
overflow-y: scroll;
}
Following up on sas's answer, PHP 5.4, Symfony 2.8, I had to use
ini_set('date.timezone','<whatever timezone string>');
instead of date_default_timezone_set
. I also added a call to ini_set
to the top of a custom web/config.php
to get that check to succeed.
Create UIView with required padding space and add it to textfield.leftView member and set textfield.leftViewMode member to UITextFieldViewMode.Always
// For example if you have textfield named title
@IBOutlet weak var title: UITextField!
// Create UIView
let paddingView : UIView = UIView(frame: CGRectMake(0, 0, 5, 20))
//Change your required space instaed of 5.
title.leftView = paddingView
title.leftViewMode = UITextFieldViewMode.Always
I have observed a similar issue in my project. The issue was solved when the jar with the missing class definition was pasted into the lib directory of tomcat.
All of the prior solutions get at the point a little, however, they just don't copy everything over. I created a PHP function (albeit somewhat lengthy) that copies everything including tables, foreign keys, data, views, procedures, functions, triggers, and events. Here is the code:
/* This function takes the database connection, an existing database, and the new database and duplicates everything in the new database. */
function copyDatabase($c, $oldDB, $newDB) {
// creates the schema if it does not exist
$schema = "CREATE SCHEMA IF NOT EXISTS {$newDB};";
mysqli_query($c, $schema);
// selects the new schema
mysqli_select_db($c, $newDB);
// gets all tables in the old schema
$tables = "SELECT table_name
FROM information_schema.tables
WHERE table_schema = '{$oldDB}'
AND table_type = 'BASE TABLE'";
$results = mysqli_query($c, $tables);
// checks if any tables were returned and recreates them in the new schema, adds the foreign keys, and inserts the associated data
if (mysqli_num_rows($results) > 0) {
// recreates all tables first
while ($row = mysqli_fetch_array($results)) {
$table = "CREATE TABLE {$newDB}.{$row[0]} LIKE {$oldDB}.{$row[0]}";
mysqli_query($c, $table);
}
// resets the results to loop through again
mysqli_data_seek($results, 0);
// loops through each table to add foreign key and insert data
while ($row = mysqli_fetch_array($results)) {
// inserts the data into each table
$data = "INSERT IGNORE INTO {$newDB}.{$row[0]} SELECT * FROM {$oldDB}.{$row[0]}";
mysqli_query($c, $data);
// gets all foreign keys for a particular table in the old schema
$fks = "SELECT constraint_name, column_name, table_name, referenced_table_name, referenced_column_name
FROM information_schema.key_column_usage
WHERE referenced_table_name IS NOT NULL
AND table_schema = '{$oldDB}'
AND table_name = '{$row[0]}'";
$fkResults = mysqli_query($c, $fks);
// checks if any foreign keys were returned and recreates them in the new schema
// Note: ON UPDATE and ON DELETE are not pulled from the original so you would have to change this to your liking
if (mysqli_num_rows($fkResults) > 0) {
while ($fkRow = mysqli_fetch_array($fkResults)) {
$fkQuery = "ALTER TABLE {$newDB}.{$row[0]}
ADD CONSTRAINT {$fkRow[0]}
FOREIGN KEY ({$fkRow[1]}) REFERENCES {$newDB}.{$fkRow[3]}({$fkRow[1]})
ON UPDATE CASCADE
ON DELETE CASCADE;";
mysqli_query($c, $fkQuery);
}
}
}
}
// gets all views in the old schema
$views = "SHOW FULL TABLES IN {$oldDB} WHERE table_type LIKE 'VIEW'";
$results = mysqli_query($c, $views);
// checks if any views were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$view = "SHOW CREATE VIEW {$oldDB}.{$row[0]}";
$viewResults = mysqli_query($c, $view);
$viewRow = mysqli_fetch_array($viewResults);
mysqli_query($c, preg_replace("/CREATE(.*?)VIEW/", "CREATE VIEW", str_replace($oldDB, $newDB, $viewRow[1])));
}
}
// gets all triggers in the old schema
$triggers = "SELECT trigger_name, action_timing, event_manipulation, event_object_table, created
FROM information_schema.triggers
WHERE trigger_schema = '{$oldDB}'";
$results = mysqli_query($c, $triggers);
// checks if any triggers were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$trigger = "SHOW CREATE TRIGGER {$oldDB}.{$row[0]}";
$triggerResults = mysqli_query($c, $trigger);
$triggerRow = mysqli_fetch_array($triggerResults);
mysqli_query($c, str_replace($oldDB, $newDB, $triggerRow[2]));
}
}
// gets all procedures in the old schema
$procedures = "SHOW PROCEDURE STATUS WHERE db = '{$oldDB}'";
$results = mysqli_query($c, $procedures);
// checks if any procedures were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$procedure = "SHOW CREATE PROCEDURE {$oldDB}.{$row[1]}";
$procedureResults = mysqli_query($c, $procedure);
$procedureRow = mysqli_fetch_array($procedureResults);
mysqli_query($c, str_replace($oldDB, $newDB, $procedureRow[2]));
}
}
// gets all functions in the old schema
$functions = "SHOW FUNCTION STATUS WHERE db = '{$oldDB}'";
$results = mysqli_query($c, $functions);
// checks if any functions were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$function = "SHOW CREATE FUNCTION {$oldDB}.{$row[1]}";
$functionResults = mysqli_query($c, $function);
$functionRow = mysqli_fetch_array($functionResults);
mysqli_query($c, str_replace($oldDB, $newDB, $functionRow[2]));
}
}
// selects the old schema (a must for copying events)
mysqli_select_db($c, $oldDB);
// gets all events in the old schema
$query = "SHOW EVENTS
WHERE db = '{$oldDB}';";
$results = mysqli_query($c, $query);
// selects the new schema again
mysqli_select_db($c, $newDB);
// checks if any events were returned and recreates them in the new schema
if (mysqli_num_rows($results) > 0) {
while ($row = mysqli_fetch_array($results)) {
$event = "SHOW CREATE EVENT {$oldDB}.{$row[1]}";
$eventResults = mysqli_query($c, $event);
$eventRow = mysqli_fetch_array($eventResults);
mysqli_query($c, str_replace($oldDB, $newDB, $eventRow[3]));
}
}
}
You can also use
:-0
This sets the cursor at the present line (blank here) at the 0 column.
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
Here the solution from Jasmine in one line... (one more, tho simple!):
reader.GetSchemaTable().Select("ColumnName='MyCol'").Length > 0;
I don't fully understand what was the problem with the "update current of cursor" but it is solved by using the fetch statement twice for the inner cursor:
FETCH NEXT FROM INNER_CURSOR
WHILE (@@FETCH_STATUS <> -1)
BEGIN
UPDATE CONTACTS
SET INDEX_NO = @COUNTER
WHERE CURRENT OF INNER_CURSOR
SET @COUNTER = @COUNTER + 1
FETCH NEXT FROM INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
END
For preventing naming conflicts, only import the variables that you need:
variableInFile () {
variable="${1}"
file="${2}"
echo $(
source "${file}";
eval echo \$\{${variable}\}
)
}
First off, the facts:
if (booleanValue)
Will satisfy the if
statement for any truthy value of booleanValue
including true
, any non-zero number, any non-empty string value, any object or array reference, etc...
On the other hand:
if (booleanValue === true)
This will only satisfy the if
condition if booleanValue
is exactly equal to true
. No other truthy value will satisfy it.
On the other hand if you do this:
if (someVar == true)
Then, what Javascript will do is type coerce true
to match the type of someVar
and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid ==
because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid ==
entirely.
As an example of how confusing it can be:
var x;_x000D_
_x000D_
x = 0;_x000D_
console.log(x == true); // false, as expected_x000D_
console.log(x == false); // true as expected_x000D_
_x000D_
x = 1;_x000D_
console.log(x == true); // true, as expected_x000D_
console.log(x == false); // false as expected_x000D_
_x000D_
x = 2;_x000D_
console.log(x == true); // false, ??_x000D_
console.log(x == false); // false
_x000D_
For the value 2
, you would think that 2
is a truthy value so it would compare favorably to true
, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true
to the number 1
so it's comparing 2 == 1
which is certainly not what you likely intended.
So, buyer beware. It's likely best to avoid ==
in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.
So, it really depends upon the expected values for booleanValue
and how you want the code to work. If you know in advance that it's only ever going to have a true
or false
value, then comparing it explicitly with
if (booleanValue === true)
is just extra code and unnecessary and
if (booleanValue)
is more compact and arguably cleaner/better.
If, on the other hand, you don't know what booleanValue
might be and you want to test if it is truly set to true
with no other automatic type conversions allowed, then
if (booleanValue === true)
is not only a good idea, but required.
For example, if you look at the implementation of .on()
in jQuery, it has an optional return value. If the callback returns false
, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false
was returned, they check the return value explicity for === false
because they don't want undefined
or 0
or ""
or anything else that will automatically type-convert to false to also satisfy the comparison.
For example, here's the jQuery event handling callback code:
ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
You can see that jQuery is explicitly looking for ret === false
.
But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
Some useful are:
Free:
Paid:
The best entries in my opinion are Flexigrid and jQuery Grid.
Most of the people have given good answers. I would also like to contribute something here. I am providing the answer using lodash
library to iterate through all command line arguments we pass while starting the app:
// Lodash library
const _ = require('lodash');
// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
_.map(process.argv, (arg) => {
console.log(arg);
});
};
// Calling the function.
runApp();
To run above code just run following commands:
npm install
node index.js xyz abc 123 456
The result will be:
xyz
abc
123
456
ngAttr
directive can totally be of help here, as introduced in the official documentation
https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
For instance, to set the id
attribute value of a div
element, so that it contains an index, a view fragment might contain
<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>
which would get interpolated to
<div id="object-1"></div>
First create an xpath selector function.
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
To use the xpath selector with jquery, you can do like this:
$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');
Hope this can help.
Yes, just override the printMe()
method:
class Son extends Dad {
public static final String me = "son";
@Override
public void printMe() {
System.out.println(me);
}
}
Short Answer:
I did it. I wrote a function for dynamic usage for all the little people out there...
Working example which displays on the page
Working example logging to the console
Long Answer:
...Still did it.
It took me awhile to do it, since a psuedo element is not really on the page. While some of the answers above work in SOME scenarios, they ALL fail to be both dynamic and work in a scenario in which an element is both unexpected in size and position(such as absolute positioned elements overlaying a portion of the parent element). Mine does not.
Usage:
//some element selector and a click event...plain js works here too
$("div").click(function() {
//returns an object {before: true/false, after: true/false}
psuedoClick(this);
//returns true/false
psuedoClick(this).before;
//returns true/false
psuedoClick(this).after;
});
How it works:
It grabs the height, width, top, and left positions(based on the position away from the edge of the window) of the parent element and grabs the height, width, top, and left positions(based on the edge of the parent container) and compares those values to determine where the psuedo element is on the screen.
It then compares where the mouse is. As long as the mouse is in the newly created variable range then it returns true.
Note:
It is wise to make the parent element RELATIVE positioned. If you have an absolute positioned psuedo element, this function will only work if it is positioned based on the parent's dimensions(so the parent has to be relative...maybe sticky or fixed would work too....I dont know).
Code:
function psuedoClick(parentElem) {
var beforeClicked,
afterClicked;
var parentLeft = parseInt(parentElem.getBoundingClientRect().left, 10),
parentTop = parseInt(parentElem.getBoundingClientRect().top, 10);
var parentWidth = parseInt(window.getComputedStyle(parentElem).width, 10),
parentHeight = parseInt(window.getComputedStyle(parentElem).height, 10);
var before = window.getComputedStyle(parentElem, ':before');
var beforeStart = parentLeft + (parseInt(before.getPropertyValue("left"), 10)),
beforeEnd = beforeStart + parseInt(before.width, 10);
var beforeYStart = parentTop + (parseInt(before.getPropertyValue("top"), 10)),
beforeYEnd = beforeYStart + parseInt(before.height, 10);
var after = window.getComputedStyle(parentElem, ':after');
var afterStart = parentLeft + (parseInt(after.getPropertyValue("left"), 10)),
afterEnd = afterStart + parseInt(after.width, 10);
var afterYStart = parentTop + (parseInt(after.getPropertyValue("top"), 10)),
afterYEnd = afterYStart + parseInt(after.height, 10);
var mouseX = event.clientX,
mouseY = event.clientY;
beforeClicked = (mouseX >= beforeStart && mouseX <= beforeEnd && mouseY >= beforeYStart && mouseY <= beforeYEnd ? true : false);
afterClicked = (mouseX >= afterStart && mouseX <= afterEnd && mouseY >= afterYStart && mouseY <= afterYEnd ? true : false);
return {
"before" : beforeClicked,
"after" : afterClicked
};
}
Support:
I dont know....it looks like ie is dumb and likes to return auto as a computed value sometimes. IT SEEMS TO WORK WELL IN ALL BROWSERS IF DIMENSIONS ARE SET IN CSS. So...set your height and width on your psuedo elements and only move them with top and left. I recommend using it on things that you are okay with it not working on. Like an animation or something. Chrome works...as usual.
A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.
str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);
Using this approach, also special chars as the null byte, unicode characters and line breaks \r
and \n
are escaped properly in a relatively compact statement.
This works!
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.
<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
//xml code
</ScrollView>
</HorizontalScrollView>
Please try the following code snippet,
IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value),
Format(Avg(Fields!Vision_Score.Value)),
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))
hope it will help, Thank-you.
How about this, which I managed to achieve thanks, in part, to this post.
You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE
), inside several directories with a pattern (e.g. /logsapp1, /logsapp2
).
Each file has a pattern you want to grep (e.g. "init time"
), and you want to have the "init time"
of each file, but knowing which file it belongs to.
find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt
Then the outputfilename.txt
would be something like
./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms
In general
find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt
Explanation:
find
command will search the filenames based in the pattern
then, pipe xargs -I{}
will redirect the find
output to the {}
which will be the input for grep ""pattern" {}
Then the trick to make grep
display the filenames \dev\null
and finally, write the output in file with tee outputfile.txt
This worked for me in grep
version 9.0.5 build 1989.
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
You may need to know the status and update a ProgressBar during the file download or use credentials before making the request.
Here it is, an example that covers these options. Lambda notation and String interpolation has been used:
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
So the Enum
has a __members__
dict.
The solution that @ozgur proposed is really the best, but you can do this, which does the same thing, with more work
[color.value for color_name, color in Color.__members__.items()]
The __members__
dictionary could come in handy if you wanted to insert stuff dynamically in it... in some crazy situation.
[EDIT]
Apparently __members__
is not a dictionary, but a map proxy. Which means you can't easily add items to it.
You can however do weird stuff like MyEnum.__dict__['_member_map_']['new_key'] = 'new_value'
, and then you can use the new key like MyEnum.new_key
.... but this is just an implementation detail, and should not be played with. Black magic is payed for with huge maintenance costs.
Technically, I would describe an interface as a set of ways (methods, properties, accessors... the vocabulary depends on the language you are using) to interact with an object. If an object supports/implements an interface, then you can use all of the ways specified in the interface to interact with this object.
Semantically, an interface could also contain conventions about what you may or may not do (e.g., the order in which you may call the methods) and about what, in return, you may assume about the state of the object given how you interacted so far.
Import System.Web Or call the System.Web.HttpUtility which contains it
You will need to add the reference to the DLL if it isn't there already
string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);
public bool IsNumeric(string value)
{
return value.All(char.IsNumber);
}
This will return what you asked, but I wouldnt recommend using css like this. Use external CSS instead of inline css.
$("tr[id='pDetails']").attr("style").split(':')[1];
To toast in Android
Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_SHORT).show();
or
Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_LONG).show();
( LENGTH_SHORT and LENGTH_LONG are acting as boolean flags - which means you cant sent toast timer to miliseconds, but you need to use either of those 2 options )
class ArchiveUtil {
private static let PeopleKey = "PeopleKey"
private static func archivePeople(people : [Human]) -> NSData {
return NSKeyedArchiver.archivedData(withRootObject: people as NSArray) as NSData
}
static func loadPeople() -> [Human]? {
if let unarchivedObject = UserDefaults.standard.object(forKey: PeopleKey) as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Human]
}
return nil
}
static func savePeople(people : [Human]?) {
let archivedObject = archivePeople(people: people!)
UserDefaults.standard.set(archivedObject, forKey: PeopleKey)
UserDefaults.standard.synchronize()
}
}
class Human: NSObject, NSCoding {
var name:String?
var age:Int?
required init(n:String, a:Int) {
name = n
age = a
}
required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as? String
age = aDecoder.decodeInteger(forKey: "age")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
}
}
var people = [Human]()
people.append(Human(n: "Sazzad", a: 21))
people.append(Human(n: "Hissain", a: 22))
people.append(Human(n: "Khan", a: 23))
ArchiveUtil.savePeople(people: people)
let others = ArchiveUtil.loadPeople()
for human in others! {
print("name = \(human.name!), age = \(human.age!)")
}
Here is a more easier way of doing this if you are using Laravel PHP framework :
<?php
// usage anywhere
// returns HelloWorld
$name = class_basename('Path\To\YourClass\HelloWorld');
// usage inside a class
// returns HelloWorld
$name = class_basename(__CLASS__);
Disclaimer: I work at BrowserStack. [Confirmed]that whether am allowed to post this (Can I suggest a product of the company am working at?)
Debug Safari on iOS (not for Chrome as of now, read ahead for more details.)
How this works?
Using DevTools with Real Phones
Hover over the elements, edit HTML, CSS just like desktop browser devtools work.
Executing JavaScript in real phone using DevTools
Switch to Console
tab, execute JavaScript code, check console.log()
output and so on...
Network tab, check request headers, response and so on...
Support for DevTools on BrowserStack?
DevTools are available on :
Client browser needs to be Chrome or Firefox. That means you need to use Chrome or Firefox browser on MacOSX or Windows to use BrowserStack Real Device DevTools.
Note: You need to buy a plan to test on all real devices, as a free user, you'll get couple of Real Android devices (includes tablets) and couple of Real iOS devices (includes tablets). Also, emphasizing on the word Real Devices because they provide emulators as well.
More details on this, please refer to DevTools section on Mobile Features page.
The correct CSS for setting font-size is "font-size: 35px". I.e.:
<td style="padding-left: 5px; padding-bottom:3px; font size: 35px;">
Note that this sets the font size in pixels. You can also set it in *em*s or percentage. Learn more about fonts in CSS here: http://www.w3schools.com/css/css_font.asp
Study this code.. good luck
import java.util.*;
class Demo{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Input String : ");
String s1 = input.nextLine();
String[] tokens = s1.split("[\\s\\xA0]+");
System.out.println(tokens.length);
for(String s : tokens){
System.out.println(s);
}
}
}
You can use momentjs
to implement date-time filter in angularjs.
For example:
angular.module('myApp')
.filter('formatDateTime', function ($filter) {
return function (date, format) {
if (date) {
return moment(Number(date)).format(format || "DD/MM/YYYY h:mm A");
}
else
return "";
};
});
Where date is in time stamp format.
A solution I tend to use more and more is this one:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 1
for i, ax in enumerate(axs.ravel()): # 2
ax.set_title("Plot #{}".format(i)) # 3
You could use Matcher#start(group)
and Matcher#end(group)
to build a generic replacement method:
public static String replaceGroup(String regex, String source, int groupToReplace, String replacement) {
return replaceGroup(regex, source, groupToReplace, 1, replacement);
}
public static String replaceGroup(String regex, String source, int groupToReplace, int groupOccurrence, String replacement) {
Matcher m = Pattern.compile(regex).matcher(source);
for (int i = 0; i < groupOccurrence; i++)
if (!m.find()) return source; // pattern not met, may also throw an exception here
return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), replacement).toString();
}
public static void main(String[] args) {
// replace with "%" what was matched by group 1
// input: aaa123ccc
// output: %123ccc
System.out.println(replaceGroup("([a-z]+)([0-9]+)([a-z]+)", "aaa123ccc", 1, "%"));
// replace with "!!!" what was matched the 4th time by the group 2
// input: a1b2c3d4e5
// output: a1b2c3d!!!e5
System.out.println(replaceGroup("([a-z])(\\d)", "a1b2c3d4e5", 2, 4, "!!!"));
}
Check online demo here.
I managed to solve it adding this code, and building with gradle build
:
android {
...
signingConfigs {
release {
storeFile file("release.keystore")
storePassword "******"
keyAlias "******"
keyPassword "******"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
This generates a signed release apk file.
You will have to implement the Google Maps API projection in your language. I have the C# source code for this:
public class GoogleMapsAPIProjection
{
private readonly double PixelTileSize = 256d;
private readonly double DegreesToRadiansRatio = 180d / Math.PI;
private readonly double RadiansToDegreesRatio = Math.PI / 180d;
private readonly PointF PixelGlobeCenter;
private readonly double XPixelsToDegreesRatio;
private readonly double YPixelsToRadiansRatio;
public GoogleMapsAPIProjection(double zoomLevel)
{
var pixelGlobeSize = this.PixelTileSize * Math.Pow(2d, zoomLevel);
this.XPixelsToDegreesRatio = pixelGlobeSize / 360d;
this.YPixelsToRadiansRatio = pixelGlobeSize / (2d * Math.PI);
var halfPixelGlobeSize = Convert.ToSingle(pixelGlobeSize / 2d);
this.PixelGlobeCenter = new PointF(
halfPixelGlobeSize, halfPixelGlobeSize);
}
public PointF FromCoordinatesToPixel(PointF coordinates)
{
var x = Math.Round(this.PixelGlobeCenter.X
+ (coordinates.X * this.XPixelsToDegreesRatio));
var f = Math.Min(
Math.Max(
Math.Sin(coordinates.Y * RadiansToDegreesRatio),
-0.9999d),
0.9999d);
var y = Math.Round(this.PixelGlobeCenter.Y + .5d *
Math.Log((1d + f) / (1d - f)) * -this.YPixelsToRadiansRatio);
return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
}
public PointF FromPixelToCoordinates(PointF pixel)
{
var longitude = (pixel.X - this.PixelGlobeCenter.X) /
this.XPixelsToDegreesRatio;
var latitude = (2 * Math.Atan(Math.Exp(
(pixel.Y - this.PixelGlobeCenter.Y) / -this.YPixelsToRadiansRatio))
- Math.PI / 2) * DegreesToRadiansRatio;
return new PointF(
Convert.ToSingle(latitude),
Convert.ToSingle(longitude));
}
}
Source:
for mysql its length not len
SELECT MAX(LENGTH(Desc)) FROM table_name
Here are the steps:
It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),
There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you're looking for database support besides the main ones you'll have to write your own code.
You can't "execute" a DLL. You can execute functions within the DLL, as explained in the other answers. Although .EXE files and .DLL files are essentially identical in terms of format, the distinguishing feature of an .EXE is that it contains a designated "entry point" to go and do the thing the EXE was created to do. DLLs actually have something similar, but the purpose of the "dll main" is just to perform initialization and not fulfill the primary purpose of the DLL; that is for the (presumably) various other functions it contains.
You can execute any of the functions exported by a DLL, assuming you know which one you want to execute; an EXE may contain a whole lot of functions, but one and only one is specially designated to be executed simply by "running" it.
You need set the keyframes animation in you CSS. And use the keyframe with jQuery:
$('#myTest').css({"animation":"my-animation 2s infinite"});
_x000D_
#myTest {_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
@keyframes my-animation {_x000D_
0% {_x000D_
background: red; _x000D_
}_x000D_
50% {_x000D_
background: blue; _x000D_
}_x000D_
100% {_x000D_
background: green; _x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myTest"></div>
_x000D_
SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data
WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.
SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON
This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.
With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.
It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.
Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.
REST is over only HTTP
Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.
P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284
You need to update Anaconda using:
conda update
and
conda update anaconda-navigator
Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:
anaconda-navigator
If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.
What you want is the Arrays.toString(int[])
method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString
helper method for every different primitive java type; the one for int[]
says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (
"[]"
). Adjacent elements are separated by the characters", "
(a comma followed by a space). Elements are converted to strings as byString.valueOf(int)
. Returns"null"
ifa
is null.
Another solution, using another great feature:
:'<,'>norm A,
See :help :normal
.
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.
for Lat,Long in zip(Latitudes, Longitudes):
Simplest of all would be.
Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.
Inflate this view and set this to AlertDialog
Lets start with Layout file first.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<EditText
android:id="@+id/etComments"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:hint="Enter comments(Optional)"
android:inputType="textMultiLine"
android:lines="8"
android:maxLines="3"
android:minLines="6"
android:scrollbars="vertical" />
</LinearLayout>
final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");
final EditText etComments = (EditText) view.findViewById(R.id.etComments);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss()
}
});
alertDialog.setView(view);
alertDialog.show();
My experience is the same as the benchmarks. Python can be slow and uses more memory. I write much, much less code and it works the first time with much less debugging. Since it manages memory for me, I don't have to do any memory management, saving hours of chasing down core leaks.
What's your question?
There is no way you can hidde the keyboard properly with js because its a OS problem, so one thing you can easy do to "hidde" the keyboard, is instead of using an input Element you can make any "non-input html element" a key listener element just by adding the [tabindex] attribute, and then you can easily listen the keydown and keyup events and store the "$event.target.value" in a variable to get the input.
Try this method;
Shorthand method:
let variable1 = '';_x000D_
_x000D_
let variable2 = variable1 || 'new'_x000D_
console.log(variable2); // new
_x000D_
Longhand method:
let variable1 = 'ya';_x000D_
let varibale2;_x000D_
_x000D_
if (variable1 !== null || variable1 !== undefined || variable1 !== '')_x000D_
variable2 = variable1;_x000D_
_x000D_
console.log(variable2); // ya
_x000D_
In a Firebird database the AFTER myOtherColumn
does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.
I needed the same thing and found the following working for me:
git log -n1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'
The --date=format
formats the date output where the --pretty
tells what to print.
I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.
After some trial and error, I discovered that with IIS, $_SERVER['HTTPS']
is
set to off
for non-TLS connections. I thought the following code should
help any other IIS users who come to this question via search engine.
<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
$redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $redirect_url");
exit();
}
?>
Edit: From another Stack Overflow answer,
a simpler solution is to check if($_SERVER["HTTPS"] != "on")
.
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
Using implode()
, you can turn the array into a string.
$str = implode(',', $array); // 33160,33280,33180,...
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.
The following is an another example of print stack of the Exception in Java.
public class Demo {
public static void main(String[] args) {
try {
ExceptionFunc();
} catch(Throwable e) {
e.printStackTrace();
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception in Java...");
StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",5)
};
t.setStackTrace(trace);
throw t;
}
}
java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
... somewhere else in another class ...
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}
You can limit the depth of the history while cloning:
--depth <depth>
Create a shallow clone with a history truncated to the specified
number of revisions.
Use this if you want limited history, but still some.
It may sound banal, but for me Build > Clean Project
fixed this error without any other changes.
@Mock
is used to declare/mock the references of the dependent beans, while @InjectMocks
is used to mock the bean for which test is being created.
For example:
public class A{
public class B b;
public void doSomething(){
}
}
test for class A
:
public class TestClassA{
@Mocks
public class B b;
@InjectMocks
public class A a;
@Test
public testDoSomething(){
}
}
You do say that the comparison is for sorting purposes. Then I suggest instead:
"a".localeCompare("b");
It returns -1
since "a" < "b"
, 1
or 0
otherwise, like you need for Array.prototype.sort()
Keep in mind that sorting is locale dependent. E.g. in German, ä
is a variant of a
, so "ä".localeCompare("b", "de-DE")
returns -1
. In Swedish, ä
is one of the last letters in the alphabet, so "ä".localeCompare("b", "se-SE")
returns 1
.
Without the second parameter to localeCompare
, the browser's locale is used. Which in my experience is never what I want, because then it'll sort differently than the server, which has a fixed locale for all users.
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT
region_ibfk_1
FOREIGN KEY (country_id
) REFERENCEScountry
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1
;
And finally an:
alter table region drop column country_id;
And you are good to go!
Device: iPad Mini
OS: iOS 9 Beta 3
App downloaded from: Hockey App
Provisioning profile with Trust issues: Enterprise
In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.
Here are the steps that I followed:
That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)
Its very simple
function archiveRemove(any) {
var click = $(any);
var id = click.attr("id");
swal.fire({
title: 'Are you sure !',
text: "?????",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'yes!',
cancelButtonText: 'no'
}).then(function (success) {
if (success) {
$('a[id="' + id + '"]').parents(".archiveItem").submit();
}
})
}
Verify the length
property of the array to be greater than 0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items">
evaluates always to true
, even if the array is empty.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
You need turn on the POP mail and IMAP mail feature in setting of the email you are using to send mail. Good luck!
This is how it worked for me :
df= pd.DataFrame([d.keys(), d.values()]).T
df.columns= ['keys', 'values'] # call them whatever you like
I hope this helps
To stop the service we must use the method stopService()
:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
//startService(myService);
stopService(myService);
then the method onDestroy()
in the service is called:
@Override
public void onDestroy() {
Log.i(TAG, "onCreate() , service stopped...");
}
Here is a complete example including how to stop the service.
I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select
input, assign its text to the newVal
variable and then apply that variable to the value
attribute of the #costLabel
label:
$(document).ready(
function() {
$('select[name=package]').change(
function(){
var newText = $('option:selected',this).text();
$('#costLabel').text('Total price: ' + newText);
}
);
}
);
<form name="thisForm" id="thisForm" action="#" method="post">
<fieldset>
<select name="package" id="package">
<option value="standard">Standard - €55 Monthly</option>
<option value="standardAnn">Standard - €49 Monthly</option>
<option value="premium">Premium - €99 Monthly</option>
<option value="premiumAnn" selected="selected">Premium - €89 Monthly</option>
<option value="platinum">Platinum - €149 Monthly</option>
<option value="platinumAnn">Platinum - €134 Monthly</option>
</select>
</fieldset>
<fieldset>
<label id="costLabel" name="costLabel">Total price: </label>
</fieldset>
</form>
Working demo of the above at: JS Bin
There are few ways to create empty Set in Python :
So, This are 2 ways to create empty Set.
Even though --files
is no longer supported, you can use an env variable to provide a list of files:
// karma.conf.js
function getSpecs(specList) {
if (specList) {
return specList.split(',')
} else {
return ['**/*_spec.js'] // whatever your default glob is
}
}
module.exports = function(config) {
config.set({
//...
files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
});
});
Then in CLI:
$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run
Your demo didn't expose memcpy drawbacks because of "bad" compiler, it does you a favor in Debug version. A release version, however, gives you the same output, but because of optimization.
memcpy(str1 + 2, str1, 4);
00241013 mov eax,dword ptr [str1 (243018h)] // load 4 bytes from source string
printf("New string: %s\n", str1);
00241018 push offset str1 (243018h)
0024101D push offset string "New string: %s\n" (242104h)
00241022 mov dword ptr [str1+2 (24301Ah)],eax // put 4 bytes to destination
00241027 call esi
The register %eax
here plays as a temporary storage, which "elegantly" fixes overlap issue.
The drawback emerges when copying 6 bytes, well, at least part of it.
char str1[9] = "aabbccdd";
int main( void )
{
printf("The string: %s\n", str1);
memcpy(str1 + 2, str1, 6);
printf("New string: %s\n", str1);
strcpy_s(str1, sizeof(str1), "aabbccdd"); // reset string
printf("The string: %s\n", str1);
memmove(str1 + 2, str1, 6);
printf("New string: %s\n", str1);
}
Output:
The string: aabbccdd
New string: aaaabbbb
The string: aabbccdd
New string: aaaabbcc
Looks weird, it's caused by optimization, too.
memcpy(str1 + 2, str1, 6);
00341013 mov eax,dword ptr [str1 (343018h)]
00341018 mov dword ptr [str1+2 (34301Ah)],eax // put 4 bytes to destination, earlier than the above example
0034101D mov cx,word ptr [str1+4 (34301Ch)] // HA, new register! Holding a word, which is exactly the left 2 bytes (after 4 bytes loaded to %eax)
printf("New string: %s\n", str1);
00341024 push offset str1 (343018h)
00341029 push offset string "New string: %s\n" (342104h)
0034102E mov word ptr [str1+6 (34301Eh)],cx // Again, pulling the stored word back from the new register
00341035 call esi
This is why I always choose memmove
when trying to copy 2 overlapped memory blocks.
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range
you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2
not being found in the searched range Sheet1!A1:A65536
. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet
is Sheet1
, then using Range("D2")
without qualifying it will be searching for Sheet1!D2
, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup
(although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP
as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A
in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...
).
Using =VLOOKUP...
is fundamentally different from Application.WorksheetFunction.VLookup
: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).
Please try window.onbeforeunload
instead for window.onunload
for chrome.
You can also try calling onbeforeunload
from the body>
tag which might work in chrome.
However, we do have a problem with unload function in chrome browser. please check
location.href does not work in chrome when called through the body/window unload event
I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...
Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
Dim FileNames As String()
Try
FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
Catch
FileNames = Nothing
End Try
Return FileNames
End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
Val = CType(obj, String).ToString
End Sub
End Class
I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.
NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.
Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.
In SSMS:-
CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';
CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO
then call it
SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')
NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.
ALTER ASSEMBLY [CLRFilesInDirAssembly]
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
and wullah! that should work.
There are some really good answers and attempts to answer your question here. I am not an encoding master, but I understand your desire to have a pure UTF-8 stack all the way through to your database. I have been using MySQL's utf8mb4
encoding for tables, fields, and connections.
My situation boiled down to "I just want my sanitizers, validators, business logic, and prepared statements to deal with UTF-8 when data comes from HTML forms, or e-mail registration links." So, in my simple way, I started off with this idea:
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
throw new RuntimeException
UTF-8
, carry on.Else, if it is ISO-8859-1
or ASCII
a. Attempt conversion to UTF-8 (wait, not finished)
b. Detect the encoding of the converted value
c. If the reported encoding and converted value are both UTF-8
, carry on.
d. Else, throw new RuntimeException
From my abstract class Sanitizer
private function isUTF8($encoding, $value)
{
return (($encoding === 'UTF-8') && (utf8_encode(utf8_decode($value)) === $value));
}
private function utf8tify(&$value)
{
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
mb_internal_encoding('UTF-8');
mb_substitute_character(0xfffd); //REPLACEMENT CHARACTER
mb_detect_order($encodings);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if (!$stringEncoding) {
$value = null;
throw new \RuntimeException("Unable to identify character encoding in sanitizer.");
}
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = mb_convert_encoding($value, 'UTF-8', $stringEncoding);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = null;
throw new \RuntimeException("Unable to convert character encoding from ISO-8859-1, or ASCII, to UTF-8 in Sanitizer.");
}
}
return;
}
One could make an argument that I should separate encoding concerns from my abstract Sanitizer
class and simply inject an Encoder
object into a concrete child instance of Sanitizer
. However, the main problem with my approach is that, without more knowledge, I simply reject encoding types that I do not want (and I am relying on PHP mb_* functions). Without further study, I cannot know if that hurts some populations or not (or, if I am losing out on important information). So, I need to learn more. I found this article.
Moreover, what happens when encrypted data is added to my email registration links (using OpenSSL
or mcrypt
)? Could this interfere with decoding? What about Windows-1252? What about security implications? The use of utf8_decode()
and utf8_encode()
in Sanitizer::isUTF8
are dubious.
People have pointed out short-comings in the PHP mb_* functions. I never took time to investigate iconv
, but if it works better than mb_*functions, let me know.
You have to specify the width to the body for it to center on the page.
Or put all the content in the div and center it.
<body>
<div>
jhfgdfjh
</div>
</body>?
div {
margin: 0px auto;
width:400px;
}
?
Check the pointer for NULL
and then using strlen
to see if it returns 0
.
NULL
check is important because passing NULL
pointer to strlen
invokes an Undefined Behavior.
Google has updated the Virtual Device targeting API 23. It now comes with Google Play Services 9.0.80. So if you are using Google Maps API V 2.0 (I'm using play-services-maps:9.0.0 and play-services-location.9.0.0) no workaround necessary. It just works!
I suggest
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
Check this demo.
To save $4.99 for a one time use and no dealing with HomeBrew and no counting empty lines.
find . -name "*.swift" -print0 | xargs -0 wc -l
If you want to exclude pods:
find . -path ./Pods -prune -o -name "*.swift" -print0 ! -name "/Pods" | xargs -0 wc -l
If your project has objective c and swift:
find . -type d \( -path ./Pods -o -path ./Vendor \) -prune -o \( -iname \*.m -o -iname \*.mm -o -iname \*.h -o -iname \*.swift \) -print0 | xargs -0 wc -l
distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.
Example:
$ hadoop distcp <src> <dst>
there few options you can set for distcp
-m for no. of mapper for copying data this will increase speed of copying.
-atomic for auto commit the data.
-update will only update data that is in old version.
There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.
I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:
(left pane must be in project view, not android for this path) app->gradle->wrapper->gradle-wrapper.properties
it has a line like this, indicating the gradle version:
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip
There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)
If by mistake, you have deleted your Tomcat Server and Eclipse is not showing more options (Next button will be inactive) then in this case follow the bellow steps:
First remove the two files from the following path:
And that two files are :
After deleting/removing the above two files from the workspace, Restart the Eclipse IDE.
Change to the Server View, Right Click 'New', Window 'Define a New Server' is shown, --> Select the Apache Folder, choose Tomcat-Version
Browse to the unzipped 'Apache-Tomcat folder', choose the second level
Now you are able to add/configure your new Tomcat Server. (Now you will see the 'Next' button will become active, and you can then follow the normal instructions)
Below are my personal learning notes on GIT tracking branches, hopefully it will be helpful for future visitors:
There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat()
, but that's way slower than just +
Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.
Simply put: +
is the fastest.
I am fairly new to Javascript. But this is what I understood:
JSON.parse()
returns SyntaxError
exceptions when invalid JSON is provided as its first parameter. So. It would be better to catch that exception as such like as follows:
try {
let sData = `
{
"id": "1",
"name": "UbuntuGod",
}
`;
console.log(JSON.parse(sData));
} catch (objError) {
if (objError instanceof SyntaxError) {
console.error(objError.name);
} else {
console.error(objError.message);
}
}
The reason why I made the words "first parameter" bold is that JSON.parse()
takes a reviver function as its second parameter.
I think, bwawok's answer is wrong at some point:
if you do
git reset --soft c14809fa
It will make your local files changed to be like they were then, but leave your history etc. the same.
According to manual: git-reset, "git reset --soft"...
does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).
The command for bwawok's answer might be:
git checkout <commit>
You can use this to peek at old revision: How did my code look yesterday?
(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)
That is because you are not fully qualifying your cells object. Try this
With Worksheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
Notice the DOT before Cells?
Try to update npm,It works for me
[sudo] npm install -g npm
The Swift version from String to Data and back to String:
Xcode 10.1 • Swift 4.2.1
extension Data {
var string: String? {
return String(data: self, encoding: .utf8)
}
}
extension StringProtocol {
var data: Data {
return Data(utf8)
}
}
extension String {
var base64Decoded: Data? {
return Data(base64Encoded: self)
}
}
Playground
let string = "Hello World" // "Hello World"
let stringData = string.data // 11 bytes
let base64EncodedString = stringData.base64EncodedString() // "SGVsbG8gV29ybGQ="
let stringFromData = stringData.string // "Hello World"
let base64String = "SGVsbG8gV29ybGQ="
if let data = base64String.base64Decoded {
print(data) // 11 bytes
print(data.base64EncodedString()) // "SGVsbG8gV29ybGQ="
print(data.string ?? "nil") // "Hello World"
}
let stringWithAccent = "Olá Mundo" // "Olá Mundo"
print(stringWithAccent.count) // "9"
let stringWithAccentData = stringWithAccent.data // "10 bytes" note: an extra byte for the acute accent
let stringWithAccentFromData = stringWithAccentData.string // "Olá Mundo\n"
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
You can use the button :
1 - make the text empty
2 - set the background for it
+3 - you can use the selector to more useful and nice button
About the imagebutton you can set the image source and the background the same picture and it must be (*.png) when you do it you can make any design for the button
and for more beauty button use the selector //just Google it ;)
Can use FullScreen API like this
function toggleFullscreen() {
let elem = document.querySelector('#demo-video');
if (!document.fullscreenElement) {
elem.requestFullscreen().catch(err => {
alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
});
} else {
document.exitFullscreen();
}
}
Demo
const elem = document.querySelector('#park-pic');_x000D_
_x000D_
elem.addEventListener("click", function(e) {_x000D_
toggleFullScreen();_x000D_
}, false);_x000D_
_x000D_
function toggleFullScreen() {_x000D_
_x000D_
if (!document.fullscreenElement) {_x000D_
elem.requestFullscreen().catch(err => {_x000D_
alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);_x000D_
});_x000D_
} else {_x000D_
document.exitFullscreen();_x000D_
}_x000D_
}
_x000D_
#container{_x000D_
border:1px solid #aaa;_x000D_
padding:10px;_x000D_
}_x000D_
#park-pic {_x000D_
width: 100%;_x000D_
max-height: 70vh;_x000D_
}
_x000D_
<div id="container">_x000D_
<p>_x000D_
<a href="#" id="toggle-fullscreen">Toggle Fullscreen</a>_x000D_
</p>_x000D_
<img id="park-pic"_x000D_
src="https://storage.coverr.co/posters/Skate-park"></video>_x000D_
</div>
_x000D_
I had the same problem. The solution turned out to be much simpler. It appears that a datatable wants the method in the form of a getter, ie getSomeMethod(), not just someMethod(). In my case in the datatable I was calling findResults. I changed the method in my backing bean to getFindResults() and it worked.
A commandButton worked find without the get which served to make it only more confusing.
How about:
myString.Any(x => Char.IsWhiteSpace(x))
Or if you like using the "method group" syntax:
myString.Any(Char.IsWhiteSpace)
New, improved answer to an old, frequently asked question...
How could I get its parent? Result should be the
store
node.
parent::
or ancestor::
axisMost answers here select the title
and then traverse up to the targeted parent or ancestor (store
) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent::
or ancestor::
axes:
//*[book/title = "50"]
Should the intervening elements vary in name:
//*[*/title = "50"]
Or, in name and depth:
//*[.//title = "50"]
...I have a string "-9o0-9909" and I want to replace it with another string.
The code below will do that.
var str = '-9o0-9909';
str = 'new string';
Jokes aside, replacing text nodes is not trivial with JavaScript.
I've written a post about this: Replacing text with JavaScript.
Type aptitude
to start the package manager. There you can see which applications are installed.
Use /
to search for packages. Try searching for apache2
and php5
(or whatever versions you want to use). If they are installed, they should be bold and have an i
in front of them. If they are not installed (p
in front of the line) and you want to install them (and you have root permissions), use +
to select them and then g
(twice) to install it.
Word of warning: Before doing that, it might be wise to have a quick look at some aptitude tutorial on the web.
Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.
result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result;
do
`screen -X -S $i quit`;
done
If you found authentication error problem when you entered correct password and username it's git problem. To solves this problem when you are installing the git in your machine uncheck the enable git credential manager
There is the index
method, i = array.index(value)
, but I don't think you can specify a custom comparison operator. It wouldn't be hard to write your own function to do so, though:
def custom_index(array, compare_function):
for i, v in enumerate(array):
if compare_function(v):
return i
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }
In Swift 5:
label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 1)
btw, the value of limitedToNumberOfLines
depends on your label's text lines you want.
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Here is a quick console program to make it clear to those who follow. The TaskToDo
method is your long running method that you want to make async. Making it run async is done by the TestAsync
method. The test loops method just runs through the TaskToDo
tasks and runs them async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestingAsync
{
class Program
{
static void Main(string[] args)
{
TestLoops();
Console.Read();
}
private static async void TestLoops()
{
for (int i = 0; i < 100; i++)
{
await TestAsync(i);
}
}
private static Task TestAsync(int i)
{
return Task.Run(() => TaskToDo(i));
}
private async static void TaskToDo(int i)
{
await Task.Delay(10);
Console.WriteLine(i);
}
}
}
Here is my solution.
Tested with IE, Opera, Chrome, FireFox, Safari, as Phonegap WebApp on IOS 8 and as Phonegap WebApp on Android 4.4.2
This solution isn't working with FireFox on localhost.
=================================================================================
onlineCheck.js (filepath: "root/js/onlineCheck.js ):
var isApp = false;
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
isApp = true;
}
function isOnlineTest() {
alert(checkOnline());
}
function isBrowserOnline(no,yes){
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(){
if(no instanceof Function){
no();
}
}
xhr.open("GET","checkOnline.php",true);
xhr.send();
}
function checkOnline(){
if(isApp)
{
var xhr = new XMLHttpRequest();
var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";
try {
xhr.open('HEAD', file , false);
xhr.send(null);
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e)
{
return false;
}
}else
{
var tmpIsOnline = false;
tmpIsOnline = navigator.onLine;
if(tmpIsOnline || tmpIsOnline == "undefined")
{
try{
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
tmpIsOnline = true;
}
xhr.onerror = function(){
tmpIsOnline = false;
}
xhr.open("GET","checkOnline.php",false);
xhr.send();
}catch (e){
tmpIsOnline = false;
}
}
return tmpIsOnline;
}
}
=================================================================================
index.html (filepath: "root/index.html"):
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="js/onlineCheck.js" ></script>
...
</head>
...
<body onload="onLoad()">
...
<div onclick="isOnlineTest()">
Online?
</div>
...
</body>
</html>
=================================================================================
checkOnline.php (filepath: "root"):
<?php echo 'true'; ?>
Check App is installed or not in Android by using kotlin.
Creating kotlin extension.
fun PackageManager.isAppInstalled(packageName: String): Boolean = try {
getApplicationInfo(packageName, PackageManager.GET_META_DATA)
true
} catch (e: Exception) {
false
}
Now, can check if app is install or not
if (packageManager.isAppInstalled("AppPackageName")) {
// App is installed
}else{
// App is not installed
}
With javascript all arrays are flexible. You can simply do something like the following:
var myArray = [];
myArray.push(object);
myArray.push(anotherObject);
// ...
: | git mktree | git diff --shortstat --stdin
Or:
git ls-tree @ | sed '1i\\' | git mktree --batch | xargs | git diff-tree --shortstat --stdin
Found a method (I modified it a bit) that worked perfectly for me: iphone UIImageView rotation
#import <QuartzCore/QuartzCore.h>
- (void) runSpinAnimationOnView:(UIView*)view duration:(CGFloat)duration rotations:(CGFloat)rotations repeat:(float)repeat {
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
rotationAnimation.duration = duration;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = repeat ? HUGE_VALF : 0;
[view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
Now with Ruby 2.3 you can use &.
operator ('lonely operator') to check for nil
at the same time as accessing a value.
@person&.spouse&.name
https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#Other_operators
Use #try
instead so you don't have to keep checking for nil
.
http://api.rubyonrails.org/classes/Object.html#method-i-try
@person.try(:spouse).try(:name)
instead of
@person.spouse.name if @person && @person.spouse
Visual Studio Code: Version: 1.53.2
If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.
Go to Edit > Replace in Files
From there it is similar to the search funtionality for a single file.
I changed the name of a class I was using across files and this worked perfectly.
Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.
I spent a while developing a better solution to this. It can handle very big numbers but once they get over 16 digits you have pass the number in as a string. Something about the limit of JavaScript numbers.
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");
_x000D_
Make sure to use cascade
constraint at the end to automatically drop all objects that depend on the table (such as views and projections).
drop table if exists tableName cascade;
One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}
i am using this two method steps for preserve same text which is in textarea to store in mysql and at a getting time i can also simply displaying plain text.....
step 1:
$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));
In query enter $textToStore
....
step 2:
write code for select query...and direct echo values....
It works
In a node.js server console.log
outputs to the terminal window, not to the browser's console window.
How are you running your server? You should see the output directly after you start it.
The second method creates the instance on the stack, along with such things as something declared int
and the list of parameters that are passed into the function.
The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass
has been allocated on the heap - or free store.
The first method also requires that you delete
what you create with new
, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).
Even on a plain x86 32 bit platform, you can get a variety of pointer sizes, try this out for an example:
struct A {};
struct B : virtual public A {};
struct C {};
struct D : public A, public C {};
int main()
{
cout << "A:" << sizeof(void (A::*)()) << endl;
cout << "B:" << sizeof(void (B::*)()) << endl;
cout << "D:" << sizeof(void (D::*)()) << endl;
}
Under Visual C++ 2008, I get 4, 12 and 8 for the sizes of the pointers-to-member-function.
Raymond Chen talked about this here.