I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool
can do the whole job:
keytool -printcert -sslserver host[:port] -rfc >tempfile
keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile
# or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]
Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:
openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options
# including actual value, envvar, or file; see the openssl(1ssl) man page
Keystore is used by a server to store private keys, and Truststore is used by third party client to store public keys provided by server to access. I have done that in my production application. Below are the steps for generating java certificates for SSL communication:
keytool -genkey -keystore server.keystore -alias mycert -keyalg RSA -keysize 2048 -validity 3950
keytool -selfcert -alias mycert -keystore server.keystore -validity 3950
keytool -export -alias mycert -keystore server.keystore -rfc -file mycert.cer
keytool -importcert -alias mycert -file mycert.cer -keystore truststore
Your keystore will be in your JAVA_HOME---> JRE -->lib---> security--> cacerts
. You need to check where your JAVA_HOME is configured, possibly one of these places,
Computer--->Advanced --> Environment variables---> JAVA_HOME
Your server startup batch files.
In your import command -keystore cacerts (give full path to the above JRE here instead of just saying cacerts).
keytool is part of the JDK.
Try to prepend %{JAVA_HOME}\
to the exec statement or c:\{path to jdk}\bin
.
When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR
keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
complete example here: How to create CSR with SANs using keytool
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
If you're trying to do stuff with the Java default system keystore (cacerts
), then the default password is changeit
.
You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.
(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)
If you are using windows8:
command prompt
command prompt
and click Run as administrator
. Then execute the keytool command.No need to use the command line.
If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.
The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.
The SDK tools create the debug keystore/key with predetermined names/passwords:
Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"
If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)
Caution: You cannot release your application to the public when signed with the debug certificate.
Source: Developer.Android
It is not guaranteed that generating hashkey with this single openssl method will work. If it does not work for me. But thanks for giving me a direction to solve my issue.
Guaranteed Solution : You need to break the whole command in separate commands and have to write output of every execution in file.
You can take the help from the following link :
http://www.helloandroid.com/tutorials/using-facebook-sdk-android-development-part-1
Enjoy :)
The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.
install certificate in java linux
/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password
jarsigner can use your pfx file as the keystore for signing your jar. Be sure that your pfx file has the private key and the cert chain when you export it. There is no need to convert to other formats. The trick is to obtain the Alias of your pfx file:
keytool -list -storetype pkcs12 -keystore your_pfx_file -v | grep Alias
Once you have your alias, signing is easy
jarsigner.exe -storetype pkcs12 -keystore pfx_file jar_file "your alias"
The above two commands will prompt you for the password you specified at pfx export. If you want to have your password hang out in clear text use the -storepass switch before the -keystore switch
Once signed, admire your work:
jarsigner.exe -verify -verbose -certs yourjarfile
The accepted answer is fine, but I'd like to add something to this as I was using IntelliJ on Mac and couldn't get it to work using the JAVA_HOME
path variable.
It turns out Java Home was different when running the application from IntelliJ.
To figure out exactly where it is, you can just do System.getProperty("java.home")
as that's where the trusted certificates are read from.
The easiest is probably to create a PKCS#12 file using OpenSSL:
openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12
You should be able to use the resulting file directly using the PKCS12
keystore type.
If you really need to, you can convert it to JKS using keytool -importkeystore
(available in keytool
from Java 6):
keytool -importkeystore -srckeystore abc.p12 \
-srcstoretype PKCS12 \
-destkeystore abc.jks \
-deststoretype JKS
In my case, I was getting error connecting to AWS Gov Postgres RDS. There is a separate link for GOV RDS CA certs- https://s3.us-gov-west-1.amazonaws.com/rds-downloads/rds-combined-ca-us-gov-bundle.pem
Add this pem certs to cacerts of java. You can use below script.
------WINDOWDS STEPS-------
Script code:
#!/usr/bin/env sh
OLDDIR="$PWD"
CACERTS_FILE=cacerts
cd /c/rds-ca
echo "Downloading RDS certificates..."
curl https://s3.us-gov-west-1.amazonaws.com/rds-downloads/rds-combined-ca-us-gov-bundle.pem > rds-combined-ca-bundle.pem
csplit -sk rds-combined-ca-bundle.pem "/-BEGIN CERTIFICATE-/" "{$(grep -c 'BEGIN CERTIFICATE' rds-combined-ca-bundle.pem | awk '{print $1 - 2}')}"
for CERT in xx*; do
# extract a human-readable alias from the cert
ALIAS=$(openssl x509 -noout -text -in $CERT |
perl -ne 'next unless /Subject:/; s/.*CN=//; print')
echo "importing $ALIAS"
keytool -import \
-keystore $CACERTS_FILE \
-storepass changeit -noprompt \
-alias "$ALIAS" -file $CERT
done
cd "$OLDDIR"
echo "$NEWDIR"
Add your JDK's /bin folder to the PATH
environmental variable. You can do this under System settings > Environmental variables, or via CLI:
set PATH=%PATH%;C:\Program Files\Java\jdk1.7.0_80\bin
Close and reopen your CLI window
This is due to path not set where keytool.exe present.
Open command prompt in windows machine, traverse where you would like to run keytool cmd and set path where keytool.exe present
Step 1 : Open cmd promt and run "cd C:\Program Files\Java\jdk1.8.0_131\jre\lib\security"
Step 2 : Run below cmd to set path using "set PATH=C:\Program Files\Java\jdk1.8.0_131\bin"
Step 3 : Run keytool cmd, now it will be able to recognize.
A keystore needs a keystore file. The KeyStore
class needs a FileInputStream
. But if you supply null (instead of FileInputStream
instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool
.
Following code creates an empty keystore with empty password
KeyStore ks2 = KeyStore.getInstance("jks"); ks2.load(null,"".toCharArray()); FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore"); ks2.store(out, "".toCharArray());
Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
In Windows 10, you need to add a double slash
./keytool -genkey -v -keystore c:\\Users\\USERNAME\\youralias.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias youralias
If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin
This can also be due to environment variable CATALINA_HOME in your system. In our organization there were several cases where JNLP applications just refused to start without logging anything and emptying CATALINA_HOME solved the issue.
I had the environment variable set in the command prompt and it didn't appear in GUI. I'm not sure if setx command or register removal commands did the trick. Restart seems to be necessary after removing the variable.
Apart from the DATEDIFF you can also use the TIMEDIFF function or the TIMESTAMPDIFF.
EXAMPLE
SET @date1 = '2010-10-11 12:15:35', @date2 = '2010-10-10 00:00:00';
SELECT
TIMEDIFF(@date1, @date2) AS 'TIMEDIFF',
TIMESTAMPDIFF(hour, @date1, @date2) AS 'Hours',
TIMESTAMPDIFF(minute, @date1, @date2) AS 'Minutes',
TIMESTAMPDIFF(second, @date1, @date2) AS 'Seconds';
RESULTS
TIMEDIFF : 36:15:35
Hours : -36
Minutes : -2175
Seconds : -130535
The guy that did AForge did a fairly good job but it's not commercial quality. It's great to learn from but you can tell he was learning too so he has some pretty serious mistakes like assuming the size of an image instead of using the correct bits per pixel.
I'm not knocking the guy, I respect the heck out of him for learning all that and show us how to do it. I think he's a Ph.D now or at least he's about to be so he's really smart it's just not a commercially usable library.
The Math.Net library has its own weirdness when working with Fourier transforms and complex images/numbers. Like, if I'm not mistaken, it outputs the Fourier transform in human viewable format which is nice for humans if you want to look at a picture of the transform but it's not so good when you are expecting the data to be in a certain format (the normal format). I could be mistaken about that but I just remember there was some weirdness so I actually went to the original code they used for the Fourier stuff and it worked much better. (ExocortexDSP v1.2 http://www.exocortex.org/dsp/)
Math.net also had some other funkyness I didn't like when dealing with the data from the FFT, I can't remember what it was I just know it was much easier to get what I wanted out of the ExoCortex DSP library. I'm not a mathematician or engineer though; to those guys it might make perfect sense.
So! I use the FFT code yanked from ExoCortex, which Math.Net is based on, without anything else and it works great.
And finally, I know it's not C#, but I've started looking at using FFTW (http://www.fftw.org/). And this guy already made a C# wrapper so I was going to check it out but haven't actually used it yet. (http://www.sdss.jhu.edu/~tamas/bytes/fftwcsharp.html)
OH! I don't know if you are doing this for school or work but either way there is a GREAT free lecture series given by a Stanford professor on iTunes University.
https://podcasts.apple.com/us/podcast/the-fourier-transforms-and-its-applications/id384232849
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
mysqldump -uusername -ppassword -c -e --default-character-set=utf8 --single-transaction --skip-set-charset --add-drop-database -B dbname > dump.sql
cp dump.sql dump-fixed.sql
vim dump-fixed.sql
:%s/DEFAULT CHARACTER SET latin1/DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci/
:%s/DEFAULT CHARSET=latin1/DEFAULT CHARSET=utf8/
:wq
mysql -uusername -ppassword < dump-fixed.sql
For bash built into Windows 10, I added this to .bash_profile:
if [ -z $SSH_AUTH_SOCK ]; then
if [ -r ~/.ssh/env ]; then
source ~/.ssh/env
if [ `ps -p $SSH_AGENT_PID | wc -l` = 1 ]; then
rm ~/.ssh/env
unset SSH_AUTH_SOCK
fi
fi
fi
if [ -z $SSH_AUTH_SOCK ]; then
ssh-agent -s | sed 's/^echo/#echo/'> ~/.ssh/env
chmod 600 ~/.ssh/env
source ~/.ssh/env > /dev/null 2>&1
fi
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.
should means: At least one of these clauses must match, like logical OR.
Basically they are used like logical operators AND and OR. See this.
Now in a bool query:
must means: Clauses that must match for the document to be included.
should means: If these clauses match, they increase the _score
; otherwise, they have no effect. They are simply used to refine the relevance score for each document.
Yes you can use multiple filters inside must
.
If you understand how factors are stored, you can avoid using apply-based functions to accomplish this. Which isn't at all to imply that the apply solutions don't work well.
Factors are structured as numeric indices tied to a list of 'levels'. This can be seen if you convert a factor to numeric. So:
> fact <- as.factor(c("a","b","a","d")
> fact
[1] a b a d
Levels: a b d
> as.numeric(fact)
[1] 1 2 1 3
The numbers returned in the last line correspond to the levels of the factor.
> levels(fact)
[1] "a" "b" "d"
Notice that levels()
returns an array of characters. You can use this fact to easily and compactly convert factors to strings or numerics like this:
> fact_character <- levels(fact)[as.numeric(fact)]
> fact_character
[1] "a" "b" "a" "d"
This also works for numeric values, provided you wrap your expression in as.numeric()
.
> num_fact <- factor(c(1,2,3,6,5,4))
> num_fact
[1] 1 2 3 6 5 4
Levels: 1 2 3 4 5 6
> num_num <- as.numeric(levels(num_fact)[as.numeric(num_fact)])
> num_num
[1] 1 2 3 6 5 4
Try this:
retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)
replace <full path to your python script>
with the full path
For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts
:
tasks.register("bootRunDev") {
group = "application"
description = "Runs this project as a Spring Boot application with the dev profile"
doFirst {
tasks.bootRun.configure {
systemProperty("spring.profiles.active", "dev")
}
}
finalizedBy("bootRun")
}
Don't have long values as primary key. That will destroy your performance. See the mysql manual, section 13.6.13 'InnoDB Performance Tuning and Troubleshooting'.
Instead, have a surrogate int key as primary (with auto_increment), and your loong key as a secondary UNIQUE.
You can use it via LINQ
var selectedEditionIds = input.SelectedEditionIds.Split(",").ToArray()
.Where(i => !string.IsNullOrWhiteSpace(i)
&& int.TryParse(i,out int validNumber))
.Select(x=>int.Parse(x)).ToList();
I think you are saying that a container
vs container-fluid
is the difference between responsive and non-responsive to the grid. This is not true...what is saying is that the width is not fixed...its full width!
This is hard to explain so lets look at the examples
Example one
container-fluid
:
So you see how the container takes up the whole screen...that's a container-fluid
.
Now lets look at the other just a normal container
and watch the edges of the preview
Example two
container
Now do you see the white space in the example? That's because its a fixed width container
! It might make more sense to open both examples up in two different tabs and switch back and forth.
EDIT
Better yet here is an example with both containers at once! Now you can really tell the difference!
I hope this helped clarify a little bit!
I am late to this thread, but I too had a similar requirement. Since my script was constructing the request for curl dynamically, I wanted a similar structure of the command across GET, POST and PUT.
Here is what works for me
For PUT request:
curl --request PUT --url http://localhost:8080/put --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'
For POST request:
curl --request POST --url http://localhost:8080/post --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'
For GET request:
curl --request GET --url 'http://localhost:8080/get?foo=bar&foz=baz'
In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.
So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.
Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).
XAML :
<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False" ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="Button_Click_dgvs">Text</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
Code Behind :
private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row & row.IsSelected) yield return row;
}
}
void Button_Click_dgvs(object sender, RoutedEventArgs e)
{
for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
if (vis is DataGridRow)
{
// var row = (DataGrid)vis;
var rows = GetDataGridRowsForButtons(dgv_Students);
string id;
foreach (DataGridRow dr in rows)
{
id = (dr.Item as tbl_student).Identification_code;
MessageBox.Show(id);
break;
}
break;
}
}
After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.
Shorter explanation:
In C++, struct and class were just two sides of the same coin. The only real difference is that one was public by default and the other was private.
In .NET, there is a much greater difference between a struct and a class. The main thing is that struct provides value-type semantics, while class provides reference-type semantics. When you start thinking about the implications of this change, other changes start to make more sense as well, including the constructor behavior you describe.
If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:
.validation-summary-valid {
display: none;
}
This may also cause the @Html.ValidationSummary
to appear hidden, as the summary is dynamically rendered with the validation-summary-valid
class.
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name
when it was not submitted.
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class and on a button click's OnClickListener()
you wanna move from one Activity to another then --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move (It may contain anything like you are saying dialog box).
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
This exmple is related to button click you can use the code anywhere which is written inside button click's OnClickListener()
at any place where you want to switch between your activities.
Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +
"SET SCHEMA TEST";
String url = "jdbc:h2:mem;" +
"INIT=RUNSCRIPT FROM '~/create.sql'\\;" +
"RUNSCRIPT FROM '~/populate.sql'";
Please note the double backslash (\\
) is only required within Java. The backslash(es) before ;
within the INIT
is required.
move c:\Sourcefoldernam\*.* e:\destinationFolder
^ This did not work for me for some reason
But when I tried using quotation marks, it suddenly worked:
move "c:\Sourcefoldernam\*.*" "e:\destinationFolder"
I think its because my directory had spaces in one of the folders. So if it doesn't work for you, try with quotation marks!
If you can use C++11 you may want to use std::function
and using
keyword.
using FunctionFunc = std::function<void(int arg1, std::string arg2)>;
Here you go:
JS:
$('form').on('submit', function (e) {
e.preventDefault();
if (!$('#email').val())
$('#email').parent().append('<span class="error">Please enter your email address.</span>');
if(!$('#password').val())
$('#password').parent().append('<span class="error">Please enter your password.</span>');
});
CSS:
@charset "utf-8";
/* CSS Document */
/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */
@import url(http://weloveiconfonts.com/api/?family=fontawesome);
/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */
@import url(http://meyerweb.com/eric/tools/css/reset/reset.css);
/* ---------- FONTAWESOME ---------- */
[class*="fontawesome-"]:before {
font-family: 'FontAwesome', sans-serif;
}
/* ---------- GENERAL ---------- */
body {
background-color: #C0C0C0;
color: #000;
font-family: "Varela Round", Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
input {
border: none;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
-webkit-appearance: none;
}
/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 400px;
}
#login h2 {
background-color: #f95252;
-webkit-border-radius: 20px 20px 0 0;
-moz-border-radius: 20px 20px 0 0;
border-radius: 20px 20px 0 0;
color: #fff;
font-size: 28px;
padding: 20px 26px;
}
#login h2 span[class*="fontawesome-"] {
margin-right: 14px;
}
#login fieldset {
background-color: #fff;
-webkit-border-radius: 0 0 20px 20px;
-moz-border-radius: 0 0 20px 20px;
border-radius: 0 0 20px 20px;
padding: 20px 26px;
}
#login fieldset div {
color: #777;
margin-bottom: 14px;
}
#login fieldset p:last-child {
margin-bottom: 0;
}
#login fieldset input {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
#login fieldset .error {
display: block;
color: #FF1000;
font-size: 12px;
}
}
#login fieldset input[type="email"], #login fieldset input[type="password"] {
background-color: #eee;
color: #777;
padding: 4px 10px;
width: 328px;
}
#login fieldset input[type="submit"] {
background-color: #33cc77;
color: #fff;
display: block;
margin: 0 auto;
padding: 4px 0;
width: 100px;
}
#login fieldset input[type="submit"]:hover {
background-color: #28ad63;
}
HTML:
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form action="javascript:void(0);" method="POST">
<fieldset>
<div><label for="email">E-mail address</label></div>
<div><input type="email" id="email" /></div>
<div><label for="password">Password</label></div>
<div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->
<div><input type="submit" value="Sign In"></div>
</fieldset>
</form>
And the fiddle: jsfiddle
File.Create(string)
returns an instance of the FileStream
class. You can call the Stream.Close()
method on this object in order to close it and release resources that it's using:
var myFile = File.Create(myPath);
myFile.Close();
However, since FileStream
implements IDisposable
, you can take advantage of the using
statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
In Access 2007 this error occurs when importing an Excel file where there are two fields with the same column header.
That's because these things (I mean tooltip etc) are jQuery plug-ins. And yes, they assume some basic knowledge about jQuery. I would suggest you to look for at least a basic tutorial about jQuery.
You'll always have to define which elements should have a tooltip. And I don't understand why Bootstrap should provide the class, you define those classes or yourself. Maybe you were hoping that bootstrap did automatically some magic? This magic however, can cause a lot of problems as well (unwanted side effects).
This magic can be easily achieved to just write $(".myclass").tooltip()
, this line of code does exact what you want. The only thing you have to do is attach the myclass class to those elements that need to apply the tooltip thingy. (Just make sure you run that line of code after your DOM has been loaded. See below.)
$(document).ready(function() {
$(".myclass").tooltip();
});
EDIT: apparently you can't use the class tooltip (probably because it is somewhere internally used!).
I'm just wondering why bootstrap doesn't run the code you specified with some class I can include.
The thing you want produces almost the same code as you have to do now. The biggest reason however they did not do that, is because it causes a lot of trouble. One person wants to assign it to an element with an ID; others want to assign it to elements with a specified classname; and again others want to assign it to one specified element achieved through some selection process. Those 3 options cause extra complexity, while it is already provided by jQuery. I haven't seen many plugins do what you want (just because it is needless; it really doesn't save you code).
With Oracle's new SQLcl there is a cd command now and accompanying pwd. SQLcl can be downloaded here: http://www.oracle.com/technetwork/developer-tools/sqlcl/overview/index.html
Here's a quick example:
SQL>pwd
/Users/klrice/
NOT_SAFE>!ls *.sql
db_awr.sql emp.sql img.sql jeff.sql orclcode.sql test.sql
db_info.sql fn.sql iot.sql login.sql rmoug.sql
SQL>cd sql
SQL>!ls *.sql
003.sql demo_worksheet_name.sql poll_so_stats.sql
1.sql dual.sql print_updates.sql
SQL>
For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.
I use the Visio Network and Database stencils to model most other requirements.
I use the following:
lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
It'll find the last row in a specific column. If you want the last used row for any column then:
lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
If you have skype
installed, close it completely.
If you have sql server
installed, go to:
Control panel
-> Administrative Tools
-> Services
And stop SQL Server Reporting Services
Port 80 must be free now. Click on Wamp icon -> Restart All Services
Try this:
@Repository
@Qualifier("birthdayRepository")
public interface BirthdayRepository extends MongoRepository<BirthDay,String> {
public BirthDay findByFirstName(String firstName);
}
And when injecting the bean:
@Autowired
@Qualifier("birthdayRepository")
private BirthdayRepository repository;
If not, check your CoponentScan in your config.
TESTED Hope this helps someone.
My simple approach (Think tags as your original code)
<html>
<div ng-click="myfuncion">
<my-dir callfunction="myfunction">
</html>
<directive "my-dir">
callfunction:"=callfunction"
link : function(scope,element,attr) {
scope.callfunction = function() {
/// your code
}
}
</directive>
my quick answer with basic java arithmetic calculation is this:
First consider the following values:
1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
the code snippet is as follows:
int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60 ;
I hope to be helpful to you.
For a pure CSS solution, scroll after the 2nd <hr>
. The first one is the initial answer (given back in 2016)
The major flaw of the solutions above is they have a fixed height for the footer.
And that just doesn't cut it in the real world, where people use a zillion number of devices and have this bad habit of rotating them when you least expect it and **Poof!** there goes your page content behind the footer!
In the real world, you need a function that calculates the height of the footer and dynamically adjusts the page content's padding-bottom
to accommodate that height.
And you need to run this tiny function on page load
and resize
events as well as on footer's DOMSubtreeModified
(just in case your footer gets dynamically updated asynchronously or it contains animated elements that change size when interacted with).
Here's a proof of concept, using jQuery v3.0.0
and Bootstrap v4-alpha
, but there is no reason why it shouldn't work on lower versions of each.
jQuery(document).ready(function($) {_x000D_
$.fn.accomodateFooter = function() {_x000D_
var footerHeight = $('footer').outerHeight();_x000D_
$(this).css({_x000D_
'padding-bottom': footerHeight + 'px'_x000D_
});_x000D_
}_x000D_
$('footer').on('DOMSubtreeModified', function() {_x000D_
$('body').accomodateFooter();_x000D_
})_x000D_
$(window).on('resize', function() {_x000D_
$('body').accomodateFooter();_x000D_
})_x000D_
$('body').accomodateFooter();_x000D_
window.addMoreContentToFooter = function() {_x000D_
var f = $('footer');_x000D_
f.append($('<p />', {_x000D_
text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
}))_x000D_
.append($('<hr />'));_x000D_
}_x000D_
});
_x000D_
body {_x000D_
min-height: 100vh;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background-color: rgba(0, 0, 0, .65);_x000D_
color: white;_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
padding: 1.5rem;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">_x000D_
<link href="http://v4-alpha.getbootstrap.com/examples/starter-template/starter-template.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js"></script>_x000D_
<script src="http://v4-alpha.getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarsExampleDefault">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>_x000D_
<div class="dropdown-menu" aria-labelledby="dropdown01">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<input class="form-control mr-sm-2" type="text" placeholder="Search">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
<div class="container">_x000D_
<div class="starter-template">_x000D_
<h1>Feed that footer - not a game (yet!)</h1>_x000D_
<p class="lead">You will notice the body bottom padding is growing to accomodate the height of the footer as you feed it (so the page contents do not get covered by it).</p><button class="btn btn-warning" onclick="window.addMoreContentToFooter()">Feed that footer</button>_x000D_
<hr />_x000D_
<blockquote class="lead"><strong>Note:</strong> I used jQuery <code>v3.0.0</code> and Bootstrap <code>v4-alpha</code> but there is no reason why it shouldn't work with lower versions of each.</blockquote>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer>I am a footer with dynamic content._x000D_
<hr />_x000D_
</footer>
_x000D_
Initially, I have posted this solution here but I realized it might help more people if posted under this question.
Note: I have purposefully wrapped the $([selector]).accomodateFooter()
as a jQuery plugin, so it could be run on any DOM element, as in most layouts it is not the $('body')
's bottom-padding
that needs adjusting, but some page wrapper element with position:relative
(usually the immediate parent of the footer
).
Later edit (3+ years after initial answer):
At this point I no longer consider acceptable using JavaScript for positioning a dynamic content footer at the bottom of the page. It can be achieved with CSS alone, using flexbox, lightning fast, cross-browser.
Here it is:
// Left this in so you could inject content into the footer and test it:_x000D_
// (but it's no longer sizing the footer)_x000D_
_x000D_
function addMoreContentToFooter() {_x000D_
var f = $('footer');_x000D_
f.append($('<p />', {_x000D_
text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
}))_x000D_
.append($('<hr />'));_x000D_
}
_x000D_
.wrapper {_x000D_
min-height: 100vh;_x000D_
padding-top: 54px;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
.wrapper>* {_x000D_
flex-grow: 0;_x000D_
}_x000D_
_x000D_
.wrapper>main {_x000D_
flex-grow: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background-color: rgba(0, 0, 0, .65);_x000D_
color: white;_x000D_
width: 100%;_x000D_
padding: 1.5rem;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="wrapper">_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<div class="dropdown-divider"></div>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>_x000D_
<main>_x000D_
<div class="container">_x000D_
<div class="starter-template">_x000D_
<h1>Feed that footer - not a game (yet!)</h1>_x000D_
<p class="lead">Footer won't ever cover the body contents, as its not fixed. It's simply placed at the bottom when the page should be shorter using `min-height:100vh` on container and using flexbox to push it down.</p><button class="btn btn-warning" onclick="addMoreContentToFooter()">Feed that footer</button>_x000D_
<hr />_x000D_
<blockquote class="lead">_x000D_
<strong>Note:</strong> This example uses current latest versions of jQuery (<code>3.4.1.slim</code>) and Bootstrap (<code>4.4.1</code>) (unlike the one above)._x000D_
</blockquote>_x000D_
</div>_x000D_
</div>_x000D_
</main>_x000D_
<footer>I am a footer with dynamic content._x000D_
<hr />_x000D_
</footer>_x000D_
</div>
_x000D_
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
You can use AdminSite.site_header
to change that text. Here is the docs
While Arvin Amir's answer comes close to a full one-line solution you can drop in anywhere; he's got a slight bug in his select statement (missing the end of the line), and I wanted to handle the most common character references.
What I ended up doing was this:
SELECT replace(replace(replace(CAST(CAST(replace([columnNameHere], '&', '&') as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max)), '&', '&'), ' ', ' '), ' ', ' ')
FROM [tableName]
Without the character reference code it can be simplified to this:
SELECT CAST(CAST([columnNameHere] as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max))
FROM [tableName]
If you could use something other than 'awk' , then try this instead
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.
AppIcon
in Images.xcassets
.29pt
29pt*2
29pt*3
40pt*2
40pt*3
57pt
57pt*2
60pt*2
60pt*3
.Images.xcassets
will look like this:
ic_launcher.png
in folders [ProjectDirectory]/android/app/src/main/res/mipmap-*/
.
ic_launcher.png
in mipmap-hdpi
.ic_launcher.png
in mipmap-mdpi
.ic_launcher.png
in mipmap-xhdpi
.ic_launcher.png
in mipmap-xxhdpi
.ic_launcher.png
in mipmap-xxxhdpi
.The latest versions of react native also supports round icon. For this particular case, you have two choices:
A. Add round icons:
In each mipmap folder, add additionally to the ic_launcher.png
file also a round version called ic_launcher_round.png
with the same size.
B. Remove round icons:
Inside yourProjectFolder/android/app/src/main/AndroidManifest.xml
remove the line android:roundIcon="@mipmap/ic_launcher_round"
and save it.
Otherwhise the build throws an error.
Using a StreamReader to convert the MemoryStream to a String.
<Extension()> _
Public Function ReadAll(ByVal memStream As MemoryStream) As String
' Reset the stream otherwise you will just get an empty string.
' Remember the position so we can restore it later.
Dim pos = memStream.Position
memStream.Position = 0
Dim reader As New StreamReader(memStream)
Dim str = reader.ReadToEnd()
' Reset the position so that subsequent writes are correct.
memStream.Position = pos
Return str
End Function
Windows 7 has the arp command within it. arp -a should show you the static and dynamic type interfaces connected to your system.
Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
It will start from -9,223,372,036,854,775,808
Long.MIN_VALUE.
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
Snagged from Oracle OTN forums
Use alter table to add column, for example:
alter table tableName add(columnName NUMBER);
Then create a sequence:
CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;
and, the use update
to insert values in column like this
UPDATE tableName SET columnName = seq_test_id.NEXTVAL
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
I have tried this pure component:
const RawHTML = ({children, className = ""}) =>
<div className={className}
dangerouslySetInnerHTML={{ __html: children.replace(/\n/g, '<br />')}} />
Features
className
prop (easier to style it)\n
to <br />
(you often want to do that)<RawHTML>{myHTML}</RawHTML>
I have placed the component in a Gist at Github: RawHTML: ReactJS pure component to render HTML
Find and download old SDK. Older SDKs are found here.
I have copied the xcode.app directory as Xcode_4.6.3.app.
Now you can test and debug in both xcode versions. You have to run them from the corresponding folders or create shortcuts in your desktop. When building from command line give the parameter as iPhoneOS6.1
instead of iPhoneOS7.0
This worked great for me in Xcode5 and iOS.
Go to into Xcode5's SDK dir. Its usually located at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Add a symbolic link to the old SDK like this:
sudo ln -s /Applications/Xcode_4.6.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk iPhoneOS6.1.sdk
Or more accurately from anywhere in the command line,
sudo ln -s /Applications/Xcode_4.6.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk
This can be done by calling the reload() method of the window object in plain JavaScript
window.location.reload();
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
Object[][] twoDarray = new Object[map.size()][2];
Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();
for (int row = 0; row < twoDarray.length; row++) {
twoDarray[row][0] = keys[row];
twoDarray[row][1] = values[row];
}
// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
for (int j = 0; j < twoDarray[i].length; j++) {
System.out.println(twoDarray[i][j]);
}
}
For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRectMake(0, 50, 320, 200)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Make sure you have remembered to import UIKit
.
To get the content of a url:
try: # Try importing requests first.
import requests
except ImportError:
try: # Try importing Python3 urllib
import urllib.request
except AttributeError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using requests.
return requests.get(url).content # Returns requests.models.Response.
except NameError:
try: # Using Python3 urllib.
with urllib.request.urlopen(index_url) as response:
return response.read() # Returns http.client.HTTPResponse.
except AttributeError: # Using Python3 urllib.
return urllib.urlopen(url).read() # Returns an instance.
It's hard to write Python2 and Python3 and request
dependencies code for the responses because they urlopen()
functions and requests.get()
function return different types:
urllib.request.urlopen()
returns a http.client.HTTPResponse
urllib.urlopen(url)
returns an instance
request.get(url)
returns a requests.models.Response
I think the easiest way to match the characters like
\^$.?*|+()[
are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:
> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\
to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp
to see more info about this.
https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf
Use the os.EOL constant instead.
var os = require("os");
function processInput ( text )
{
fs.open('H://log.txt', 'a', 666, function( e, id ) {
fs.write( id, text + os.EOL, null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});
});
});
}
Since the question Something like `this.class` instead of `ClassName.class`? is marked as a duplicate for this one (which is arguable because that question is about the class rather than class name), I'm posting the answer here:
class MyService {
private static Class thisClass = MyService.class;
// or:
//private static Class thisClass = new Object() { }.getClass().getEnclosingClass();
...
static void startService(Context context) {
Intent i = new Intent(context, thisClass);
context.startService(i);
}
}
It is important to define thisClass
as private because:
1) it must not be inherited: derived classes must either define their own thisClass
or produce an error message
2) references from other classes should be done as ClassName.class
rather than ClassName.thisClass
.
With thisClass
defined, access to the class name becomes:
thisClass.getName()
There are excellent answers, but if you want to color your console logs you can use the pattern :
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
[%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
The full log4j2 file is:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="APP_LOG_ROOT">/opt/test/log</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
[%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
</Console>
<RollingFile name="XML_ROLLING_FILE_APPENDER"
fileName="${APP_LOG_ROOT}/appName.log"
filePattern="${APP_LOG_ROOT}/appName-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="%d{DEFAULT} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<SizeBasedTriggeringPolicy size="19500KB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Logger name="com.compName.projectName" level="debug">
<AppenderRef ref="XML_ROLLING_FILE_APPENDER"/>
</Logger>
</Loggers>
</Configuration>
Mad a similar error, easy to fix:
TypeError Traceback (most recent call last) <ipython-input-2-1eb12bfdc7db> in <module>
3 mylist = [10,20,30] ----> 4 arr = np.array[(10,20,30)] 5 d = {'a':10, 'b':20, 'c':30} TypeError: 'builtin_function_or_method' object is not subscriptable
but I should have written it as:
arr = np.array([10,20,30])
Very fixable, rookie/dumb mistake.
Public Sub UpdateMyFunctions()
Dim myRange As Range
Dim rng As Range
'Considering The Functions are in Range A1:B10
Set myRange = ActiveSheet.Range("A1:B10")
For Each rng In myRange
rng.Formula = rng.Formula
Next
End Sub
# one instance only (works unless your cmd has 'grep' in it)
ALREADY_RUNNING_EXIT_STATUS=0
bn=`basename $0`
proc=`ps -ef | grep -v grep | grep "$bn" | grep -v " $$ "`
[ $? -eq 0 ] && {
pid=`echo $proc | awk '{print $2}'`
echo "$bn already running with pid $pid"
exit $ALREADY_RUNNING_EXIT_STATUS
}
UPDATE .. better way using flock:
/usr/bin/flock -n /tmp/your-app.lock /path/your-app args
The above example using sort is close, but in the case of strings simply use SearchString:
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
If you set a session in php5, then try to read it on a php4 page, it might not look in the correct place! Make the pages the same php version or set the session_path.
Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".
I do not see it mentioned here, but a command that i use often and that helps me to have a bird's eye view on all groups, topics, partitions, offsets, lags, consumers, etc
kafka-consumer-groups.bat --bootstrap-server localhost:9092 --describe --all-groups
A sample would look like this:
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
Group Topic 2 7 7 0 <SOME-ID> XXXX <SOME-ID>
:
:
The most important column is the LAG
, where for a healthy platform, ideally it should be 0
(or nearer to 0 or a low number for high throughput) - at all times. So make sure you monitor it!!! ;-).
P.S:
An interesting article on how you can monitor the lag can be found here.
Adding import 'core-js/es7/array';
to my polyfill.ts
fixed the issue for me.
Using nvidia-smi
should tell you that:
bwood@mybox:~$ nvidia-smi
Mon Oct 29 12:30:02 2012
+------------------------------------------------------+
| NVIDIA-SMI 3.295.41 Driver Version: 295.41 |
|-------------------------------+----------------------+----------------------+
| Nb. Name | Bus Id Disp. | Volatile ECC SB / DB |
| Fan Temp Power Usage /Cap | Memory Usage | GPU Util. Compute M. |
|===============================+======================+======================|
| 0. GeForce GTX 580 | 0000:25:00.0 N/A | N/A N/A |
| 54% 70 C N/A N/A / N/A | 25% 383MB / 1535MB | N/A Default |
|-------------------------------+----------------------+----------------------|
| Compute processes: GPU Memory |
| GPU PID Process name Usage |
|=============================================================================|
| 0. Not Supported |
+-----------------------------------------------------------------------------+
I've had success with
<span class="someclass"></span>
Caveat : the class must already exist on the site.
Didn't see any answers correctly using DATE_ADD
or DATE_SUB
:
Subtract 1 day from NOW()
...WHERE DATE_FIELD >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Add 1 day from NOW()
...WHERE DATE_FIELD >= DATE_ADD(NOW(), INTERVAL 1 DAY)
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify transaction_status varchar(10) but you actually trying to store _transaction_status which contain 19 characters. that's why you faced this type of error in this code
I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:
Sub CopyPartOfFilteredRange()
Dim src As Worksheet
Dim tgt As Worksheet
Dim filterRange As Range
Dim copyRange As Range
Dim lastRow As Long
Set src = ThisWorkbook.Sheets("Sheet1")
Set tgt = ThisWorkbook.Sheets("Sheet2")
' turn off any autofilters that are already set
src.AutoFilterMode = False
' find the last row with data in column A
lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row
' the range that we are auto-filtering (all columns)
Set filterRange = src.Range("A1:C" & lastRow)
' the range we want to copy (only columns we want to copy)
' in this case we are copying country from column A
' we set the range to start in row 2 to prevent copying the header
Set copyRange = src.Range("A2:A" & lastRow)
' filter range based on column B
filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"
' copy the visible cells to our target range
' note that you can easily find the last populated row on this sheet
' if you don't want to over-write your previous results
copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")
End Sub
Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False
is not necessary.
After "AND" and after "OR" the QUERY has forgotten what it is all about.
I would also not know that it is about in any SQL / programming language.
if(SOMETHING equals "X" or SOMETHING equals "Y")
COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"
Mac users:
ng serve --host 192.168.1.x
Then you must be able to see your page on other devices through 192.168.1.x:4200
.
For an updated answer you can build a forEach
function in Python easily:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
You could also adapt this to map
, reduce
, filter
, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach
or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.
Since R2019b, there is a new command line option, -batch
. It replaces -r
, which is no longer recommended. It also unifies the syntax across platforms. See for example the documentation for Windows, for the other platforms the description is identical.
matlab -batch "statement to run"
This starts MATLAB without the desktop or splash screen, logs all output to stdout
and stderr
, exits automatically when the statement completes, and provides an exit code reporting success or error.
It is thus no longer necessary to use try
/catch
around the code to run, and it is no longer necessary to add an exit
statement.
b = a[a>threshold]
this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0
I got
$ python test.py
0:00:00.028000
0:00:02.461000
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
More portable to use ed; some systems don't support \n in sed
printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename
[self dismissModalViewControllerAnimated:NO];
has been deprecated.
Use [self dismissViewControllerAnimated:NO completion:nil];
instead.
You put them in the workspace/projects
folder. You should put them directly in the workspace
folder and then do an Import Existing Projects into workspace.
$(".bootgrid-table tr").eq(0).addClass("black");
$(".bootgrid-table tr").eq(1).addClass("black");
This works fine. Checked in chrome
browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
You need to use the CSS3 transform property rotate
- see here for which browsers support it and the prefix you need to use.
One example for webkit browsers is -webkit-transform: rotate(-90deg);
Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit-
CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>
s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.
There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)
Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.
Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.
Hope this helps!
Main and Background Queues
let main = DispatchQueue.main
let background = DispatchQueue.global()
let helper = DispatchQueue(label: "another_thread")
Working with async and sync threads!
background.async { //async tasks here }
background.sync { //sync tasks here }
Async threads will work along with the main thread.
Sync threads will block the main thread while executing.
if you have enum like this
public enum PcapLinkType {
DLT_NULL(0)
DLT_EN10MB(1)
DLT_EN3MB(2),
DLT_AX25(3),
DLT_UNKNOWN(-1);
private final int value;
PcapLinkType(int value) {
this.value= value;
}
}
then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
This works with Firefox Quantum 60+ and Chrome v72 (2019)
//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");
It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.
public void ExpoetToCSV(DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i].ToString().Trim());
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString().Trim();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString().Trim());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
Many times, we need to hide some parts of codes while writing a long code.
Example: - Just on clicking "Code show/hide", we can hide 3 lines of codes.
So here is the function that you need to define for partially hiding few part of codes and then call it whenever you want to hide some code:
from IPython.display import HTML
def hide_toggle(for_next=False):
this_cell = """$('div.cell.code_cell.rendered.selected')""" ; next_cell = this_cell + '.next()';
toggle_text = 'Code show/hide' # text shown on toggle link
target_cell = this_cell ; js_hide_current = ''
if for_next:
target_cell = next_cell; toggle_text += ' next cell';
js_hide_current = this_cell + '.find("div.input").hide();'
js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))
html = """<script>
function {f_name}() {{{cell_selector}.find('div.input').toggle(); }}
{js_hide_current}
</script>
<a href="javascript:{f_name}()">{toggle_text}</a>
""".format(f_name=js_f_name,cell_selector=target_cell,js_hide_current=js_hide_current, toggle_text=toggle_text )
return HTML(html)
Once we are ready with function definition, our next task is very easy. Just we need to call the function to hide/show the code.
print("Function for hiding the cell")
hide_toggle()
Your compiler just tried to compile the file named foo.cc
. Upon hitting line number line
, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar
. For an explanation of the difference between the versions of the include statement look here.
g++
has an option -I
. It lets you add include search paths to the command line. Imagine that your file bar
is in a folder named frobnicate
, relative to foo.cc
(assume you are compiling from the directory where foo.cc
is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I
that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar
in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar"
is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/
, B/
and C/
, it stopped at the first or leftmost hit.
This is true of both forms, include <>
and incude ""
.
#include <bar>
and #include "bar"
Usually, the #include <xxx>
makes it look into system folders first, the #include "xxx"
makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc
:
#include "list"
....
For this, your compiler will #include
the file list
in your project folder, because it currently compiles main.cc
and there is that file list
in the current folder.
But with main.cc
:
#include <list>
....
and then g++ main.cc
, your compiler will look into the system folders first, and because <list>
is a standard header, it will #include
the file named list
that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
<>
/""
-priorities and -I
According to the gcc-documentation, the priority for include <>
is, on a "normal Unix system", as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list"
example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I.
prioritizes the folder .
over the system includes and we get a compiler error.
Kotlin code:
Start the SecondActivity
:
startActivity(Intent(context, SecondActivity::class.java)
.putExtra(SecondActivity.PARAM_GAME_ID, gameId))
Get the Id in SecondActivity
:
class CaptureActivity : AppCompatActivity() {
companion object {
const val PARAM_GAME_ID = "PARAM_GAME_ID"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val gameId = intent.getStringExtra(PARAM_GAME_ID)
// TODO use gameId
}
}
where gameId
is String?
(can be null)
except for codecs.open()
, one can uses io.open()
to work with Python2 or Python3 to read / write unicode file
example
import io
text = u'á'
encoding = 'utf8'
with io.open('data.txt', 'w', encoding=encoding, newline='\n') as fout:
fout.write(text)
with io.open('data.txt', 'r', encoding=encoding, newline='\n') as fin:
text2 = fin.read()
assert text == text2
DELIMITER $$
DROP FUNCTION IF EXISTS `split_name`$$
CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
READS SQL DATA
BEGIN
DECLARE v_words INT UNSIGNED;
DECLARE v_name TEXT;
SET p_fullname=RTRIM(LTRIM(p_fullname));
SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));
IF v_words=1 THEN
IF p_part=1 THEN
SET v_name=p_fullname;
ELSEIF p_part=2 THEN
SET v_name=NULL;
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=2 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words>3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
SET v_name=REVERSE(p_fullname);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSE
SET v_name=NULL;
END IF;
RETURN v_name;
END;
SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name
You can use single line comments:
-- this is a comment
# this is also a comment
Or a multiline comment:
/*
multiline
comment
*/
Function can be used within a sql statement whereas procedure cannot be used within a sql statement.
Insert, Update and Create statements cannot be included in function but a procedure can have these statements.
Procedure supports transactions but functions do not support transactions.
Function has to return one and only one value (another can be returned by OUT variable) but procedure returns as many data sets and return values.
Execution plans of both functions and procedures are cached, so the performance is same in both the cases.
Make sure you have closed your MSAccess file before running the java program.
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
In real life you wish to simulate a signal with white noise. You should add to your signal random points that have Normal Gaussian distribution. If we speak about a device that have sensitivity given in unit/SQRT(Hz) then you need to devise standard deviation of your points from it. Here I give function "white_noise" that does this for you, an the rest of a code is demonstration and check if it does what it should.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
"""
parameters:
rhp - spectral noise density unit/SQRT(Hz)
sr - sample rate
n - no of points
mu - mean value, optional
returns:
n points of noise signal with spectral noise density of rho
"""
def white_noise(rho, sr, n, mu=0):
sigma = rho * np.sqrt(sr/2)
noise = np.random.normal(mu, sigma, n)
return noise
rho = 1
sr = 1000
n = 1000
period = n/sr
time = np.linspace(0, period, n)
signal_pure = 100*np.sin(2*np.pi*13*time)
noise = white_noise(rho, sr, n)
signal_with_noise = signal_pure + noise
f, psd = signal.periodogram(signal_with_noise, sr)
print("Mean spectral noise density = ",np.sqrt(np.mean(psd[50:])), "arb.u/SQRT(Hz)")
plt.plot(time, signal_with_noise)
plt.plot(time, signal_pure)
plt.xlabel("time (s)")
plt.ylabel("signal (arb.u.)")
plt.show()
plt.semilogy(f[1:], np.sqrt(psd[1:]))
plt.xlabel("frequency (Hz)")
plt.ylabel("psd (arb.u./SQRT(Hz))")
#plt.axvline(13, ls="dashed", color="g")
plt.axhline(rho, ls="dashed", color="r")
plt.show()
I found this shorter and much better:
if(varName !== (undefined || null)) { //do something }
All file modes in Python
r
for readingr+
opens for reading and writing (cannot truncate a file)w
for writing w+
for writing and reading (can truncate a file) rb
for reading a binary file. The file pointer is placed at the beginning of the file.rb+
reading or writing a binary filewb+
writing a binary filea+
opens for appendingab+
Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.x
open for exclusive creation, failing if the file already exists (Python 3)You can try SharpZipLib for that. Is is open source, platform independent pure c# code.
All of these answers appear to be incomplete and/or kludges. Looking at the RestTemplate interface, it sure looks like it is intended to have a ClientHttpRequestFactory
injected into it, and then that requestFactory will be used to create the request, including any customizations of headers, body, and request params.
You either need a universal ClientHttpRequestFactory
to inject into a single shared RestTemplate
or else you need to get a new template instance via new RestTemplate(myHttpRequestFactory)
.
Unfortunately, it looks somewhat non-trivial to create such a factory, even when you just want to set a single Authorization header, which is pretty frustrating considering what a common requirement that likely is, but at least it allows easy use if, for example, your Authorization header can be created from data contained in a Spring-Security Authorization
object, then you can create a factory that sets the outgoing AuthorizationHeader on every request by doing SecurityContextHolder.getContext().getAuthorization()
and then populating the header, with null checks as appropriate. Now all outbound rest calls made with that RestTemplate will have the correct Authorization header.
Without more emphasis placed on the HttpClientFactory mechanism, providing simple-to-overload base classes for common cases like adding a single header to requests, most of the nice convenience methods of RestTemplate
end up being a waste of time, since they can only rarely be used.
I'd like to see something simple like this made available
@Configuration
public class MyConfig {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(new AbstractHeaderRewritingHttpClientFactory() {
@Override
public HttpHeaders modifyHeaders(HttpHeaders headers) {
headers.addHeader("Authorization", computeAuthString());
return headers;
}
public String computeAuthString() {
// do something better than this, but you get the idea
return SecurityContextHolder.getContext().getAuthorization().getCredential();
}
});
}
}
At the moment, the interface of the available ClientHttpRequestFactory's are harder to interact with than that. Even better would be an abstract wrapper for existing factory implementations which makes them look like a simpler object like AbstractHeaderRewritingRequestFactory for the purposes of replacing just that one piece of functionality. Right now, they are very general purpose such that even writing those wrappers is a complex piece of research.
After trying @regeter's solution and seeing it didn't solve my problem when I was searching for a foreign/primary key to see all tables/columns where it exists, it didn't work. After reading how it failed for another who tried to use a unique identifier, I have made the modifications and here is the updated result: (works with both int, and guids... you will see how to easily extend)
CREATE PROC [dbo].[SearchAllTables_Like]
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('guid', 'int', 'char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
Stephen's answer is correct but here's my adaptation of his answer:
<div class="parent">
<p> parent 1 </p>
<div class="child">
Text Block 1
</div>
</div>
<div class="parent">
<p> parent 2 </p>
<div class="child">
Text Block 2
</div>
</div>
.parent { width: 100px; min-height: 100px; color: red; }
.child { width: 50px; min-height: 20px; color: blue; display: none; }
.parent:hover .child, .parent.hover .child { display: block; }
//this is only necessary for IE and should be in a conditional comment
jQuery('.parent').hover(function () {
jQuery(this).addClass('hover');
}, function () {
jQuery(this).removeClass('hover');
});
You can see this example working over at jsFiddle.
You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
Add a new EC2 security group inbound rule:
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
This is the best way to enable/ disable swipe to pop view controller in iOS 10, Swift 3 :
For First Screen [ Where you want to Disable Swipe gesture ] :
class SignUpViewController : UIViewController,UIGestureRecognizerDelegate {
//MARK: - View initializers
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
swipeToPop()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func swipeToPop() {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
self.navigationController?.interactivePopGestureRecognizer?.delegate = self;
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
return false
}
return true
} }
For middle screen [ Where you want to Enable Swipe gesture ] :
class FriendListViewController : UIViewController {
//MARK: - View initializers
override func viewDidLoad() {
super.viewDidLoad()
swipeToPop()
}
func swipeToPop() {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil;
} }
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
You're the victim of the classic deadlock. task.Wait()
or task.Result
is a blocking call in UI thread which causes the deadlock.
Don't block in the UI thread. Never do it. Just await it.
private async void Button_Click(object sender, RoutedEventArgs
{
var task = GetResponseAsync<MyObject>("my url");
var items = await task;
}
Btw, why are you catching the WebException
and throwing it back? It would be better if you simply don't catch it. Both are same.
Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse
method. StreamReader.ReadToEnd
is a blocking call --you should be using StreamReader.ReadToEndAsync
.
Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.
Your method should look something like the following when you've addressed all the above concerns.
public static async Task<List<T>> GetResponseAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = await strReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<List<T>>(text);
}
For me the padding solution wasn't good, as I was using border on the button, and would've been hard to put modify the markup to create an overlay for the touch area.
So what I did, is I just used the :before pseudo tag, and created an overlay, which was perfect in my case, as the click event propagated the same way.
button.my-button:before {
content: '';
position: absolute;
width: 26px;
height: 26px;
top: -6px;
left: -5px;
}
Better way till now:
If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.
Better way is to use two different classes for inner divs with width, margin and float.
Best way till now:
Use flexbox.
On MacOS Sierra use:
/usr/bin/time -l commandToMeasure
You can use grep
to take what you want maybe.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
Anurags answer is basically correct.
But to support Object.keys(obj)
in older browsers as well you can use the code below that is copied from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
. It adds the Object.keys(obj)
method if it's not available from the browser.
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
Wrap your two+ function calls in another function/method. Here are a couple variants of that idea:
1) Separate method
var Test = React.createClass({
onClick: function(event){
func1();
func2();
},
render: function(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});
or with ES6 classes:
class Test extends React.Component {
onClick(event) {
func1();
func2();
}
render() {
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
}
2) Inline
<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>
or ES6 equivalent:
<a href="#" onClick={() => { func1(); func2();}}>Test Link</a>
Just additional notes. Using class ES6, When we create static methods..the Javacsript engine set the descriptor attribute a lil bit different from the old-school "static" method
function Car() {
}
Car.brand = function() {
console.log('Honda');
}
console.log(
Object.getOwnPropertyDescriptors(Car)
);
it sets internal attribute (descriptor property) for brand() to
..
brand: [object Object] {
configurable: true,
enumerable: true,
value: ..
writable: true
}
..
compared to
class Car2 {
static brand() {
console.log('Honda');
}
}
console.log(
Object.getOwnPropertyDescriptors(Car2)
);
that sets internal attribute for brand() to
..
brand: [object Object] {
configurable: true,
enumerable: false,
value:..
writable: true
}
..
see that enumerable is set to false for static method in ES6.
it means you cant use the for-in loop to check the object
for (let prop in Car) {
console.log(prop); // brand
}
for (let prop in Car2) {
console.log(prop); // nothing here
}
static method in ES6 is treated like other's class private property (name, length, constructor) except that static method is still writable thus the descriptor writable is set to true { writable: true }
. it also means that we can override it
Car2.brand = function() {
console.log('Toyota');
};
console.log(
Car2.brand() // is now changed to toyota
);
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
1) To access DOM in component.
import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
constructor(el: ElementRef,public zone:NgZone) {
this.el = el.nativeElement;
this.dom = new BrowserDomAdapter();
}
ngOnInit() {
this.dom.setValue(this.el,"Adding some content from ngOnInit");
}
You can include jQuery in following way. 2) Include you jquery file in index.html before angular2 loads
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- jquery file -->
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
You can use Jquery in following way, Here i am using JQuery Ui date picker.
import { Directive, ElementRef} from '@angular/core';
declare var $:any;
@Directive({
selector: '[uiDatePicker]',
})
export class UiDatePickerDirective {
private el: HTMLElement;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
$(this.el).datepicker({
onSelect: function(dateText:string) {
//do something on select
}
});
}
}
This work for me.
This thing worked for me. No any external liabraries used
define ("MAX_SIZE","3000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["image-1"]["name"];
$uploadedfile = $_FILES['image-1']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['image-1']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "Unknown Extension..!";
}
else
{
$size=filesize($_FILES['image-1']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo "File Size Excedeed..!!";
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];
$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
See: Multiple-line-syntax
It also support variables in multiline string, for example:
String name="zzg";
String lines = ""/**~!{
SELECT *
FROM user
WHERE name="$name"
}*/;
System.out.println(lines);
Output:
SELECT *
FROM user
WHERE name="zzg"
You need to use -I
with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach
:
INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)
Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...
CoffeeScript
$(document).ready ->
material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
$(window).load ->
renderer.render scene, camera
JavaScript
$(document).ready(function() {
material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
$(window).load(function() {
renderer.render(scene, camera);
});
});
Thanks...
Don't waste your time, you can use Resource Bundle plugin in Eclipse
Create simple drop-down menu using HTML and CSS
CSS:
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
and HTML:
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
playing with globals() makes it possible:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
one result:
'alphabet'
'random'
('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')
I used random because you don't explain which names of "variables" to give, and which values to create. Because i don't think it's possible to create a name without making it binded to an object.
This one will gets the job done nicely:
public static String removeZero(double number) {
DecimalFormat format = new DecimalFormat("#.###########");
return format.format(number);
}
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).
You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form
the control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:
The control's Parent property value might not be the same as the Form returned by FindForm method. For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control's Parent is the GroupBox and the GroupBox control's Parent is the Form.
Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000
) is not included in \s
for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000
with \u0020
), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000]
.
If you're using Perl or PCRE, you have the option of using the \h
shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.
However, this \h
shorthand has not been implemented for .NET and C#, as best I've been able to tell.
The root cause of this problem has to do with user authentication versions. For each database user, multiple password verifiers are kept in the database. Typically when you upgrade your database, a new password verifier will be added to the list, a stronger one. The following query shows the password verifier versions that are available for each user. For example:
SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';
PASSWORD_VERSIONS
-----------------
11G 12C
When upgrading to a newer driver you can use a newer version of the verifier because the driver and server negotiate the strongest possible verifier to to be used. This newer version of the verifier will be more secure and will involve generating larger random numbers or using more complex hashing functions which can explain why you see issues while establishing JDBC connections. As mentioned by other responses using /dev/urandom
normally resolves these issues. You can also decide to downgrade your password verifier and make the newer driver use the same older password verifier that your previous driver was using. For example if you want to use the 10G password verifier (for testing purposes only), first you need to make sure it's available for your user.
Set SQLNET.ALLOWED_LOGON_VERSION_SERVER=8
in sqlnet.ora on the server. Then:
SQL> alter user scott identified by "tiger";
User altered.
SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';
PASSWORD_VERSIONS
-----------------
10G 11G 12C
Then you can force the JDBC thin driver to use the 10G verifier by setting this JDBC property oracle.jdbc.thinLogonCapability="o3"
. If you run into the error "ORA-28040: No matching authentication protocol"
then that means your server is not allowing the 10G verifier to be used. If that's the case then you need to check your configuration again.
If you are on iOS 13.5 and Xcode 11.5, removing the device and adding it again fixed it for me.
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
If someone is strugling with axios to make this work this helped me:
import axios from 'axios';
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
Source: https://cbuelter.wordpress.com/2017/04/10/django-csrf-with-axios/
You can try this.. My own version of it..
funcc() {
while true ; do
for i in \| \/ \- \\ \| \/ \- \\; do
echo -n -e "\r$1 $i "
sleep 0.5
done
#echo -e "\r "
[ -f /tmp/print-stat ] && break 2
done
}
funcc "Checking Kubectl" & &>/dev/null
sleep 5
touch /tmp/print-stat
echo -e "\rPrint Success "
It means that one of the dependent dlls is compiled with a different run-time library.
Project -> Properties -> C/C++ -> Code Generation -> Runtime Library
Go over all the libraries and see that they are compiled in the same way.
More about this error in this link:
warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
private void addContact(String name, String number){
Uri addContactsUri = ContactsContract.Data.CONTENT_URI;
long rowContactId = getRawContactId();
String displayName = name;
insertContactDisplayName(addContactsUri, rowContactId, displayName);
String phoneNumber = number;
String phoneTypeStr = "Mobile";//work,home etc
insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);
}
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
// Put contact display name value.
contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);
activity.getContentResolver().insert(addContactsUri, contentValues);
}
private long getRawContactId()
{
// Inser an empty contact.
ContentValues contentValues = new ContentValues();
Uri rawContactUri = activity.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
// Get the newly created contact raw id.
long ret = ContentUris.parseId(rawContactUri);
return ret;
}
private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr) {
// Create a ContentValues object.
ContentValues contentValues = new ContentValues();
// Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// Put phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
// Calculate phone type by user selection.
int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
if ("home".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
} else if ("mobile".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
} else if ("work".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
// Put phone type value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);
// Insert new contact data into phone contact list.
activity.getContentResolver().insert(addContactsUri, contentValues);
}
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
You will get useful information from here.
SELECT ticker
INTO quotedb
FROM tickerdb;
I often need to execute an action on each pair in two collections. The Zip method is not useful in this case.
This extension method ForPair can be used:
public static void ForPair<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second,
Action<TFirst, TSecond> action)
{
using (var enumFirst = first.GetEnumerator())
using (var enumSecond = second.GetEnumerator())
{
while (enumFirst.MoveNext() && enumSecond.MoveNext())
{
action(enumFirst.Current, enumSecond.Current);
}
}
}
So for example, you could write:
var people = new List<Person> { person1, person2 };
var wages = new List<decimal> { 10, 20 };
people.ForPair(wages, (p, w) => p.Wage = w);
Note however that this method cannot be used to modify the collection itself. This for example will not work:
List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };
listA.ForPair(listA, (c1, c2) => c1 = c2); // Nothing will happen!
So in this case, the example in your own question is probably the best way.
Bootstrap V3:
Official Doc Link 1
Official Doc Link 2
<div class="form-group has-success">
<label class="control-label" for="inputSuccess">Input with success</label>
<input type="text" class="form-control" id="inputSuccess" />
<span class="help-block">Woohoo!</span>
</div>
<div class="form-group has-warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<input type="text" class="form-control" id="inputWarning">
<span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
This also works:
SELECT
pieces.*
FROM
pieces inner join (select min(price) as minprice from pieces) mn
on pieces.price = mn.minprice
(since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)
This compliant example uses the #pragma pack compiler extension from Microsoft Visual Studio to ensure the structure members are packed as tightly as possible:
#include <string.h>
#pragma pack(push, 1)
struct s {
char c;
int i;
char buffer[13];
};
#pragma pack(pop)
void compare(const struct s *left, const struct s *right) {
if (0 == memcmp(left, right, sizeof(struct s))) {
/* ... */
}
}
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
The double underscore (__) syntax is used all over the place when working with querysets.
The most efficient selector you can use is an attribute selector.
input[name="btnPage"]:hover {/*your css here*/}
Here's a live demo: http://tinkerbin.com/3G6B93Cb
I believe you are trying to compare two strings representing values, the function you are looking for is:
int atoi(const char *nptr);
or
long int strtol(const char *nptr, char **endptr, int base);
these functions will allow you to convert a string to an int/long int:
int val = strtol("555", NULL, 10);
and compare it to another value.
int main (int argc, char *argv[])
{
long int val = 0;
if (argc < 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
exit(EXIT_FAILURE);
}
val = strtol(argv[1], NULL, 10);
printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");
return 0;
}
For most it is a breeze, however like you I had a difficult time installing jq
The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/
However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system
What worked for me was removing all previous installs then pip install jq
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
I happened to face the same issue, all of a sudden all my imports were missing. I tried deleting all the contents in my .m2 folder. And trying to re-import everything , but still nothing worked. Finally what I did was opened the website for which the IDE was complaining that it couldn't download in my browser. And saw the certificate it was using, and saw in my
$ keytool -v -list PATH_TO_JAVA_KEYSTORE
Path to my keystore was /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
that particular certificate was not there.
So all you have to do is put the certificate into the JAVA JVM keystore again. It can be done using the below command.
$ keytool -import -alias ANY_NAME_YOU_WANT_TO_GIVE -file PATH_TO_YOUR_CERTIFICATE -keystore PATH_OF_JAVA_KEYSTORE
If it asks for password, try the default password 'changeit' If you get permission error when running the above command. In windows open it in administration mode. In mac and unix use sudo.
After you have successfully added the key, You can view it using :
$ keytool -v -list /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
You can view just the SHA-1 using teh command
$ keytool -list /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works.
The find
command can output many parameters.
For example, add the following to the --printf
clause:
%a for attributes in the octal format
%n for the file name including a complete path
Example:
find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file
Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.
In npm 6.x you can use
npm i --package-lock-only
According to https://docs.npmjs.com/cli/install.html
The --package-lock-only argument will only update the package-lock.json, instead of checking node_modules and downloading dependencies.
To complete the answers, here are real-world examples of removing events when you are visiting websites and don't have control over the HTML and JavaScript code generated.
Some annoying websites are preventing you to copy-paste usernames on login forms, which could easily be bypassed if the onpaste
event was added with the onpaste="return false"
HTML attribute.
In this case we just need to right click on the input field, select "Inspect element" in a browser like Firefox and remove the HTML attribute.
However, if the event was added through JavaScript like this:
document.getElementById("lyca_login_mobile_no").onpaste = function(){return false};
We will have to remove the event through JavaScript also:
document.getElementById("lyca_login_mobile_no").onpaste = null;
In my example, I used the ID "lyca_login_mobile_no" since it was the text input ID used by the website I was visiting.
Another way to remove the event (which will also remove all the events) is to remove the node and create a new one, like we have to do if addEventListener
was used to add events using an anonymous function that we cannot remove with removeEventListener
.
This can also be done through the browser console by inspecting an element, copying the HTML code, removing the HTML code and then pasting the HTML code at the same place.
It can also be done faster and automated through JavaScript:
var oldNode = document.getElementById("lyca_login_mobile_no");
var newNode = oldNode.cloneNode(true);
oldNode.parentNode.insertBefore(newNode, oldNode);
oldNode.parentNode.removeChild(oldNode);
Update: if the web app is made using a JavaScript framework like Angular, it looks the previous solutions are not working or breaking the app. Another workaround to allow pasting would be to set the value through JavaScript:
document.getElementById("lyca_login_mobile_no").value = "username";
At the moment, I don't know if there is a way to remove all form validation and restriction events without breaking an app written entirely in JavaScript like Angular.
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});
Works on almost all browsers.
You can try giving padding-bottom
as a percentage.
<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>
The outer div is making a square and inner div contains the content. This solution worked for me many times.
Here's a jsfiddle
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
All of the following assume that your cursor is on the first line:
Using normal mappings:
3Shift+J
Using Ex commands:
:,+2j
Which is an abbreviation of
:.,.+2 join
Which can also be entered by the following shortcut:
3:j
An even shorter Ex command:
:j3
Another way to do this is with union:
INSERT INTO Data ( Col1 )
select 'hello'
union
select 'world'
As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()
) which will search the class files in defined places:
require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php
$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);
function __autoload($classname) {
if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
} else {
include_once($classname . '.php'); // looking for the class in include_path
}
}
An example of an associated full GC also shows the collectors used for the old and permanent generations:
3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)]
[ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K)
[PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]
Finally, breaking down one line of your example log output:
8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
Just wrap the button label in an extra span and add class="align-middle"
to both (the icon and the label). This will center your icon with text vertical.
<button id="edit-listing-form-house_Continue"
class="btn btn-large btn-primary"
style=""
value=""
name="Continue"
type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>
$('#form').append('<input type="text" value="'+yourValue+'" />');
This worked for me. If field with name fieldA is clicked or any key entered it updates field with id fieldB.
jQuery("input[name='fieldA']").on("input", function() {
jQuery('#fieldB').val(jQuery(this).val());
});
You want to use %p
to print a pointer. From the spec:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
And don't forget the cast, e.g.
printf("%p\n",(void*)&a);
You also need to be sure that returned bean is not empty (and can be serialized by Jackson). In my particular case I tried to return an instance of an object without getters and setters and without any jackson annotation and with fields equals to null. I got following message:
com.fasterxml.jackson.databind.JsonMappingException:
No serializer found for class com.foo.bar.Baz and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
RewriteEngine on
RewriteBase /basic_test/
RewriteRule ^index.php$ test.php
After reading all this and trying to fix it, I got a simple solution on ubuntu forum (https://help.ubuntu.com/community/ApacheMySQLPHP). The problem lies with libapache2-mod-php5 module. Thats why the browser downloads the index.php file rather than showing the web page. Do the following. If sudo a2enmod php5 returns module does not exist then the problem is with libapache2-mod-php5. Purge remove the module with command sudo apt-get --purge remove libapache2-mod-php5 Then install it again sudo apt-get install libapache2-mod-php5
Ref this
SELECT * FROM product WHERE name REGEXP '[0-9]'
If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.
You should not be repeating the string
part when sending parameters.
int wordLength = wordLengthFunction(word); //you do not put string word here.
If you are sure that the required substring is present in the string, then this will replace the first occurence of "abc"
to "hij"
test.replace( test.find("abc"), 3, "hij");
It will crash if you dont have "abc" in test, so use it with care.
No you don't have to put credentials, You have to put headers on client side eg:
$http({
url: 'url of service',
method: "POST",
data: {test : name },
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
And and on server side you have to put headers to this is example for nodejs:
/**
* On all requests add headers
*/
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
kw=(EditText)findViewById(R.id.kw);
btn=(Button)findViewById(R.id.btn);
cost=(TextView )findViewById(R.id.cost);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { cst = Double.valueOf(kw.getText().toString());
cst = cst*0.551;
cost.setText(cst.toString());
}
});
Here is pro example of using multi proptypes and single proptype.
import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';
class MyComponent extends Component {
/**
* Render
*/
render() {
const { title, data } = this.props;
return (
<>
{title}
<br />
{data}
</>
);
}
}
/**
* Define component props
*/
MyComponent.propTypes = {
data: oneOfType([array, string, shape({})]),
title: string,
};
export default MyComponent;
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string newItem = ((DataRowView) e.AddedItems[0]).Row.ItemArray[0].ToString();
}
With Vue.js:
<textarea name="story" :placeholder="'Enter story\n next line\n more'"></textarea>
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
Reference: http://developer.android.com/reference/android/view/View.html
Yes, there is better. Check the stat
or the fstat
function
Here is a callback object I wrote where you can either set a single callback to fire once all complete or let each have their own callback and fire them all once all complete:
NOTICE
Since jQuery 1.5+ you can use the deferred method as described in another answer:
$.when($.ajax(), [...]).then(function(results){},[...]);
for jQuery < 1.5 the following will work or if you need to have your ajax calls fired at unknown times as shown here with two buttons: fired after both buttons are clicked
[usage]
for single callback once complete: Working Example
// initialize here
var requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function(){
alert( "I'm the callback");
}
});
//usage in request
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}
});
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}
});
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}
});
each having their own callback when all complete: Working Example
//initialize
var requestCallback = new MyRequestsCompleted({
numRequest: 3
});
//usage in request
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the first callback');
});
}
});
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the second callback');
});
}
});
$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the third callback');
});
}
});
[The Code]
var MyRequestsCompleted = (function() {
var numRequestToComplete, requestsCompleted, callBacks, singleCallBack;
return function(options) {
if (!options) options = {};
numRequestToComplete = options.numRequest || 0;
requestsCompleted = options.requestsCompleted || 0;
callBacks = [];
var fireCallbacks = function() {
alert("we're all complete");
for (var i = 0; i < callBacks.length; i++) callBacks[i]();
};
if (options.singleCallback) callBacks.push(options.singleCallback);
this.addCallbackToQueue = function(isComplete, callback) {
if (isComplete) requestsCompleted++;
if (callback) callBacks.push(callback);
if (requestsCompleted == numRequestToComplete) fireCallbacks();
};
this.requestComplete = function(isComplete) {
if (isComplete) requestsCompleted++;
if (requestsCompleted == numRequestToComplete) fireCallbacks();
};
this.setCallback = function(callback) {
callBacks.push(callBack);
};
};
})();
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)
Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.
Import the lib
fluttertoast: 3.1.3
Use like below
Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:
public async Task<object> MethodName()
{
return await Task.FromResult<object>(null);
}
Here is an example with no return value:
public async Task MethodName()
{
await Task.CompletedTask;
}
Read these:
TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx
Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx
I faced this problem too. Re-ran the Visual Studio 2017 Installer, go to 'Individual Components' and select Windows 8.1 SDK
. Go back to to the project > Right click and Re-target to match the SDK required as shown below:
In the past I have used the excellently named MetricsReloaded plugin to get this information.
You can install it from the JetBrains repository.
Once installed, access via: Analyze -> Calculate Metrics...
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
Clone()
is used to copy only structure of data/array it doesn't copy the actual data.
CopyTo()
copies the structure as well as actual data.
See the query below (assumed @dt1 >= @dt2);
Declare @dt1 datetime = '2013-7-3'
Declare @dt2 datetime = '2013-5-2'
select abs(DATEDIFF(DD, @dt2, @dt1)) Days,
case when @dt1 >= @dt2
then case when DAY(@dt2)<=DAY(@dt1)
then Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)) + CONVERT(varchar, ' Month(s) ') + Convert(varchar, DAY(@dt1)-DAY(@dt2)) + CONVERT(varchar, 'Day(s).')
else Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)-1) + CONVERT(varchar, ' Month(s) ') + convert(varchar, abs(DATEDIFF(DD, @dt1, DateAdd(Month, -1, @dt1))) - (DAY(@dt2)-DAY(@dt1))) + CONVERT(varchar, 'Day(s).')
end
else 'See asumption: @dt1 must be >= @dt2'
end In_Months_Days
Returns:
Days | In_Months_Days
62 | 2 Month(s) 1Day(s).
ah homework...
So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.
If you really need to do that though... Assuming that ITEM is unique in stock_bal...
SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY
Show as decimal Select ifnull(format(100.00, 1, 'en_US'), 0) 100.0
Show as Percentage Select concat(ifnull(format(100.00, 0, 'en_US'), 0), '%') 100%
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class