You must link an event in your onClick. Additionally, the click function must receive the event. See the example
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)}
>
</div>
)
}
element.InnerHtml= allmycontent
: will re-write everything inside the element. You must use a variable let allmycontent="this is what I want to print inside this element"
to store the whole content you want inside this element. If not each time you will call this function, the content of your element will be erased and replace with the last call you made of it.
document.write()
: can be use several times, each time the content will be printed where the call is made on the page.
But be aware: document.write() method is only useful for inserting content at page creation . So use it for not repeating when having a lot of data to write like a catalogue of products or images.
Here a simple example: all your li for your aside menu are stored in an array "tab", you can create a js script with the script tag directly into the html page and then use the write method in an iterative function where you want to insert those li on the page.
<script type="text/javascript">
document.write("<ul>");
for (var i=0; i<=tab.length; i++){
document.write(tab[i]);
}document.write("</ul>");
</script>`
This works because Js is interpreted in a linear way during the loading. So make sure your script is at the right place in your html page.You can also use an external Js file, but then again you must declare it at the place where you want it to be interpreted.
For this reason, document.write cannot be called for writing something on your page as a result of a "user interaction" (like click or hover), because then the DOM has been created and write method will, like said above, write a new page (purge the actual execution stack and start a new stack and a new DOM tree). In this case use:
element.innerHTML=("Myfullcontent");
To learn more about document's methods: open your console: document;
then open: __proto__: HTMLDocumentPrototype
You'll see the function property "write" in the document object.
You can also use document.writeln which add a new line at each statement.
To learn more about a function/method, just write its name into the console with no parenthesis: document.write;
The console will return a description instead of calling it.
The following query should give the exact stuff you are looking out for.
select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Here is the link from MSDN for what all you can do with datediff function . https://msdn.microsoft.com/en-us/library/ms189794.aspx
No, but you have a couple of options:
The easiest is to upload all the files you have into that directory you're in (i.e. the cPanel user home directory), and put the contents of public into public_html. That way your directory structure will be something like this (slightly messy but it works):
/
.composer/
.cpanel/
...
app/ <- your laravel app directory
etc/
bootstrap/ <- your laravel bootstrap directory
mail/
public_html/ <- your laravel public directory
vendor/
artisan <- your project's root files
You may also need to edit bootstrap/paths.php
to point at the correct public directory.
The other solution, if you don't like having all these files in that 'root' directory would be to put them in their own directory (maybe 'laravel') that's still in the root directory and then edit the paths to work correctly. You'll still need to put the contents of public
in public_html
, though, and this time edit your public_html/index.php
to correctly bootstrap the application. Your folder structure will be a lot tidier this way (though there could be some headaches with paths due to messing with the framework's designed structure more):
/
.composer/
.cpanel/
...
etc/
laravel/ <- a directory containing all your project files except public
app/
bootstrap/
vendor/
artisan
mail/
public_html/ <- your laravel public directory
Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.
In my case, i have forgot to decorate with @Bean which causing this issue.
In HTML5, the
<hr>
tag defines a thematic break. In HTML 4.01, the<hr>
tag represents a horizontal rule.
http://www.w3schools.com/tags/tag_hr.asp
So after definition, I would prefer <hr>
https://bugs.eclipse.org/bugs/show_bug.cgi?id=102239 states that there is no substitution mechanics implemented in Eclipse's launcher, at least no up to release Juno.
Thus it is (almost) impossible to append or prepend another library folder to java.library.path when launching Eclipse without prior knowledge of the default setting.
I wrote almost, cause it should be possible to let Eclipse startup, dump the content of java.library.path and stop Eclipse in one command. The dump would the be parsed and then taken as the input for launching Eclipse, i.e.
#!/bin/bash
# get default value of java.library.path (somehow)
default_lib_path=$( start_dump_stop_eclipse_somehow )
# now launch Eclipse
eclipse --launcher.appendVmargs \
-vmargs \
-Djava.library.path="/my/native/lib/folder:${default_lib_path}"
A newer version example is here.
Below is a copy of the original code:
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.entity.mime;
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
/**
* @Route("/category/{id}", name="_category")
* @Route("/category/{id}/{active}", name="_be_activatecategory")
* @Template()
*/
public function categoryAction($id, $active = null)
{ .. }
May works.
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
You can't just add a border to the span because it will break the layout because of the way width is calculate: width = border + padding + width. Since the container is 940px and the span is 940px, adding 2px border (so 4px altogether) will make it look off centered. The work around is to change the width to include the 4px border (original - 4px) or have another div inside that creates the 2px border.
In database, Cardinality number of rows in the table.
image source
I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):
/**
* (Date: 30.01.2013)
*
* case 1: - "An error occured while creating the share (publishing to wall)"
* - "An unknown error has occurred."
* case 2: "An unexpected error has occurred. Please retry your request later."
* case 3: App must be on whitelist
* case 4: Application request limit reached
* case 5: Unauthorized source IP address
* case 200: Requires extended permissions
* case 240: Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
* case 1500: The url you supplied is invalid
* case 200:
* case 210: - Subject must be a page
* - User not visible
*/
/**
* Error Code 100 several issus:
* - "Specifying multiple ids with a post method is not supported" (http status 400)
* - "Error finding the requested story" but it is available via GET
* - "Invalid post_id"
* - "Code was invalid or expired. Session is invalid."
*
* Error Code 2:
* - Service temporarily unavailable
*/
Use short circuit evaluation:
s = a or '' + b or ''
Since + is not a very good operation on strings, better use format strings:
s = "%s%s" % (a or '', b or '')
The problem is caused because the code you are running was created in an older API level, And your present SDK Manager doesn't support running them. So do try the following; 1.Install the SDK Manager that support API level 23. Go to >SDK Manager, >Android SDK , then select API 23 and install. 2.second alternative is to update your build.grade app module to change compileSdkVersion,compile,and other numbers to your currently supported API level.
Note:please ensure to check the API and Revision numbers and change them exactly. otherwise Your project won't synchronize
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
Handler answer in Kotlin :
1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
2 - Then call it anywhere you needed it :
delayFunction({ myDelayedFunction() }, 300)
In the spirit of arrow sexiness, you could create a micro clamp/constrain/gate/&c. function using rest parameters
var clamp = (...v) => v.sort((a,b) => a-b)[1];
Then just pass in three values
clamp(100,-3,someVar);
That is, again, if by sexy, you mean 'short'
Using replace()
with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace()
will only replace the first instance.
For example:
var str = "foo gar gaz";
// returns: "foo bar gaz"
str.replace('g', 'b');
// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');
In the latter example, the trailing /gi
indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.
To remove characters, use an empty string as the replacement:
var str = "foo bar baz";
// returns: "foo r z"
str.replace(/ba/gi, '');
I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.
set codedirectory=C:\Users\code
for /r %codedirectory% %%i in (*.c) do
( some GCC commands )
You should not expose this info. in public, specially api keys. It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
Yes, simply set it to another value:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text
key of the array. The $_POST
is superglobal associative array and you can change the values like a normal PHP array.
Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST
array is cleared. A new form submission will generate a new $_POST
array.
If you want to persist the value across form submissions, you will need to put it in the form as an input
tag's value
attribute or retrieve it from a data store.
find your target element "d" however you wish and then:
d.className += ' additionalClass'; //note the space
you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..
Components
@Component
meta-data annotation.@View
decorator or templateurl template are mandatory in the component.Directive
@Directive
meta-data annotation.Sources:
http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html
Best Utility in terms of speed is Nmap.
write @ cmd prompt:
Nmap -sn -oG ip.txt 192.168.1.1-255
this will just ping all the ip addresses in the range given and store it in simple text file
It takes just 2 secs to scan 255 hosts using Nmap.
In my case I'm using an external maven installation with m2e. I've added my proxy settings to the external maven installation's settings.xml file. These settings haven't been used by m2e even after I've set the external maven installation as default maven installation.
To solve the problem I've configured the global maven settings file within eclipse to be the settings.xml file from my external maven installation.
Now eclipse can download the required artifacts.
For Grammarly you can use:
<textarea data-gramm="false" />
Take a clone of a remote repository and run git branch -a
(to show all the branches git knows about). It will probably look something like this:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
Here, master
is a branch in the local repository. remotes/origin/master
is a branch named master
on the remote named origin
. You can refer to this as either origin/master
, as in:
git diff origin/master..master
You can also refer to it as remotes/origin/master
:
git diff remotes/origin/master..master
These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote master
branch and my master
branch).
remotes/origin/HEAD
is the default branch
for the remote named origin
. This lets you simply say origin
instead of origin/master
.
If you are doing with the postman, Please confirm these stuff when you are requesting API
What is the difference between Git and GitHub?
Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)
In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).
Is Git saving every repository locally (in the user's machine) and in GitHub?
Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:
How does Git compare to a backup system such as Time Machine?
Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, this is a manual process.
If are not collaborating and you are already using a backup system why would you use Git?
For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.
Assuming you're referring to MS-DOS batch files: as it is simply a text file with a special extension, a .bat
file doesn't store an icon of its own.
You can, however, create a shortcut in the .lnk
format that stores an icon.
Disabling the Sync to VBlank checkbox in nvidia-settings (OpenGL Settings tab) does the trick for me.
You shouldn't need to. Allow the user to have whatever preferences they want.
Firefox does that by default because opening a page in a new window is annoying and a page should never be allowed to do so if that is not what is desired by the user. (Firefox does allow you to open tabs in a new window if you set it that way).
How about
`SELECT
my_distinct_column,
max(col1),
max(col2),
max(col3)
...
FROM
my_table
GROUP BY
my_distinct_column`
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use different proxy settings to the current user then you would need to code
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
or
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set webRequest.Proxy
or WebRequest.DefaultWebProxy = null
to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy()
with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.
The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.
Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP
Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.
If you don't have the stdlib then you have to do it manually.
unsigned long hex2int(char *a, unsigned int len)
{
int i;
unsigned long val = 0;
for(i=0;i<len;i++)
if(a[i] <= 57)
val += (a[i]-48)*(1<<(4*(len-1-i)));
else
val += (a[i]-55)*(1<<(4*(len-1-i)));
return val;
}
Note: This code assumes uppercase A-F. It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters.
This can apparently be done by just typing normally,
<textarea name="" id="" placeholder="Hello awesome world. I will break line now
Yup! Line break seems to work."></textarea>
_x000D_
You should be able to fake this by using a custom cell to do your header rows. These will then scroll like any other cell in the table view.
You just need to add some logic in your cellForRowAtIndexPath
to return the right cell type when it is a header row.
You'll probably have to manage your sections yourself though, i.e. have everything in one section and fake the headers. (You could also try returning a hidden view for the header view, but I don't know if that will work)
In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.
I have found that this works...as an example.
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;
For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .
In my case i do an HTML POST with JSON like so...
{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}
I've ran into the same issue and these two links solved for me:
The first one is this one: How do I retrieve the logged in Google account on android phones?
Which presents the code for retrieving the accounts associated with the phone. Basically you will need something like this:
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
And to add the permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
Additionally, if you are using the Emulator the following link will help you to set it up with an account : Android Emulator - Trouble creating user accounts
Basically, it says that you must create an android device based on a API Level and not the SDK Version (like is usually done).
eg:
from: /xxx/a/b/c/d/e/1.html
to: user@remote:/pre_existing/dir/b/c/d/e/1.html
rsync:
cd /xxx/a/ && rsync -auvR b/c/d/e/ user@remote:/pre_existing/dir/
What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.
A nice handy overview table from the Bash Hackers Wiki:
Syntax | Effective result |
---|---|
$* |
$1 $2 $3 … ${N} |
$@ |
$1 $2 $3 … ${N} |
"$*" |
"$1c$2c$3c…c${N}" |
"$@" |
"$1" "$2" "$3" … "${N}" |
where c
in the third row is the first character of $IFS
, the Input Field Separator, a shell variable.
If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*"
trick with the input field separator set to tab IFS=$'\t'
.
If you face this problem in Angular 6, you can fix it by adding the parameter scrollPositionRestoration: 'enabled'
to app-routing.module.ts 's RouterModule:
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'enabled'
})],
exports: [RouterModule]
})
List<Class1> list = new List<Class1>();
int index = list.FindIndex(item => item.Number == textBox6.Text);
Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";
list[index] = newItem;
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
What is System Event Log saying?
Have you tried to repair: Sql Server Installation Center -> Maintenance -> Repair
maybe SSL
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// ignore ssl error
if (handler != null){
handler.proceed();
} else {
super.onReceivedSslError(view, null, error);
}
}
This link works with me: video
The answer posted before didn't work for me until the second click
So what I did is Directly call:
new NewForm().setVisible(true);
this.dispose();//to close the current jframe
clear
echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
unset array
declare -A array
read -p 'Enter number for array size: ' num
for (( i=0; i < num; i++ ))
do
echo -n "(pair $(( $i+1 )))"
read -p ' Enter key: ' k
read -p ' Enter value: ' v
echo " "
array[$k]=$v
done
echo " "
echo "The keys are: " ${!array[@]}
echo "The values are: " ${array[@]}
echo " "
echo "Key <-> Value"
echo "-------------"
for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
echo " "
echo "Thanks for using input associative array 2.0!"
Output:
Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
Enter value: Value#1
(pair 2) Enter key: Key Two
Enter value: Value2
(pair 3) Enter key: Key3
Enter value: Val3
(pair 4) Enter key: Key4
Enter value: Value4
The keys are: Key4 Key3 Key Number 1 Key Two
The values are: Value4 Val3 Value#1 Value2
Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2
Thanks for using input associative array 2.0!
clear
echo "Welcome to input associative array! (written by mO extraordinaire!)"
unset array
declare -A array
read -p 'Enter number for array size: ' num
for (( i=0; i < num; i++ ))
do
read -p 'Enter key and value separated by a space: ' k v
array[$k]=$v
done
echo " "
echo "The keys are: " ${!array[@]}
echo "The values are: " ${array[@]}
echo " "
echo "Key <-> Value"
echo "-------------"
for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
echo " "
echo "Thanks for using input associative array!"
Output:
Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100
The keys are: h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are: 80 10 100 70 60 50 40 30 90 20
Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20
Thanks for using input associative array!
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
Use Valgrind, callgrind and kcachegrind:
valgrind --tool=callgrind ./(Your binary)
generates callgrind.out.x. Read it using kcachegrind.
Use gprof (add -pg):
cc -o myprog myprog.c utils.c -g -pg
(not so good for multi-threads, function pointers)
Use google-perftools:
Uses time sampling, I/O and CPU bottlenecks are revealed.
Intel VTune is the best (free for educational purposes).
Others: AMD Codeanalyst (since replaced with AMD CodeXL), OProfile, 'perf' tools (apt-get install linux-tools)
Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)
-pom-
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
Use this code:
QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
...
}
inputFile.close();
}
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
Another solution is
class T1
{
enum
{
t = 100
};
public:
T1();
};
So t is initialised to 100 and it cannot be changed and it is private.
I was also trying to understand ABI and JesperE’s answer was very helpful.
From a very simple perspective, we may try to understand ABI by considering binary compatibility.
KDE wiki defines a library as binary compatible “if a program linked dynamically to a former version of the library continues running with newer versions of the library without the need to recompile.” For more on dynamic linking, refer Static linking vs dynamic linking
Now, let’s try to look at just the most basic aspects needed for a library to be binary compatibility (assuming there are no source code changes to the library):
Sure, there are many other details but this is mostly what the ABI also covers.
More specifically to answer your question, from the above, we can deduce:
ABI functionality: binary compatibility
existing entities: existing program/libraries/OS
consumer: libraries, OS
Hope this helps!
To get the all related companies name, not based on particular Id.
SELECT
(SELECT GROUP_CONCAT(cmp.cmpny_name)
FROM company cmp
WHERE FIND_IN_SET(cmp.CompanyID, odr.attachedCompanyIDs)
) AS COMPANIES
FROM orders odr
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok"))
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready()
in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close"
:
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular button anywhere on page
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
Swift 3 and Swift 4 Compatible Xcode 9
A Better Solution for this to make a Class for common Navigation bars
I have 5 Controllers and each controller title is changed to orange color. As each controller has 5 navigation controllers so i had to change every one color either from inspector or from code.
So i made a class instead of changing every one Navigation bar from code i just assign this class and it worked on all 5 controller Code reuse Ability. You just have to assign this class to Each controller and thats it.
import UIKit
class NabigationBar: UINavigationBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonFeatures()
}
func commonFeatures() {
self.backgroundColor = UIColor.white;
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor:ColorConstants.orangeTextColor]
}
}
Even you set opacity to zero, the tooltip will appear. Try visibility:hidden
on the element. It is working for me.
The main
function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).
The name main
is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main
, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.
You can declare a function named main
as a member function or in a namespace, but such a function would not be the main
function that designates where the program starts.
The main
function cannot be declared as static
or inline
. It also cannot be overloaded; there can be only one function named main
in the global namespace.
The main
function cannot be used in your program: you are not allowed to call the main
function from anywhere in your code, nor are you allowed to take its address.
The return type of main
must be int
. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main
with a return type of void
; this is probably the most frequently violated rule concerning the main
function).
There are two declarations of main
that must be allowed:
int main() // (1)
int main(int, char*[]) // (2)
In (1), there are no parameters.
In (2), there are two parameters and they are conventionally named argc
and argv
, respectively. argv
is a pointer to an array of C strings representing the arguments to the program. argc
is the number of arguments in the argv
array.
Usually, argv[0]
contains the name of the program, but this is not always the case. argv[argc]
is guaranteed to be a null pointer.
Note that since an array type argument (like char*[]
) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:
int main(int argc, char* argv[])
int main(int argc, char** argv)
Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.
main()
is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return
statement in main()
: if you let main()
return without an explicit return
statement, it's the same as if you had written return 0;
. The following two main()
functions have the same behavior:
int main() { }
int main() { return 0; }
There are two macros, EXIT_SUCCESS
and EXIT_FAILURE
, defined in <cstdlib>
that can also be returned from main()
to indicate success and failure, respectively.
The value returned by main()
is passed to the exit()
function, which terminates the program.
Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main()
function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.
The problem with your code is that you are selecting the .remode_hover
that is a descendant of .remode_selected
. So the first part of getting your code to work correctly is by removing that space
.reMode_selected.reMode_hover:hover
Then, in order to get the style to not work, you have to override the style set by the :hover
. In other words, you need to counter the background-color
property. So the final code will be
.reMode_selected.reMode_hover:hover {
background-color:inherit;
}
.reMode_hover:hover {
background-color: #f0ac00;
}
An alternative method would be to use :not()
, as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected
in there. This will target all elements that don't have a class of .remode_selected
However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.
A third method would be to use jQuery. You can target the .not()
selector, which would be similar to using :not()
in CSS, but with much better browser support
+----+-----------------------+---------+--------------+---------------+
| id | email | name | location_lat | location_long |
+----+-----------------------+---------+--------------+---------------+
| 7 | [email protected] | rembo | 23.0249256 | 72.5269697 |
| 25 | [email protected]. | Rajnis | 23.0233221 | 72.5342112 |
+----+-----------------------+---------+--------------+---------------+
$lat = 23.02350629;
$long = 72.53230239;
DB::
SELECT
("
SELECT
*
FROM
(
SELECT
,
(
( ( acos( sin(( ". $ lat ." * pi() / 180)) * sin(( lat
* pi() / 180)) + cos(( ". $ lat ." pi() / 180 )) * cos(( lat
* pi() / 180)) * cos((( ". $ long ." - LONG
) * pi() / 180))) ) * 180 / pi() ) * 60 * 1.1515 * 1.609344
)
as distance
FROM
users
)
users
WHERE
distance <= 2");
In my case the select2 would open correctly if there was zero or more pills.
But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:
$("#myselect").select2({ width: '100%' });
/^\d+(\.\d{1,2})?$/
var regexp = /^\d+(\.\d{1,2})?$/;_x000D_
_x000D_
console.log("'.74' returns " + regexp.test('.74'));_x000D_
console.log("'7' returns " + regexp.test('7'));_x000D_
console.log("'10.5' returns " + regexp.test('10.5'));_x000D_
console.log("'115.25' returns " + regexp.test('115.25'));_x000D_
console.log("'1535.803' returns " + regexp.test('1535.803'));_x000D_
console.log("'153.14.5' returns " + regexp.test('153.14.5'));_x000D_
console.log("'415351108140' returns " + regexp.test('415351108140'));_x000D_
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));_x000D_
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));_x000D_
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));
_x000D_
/ /
: the beginning and end of the expression^
: whatever follows should be at the beginning of the string you're testing\d+
: there should be at least one digit( )?
: this part is optional\.
: here goes a dot\d{1,2}
: there should be between one and two digits here$
: whatever precedes this should be at the end of the string you're testingYou can use regexr.com or regex101.com for testing regular expressions directly in the browser!
The best solution from my experience : https://stackoverflow.com/a/44177688/3118950, which is override the long getItemId()
and return unique ID instead of the default position. In addition to that answer is imported to notice that old fragment will be kept in the fragment manager in case the total amount is less than the page limit and onDetach()
/onDestory()
will not be called when the fragment is replaced.
Well this is simple answer you want.
MaterialApp(
debugShowCheckedModeBanner: false
)
But if you want to go deep with app (Want a release apk (which don't have debug banner) and if you are using android studio then go to
Run -> Flutter Run 'main.dart' in Relese mode
It will redirects to index.html on localhost:8080 call.
app.get('/',function(req,res){
res.sendFile('index.html', { root: __dirname });
});
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Just to Elaborate an alternate method and a Use case for which it is helpful:
from datetime import datetime, timedelta print datetime.now() + timedelta(days=-1) # Here, I am adding a negative timedelta
from datetime import datetime, timedelta print datetime.now() + timedelta(days=5, hours=-5)
It can similarly be used with other parameters e.g. seconds, weeks etc
In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".
But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.
I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:
XAML:
<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextBox_EnterButtomEvent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height ="0.3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
Input text end press ENTER:
</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
You have entered:
</TextBlock>
<TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>
C# logical part (KeyUp Event handler is attached to a grid element):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
TextBox txtBox = e.Source as TextBox;
if(txtBox != null)
{
this.txtBlock.Text = txtBox.Text;
this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
}
}
}
}
Result:
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
I use Visual Studio 2013 where Project > Export Template is not an option. Here is what I use to clone a project.
From your solution: File > Export Template > select project to make template from, note save path
Download and install VS 2013 SDK Here
Create new VSIX project under Extensibility
From the VSIXManifest Dialog select the Assets tab
Fill in the Author textbox
Choose "Project Template" for Type and Browse to add the exported template (saved at path you noted in step 1)
Save and build the VSIX project. Go to the VSIX project's .../bin/Debug folder and double click to run the .vsix file
Start new instance of Visual Studio and you should see your template under whatever project type your template is. Create a new project from your template
You will have to re-add any dll references
I had ran into this trouble when I left a php foreach: tag unclosed.
<?php foreach($many as $one): ?>
Closing it using the following solved the syntax error: unexpected end of file
<?php endforeach; ?>
Hope it helps someone
Even if you use exceptions, it still output errors.
You have to set $MailerDebug to False wich should look like this
$mail = new PHPMailer();
$mail->MailerDebug = false;
File modification:
ls -t
Inode change:
ls -tc
File access:
ls -tu
"Newest" one at the bottom:
ls -tr
None of this is a creation time. Most Unix filesystems don't support creation timestamps.
So to upgrade scikit-learn package, you have to follow below process
Step-1: Open your terminal(Ctrl+Alt+t)
Step-2: Now for checking currently installed packages along with the
versions installed on your
conda environment by typing conda list
Step-3: Now for upgrade type below command
conda update scikit-learn
Hope it helps!!
"I don't know why this is happening"
Well I have just run into a possible cause:-) Your HTML page is being assembled from separate files. Perhaps you have files which only contain the body or banner portion of your final page. Those files contain a BOM (0xFEFF) marker. Then as part of the merge process you are running HTML tidy or xmllint over the final merged HTML file.
That will cause it!
You need to use "track by" so that the objects can be compared correctly. Otherwise Angular will use the native js way of comparing objects.
So your example code would change to -
<select ng-options="size.code as size.name
for size in sizes track by size.code"
ng-model="item.size.code"></select>
Optimization of the accepted answer:
The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:
import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
Output:
_id HourUTC HourDK ... ElbasAveragePriceEUR ElbasMaxPriceEUR ElbasMinPriceEUR
0 264028 2019-01-01T00:00:00+00:00 2019-01-01T01:00:00 ... NaN NaN NaN
1 138428 2017-09-03T15:00:00+00:00 2017-09-03T17:00:00 ... 33.28 33.4 32.0
2 138429 2017-09-03T16:00:00+00:00 2017-09-03T18:00:00 ... 35.20 35.7 34.9
3 138430 2017-09-03T17:00:00+00:00 2017-09-03T19:00:00 ... 37.50 37.8 37.3
4 138431 2017-09-03T18:00:00+00:00 2017-09-03T20:00:00 ... 39.65 42.9 35.3
.. ... ... ... ... ... ... ...
995 139290 2017-10-09T13:00:00+00:00 2017-10-09T15:00:00 ... 38.40 38.4 38.4
996 139291 2017-10-09T14:00:00+00:00 2017-10-09T16:00:00 ... 41.90 44.3 33.9
997 139292 2017-10-09T15:00:00+00:00 2017-10-09T17:00:00 ... 46.26 49.5 41.4
998 139293 2017-10-09T16:00:00+00:00 2017-10-09T18:00:00 ... 56.22 58.5 49.1
999 139294 2017-10-09T17:00:00+00:00 2017-10-09T19:00:00 ... 56.71 65.4 42.2
PS: API is for Danish electricity prices
You cannot, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
You can use placeholders and feed_dict.
Suppose we have numpy arrays like these:
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
You can declare two placeholders:
X = tf.placeholder("float")
Y = tf.placeholder("float")
Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...
Finally, when you run the model/cost, feed the numpy arrays using feed_dict:
with tf.Session() as sess:
....
sess.run(model, feed_dict={X: trY, Y: trY})
This works for me
find _CACHE_* | while read line; do
cat "$line" | grep "something"
done
to print all (or arbitrarily many) lines of the grouped df:
import pandas as pd
pd.set_option('display.max_rows', 500)
grouped_df = df.group(['var1', 'var2'])
print(grouped_df)
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
You Can try This To Run Command Then cmd
Exits
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
Process.Start("cmd", "/k YourCode")
Not plumbing, but I have these in my .gitconfig:
lsum = log -n 1 --pretty=format:'%s'
lmsg = log -n 1 --pretty=format:'%s%n%n%b'
That's "last summary" and "last message". You can provide a commit to get the summary or message of that commit. (I'm using 1.7.0.5 so don't have %B.)
You can use display:inline-block
with white-space:nowrap
. Write like this:
.scrolls {
overflow-x: scroll;
overflow-y: hidden;
height: 80px;
white-space:nowrap
}
.imageDiv img {
box-shadow: 1px 1px 10px #999;
margin: 2px;
max-height: 50px;
cursor: pointer;
display:inline-block;
*display:inline;/* For IE7*/
*zoom:1;/* For IE7*/
vertical-align:top;
}
Check this http://jsfiddle.net/YbrX3/
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
I think, it should be like this:
class foo():
input = get_input(__qualname__)
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
You may simply use both as per the specification kindly provided by Oli.
I always use border:0 none;
.
Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.
Though border:0;
will normally default the border style to none
, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;
.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
UPDATE 2: without seconds option
UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/
I created this function to do this:
function formatDate(date) {_x000D_
var d = new Date(date);_x000D_
var hh = d.getHours();_x000D_
var m = d.getMinutes();_x000D_
var s = d.getSeconds();_x000D_
var dd = "AM";_x000D_
var h = hh;_x000D_
if (h >= 12) {_x000D_
h = hh - 12;_x000D_
dd = "PM";_x000D_
}_x000D_
if (h == 0) {_x000D_
h = 12;_x000D_
}_x000D_
m = m < 10 ? "0" + m : m;_x000D_
_x000D_
s = s < 10 ? "0" + s : s;_x000D_
_x000D_
/* if you want 2 digit hours:_x000D_
h = h<10?"0"+h:h; */_x000D_
_x000D_
var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);_x000D_
_x000D_
var replacement = h + ":" + m;_x000D_
/* if you want to add seconds_x000D_
replacement += ":"+s; */_x000D_
replacement += " " + dd;_x000D_
_x000D_
return date.replace(pattern, replacement);_x000D_
}_x000D_
_x000D_
alert(formatDate("February 04, 2011 12:00:00"));
_x000D_
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar
You should not have any server-specific libraries in the /WEB-INF/lib
. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib
(and also in JRE/lib
and JRE/lib/ext
if you have placed any of them there).
A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet
classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar
and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.
if you dont push your changes to git yet
git reset --soft HEAD~1
It will reset all the changes and revert to one commit back
If this is the last commit you made and you want to delete the file from local and remote repository try this :
git rm <file>
git commit --amend
or even better :
reset first
git reset --soft HEAD~1
reset the unwanted file
git reset HEAD path/to/unwanted_file
commit again
git commit -c ORIG_HEAD
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global
.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B
with the variable named x_local
and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B
calls func_A
. In this example, order does matter:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Note that global
is only required to modify global objects. You can still access them from within a function without declaring global
.
Thus, we have:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally
and access_only
-- access_only
is accessing the global x despite not calling global
, and even though create_locally
doesn't use global
either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
For Black Screen Error ( Swift 4 & 4.2 ) .
I fixed the black screen problem. In the verified solution The keyboard height changes after tapping and this is causing black screen.
Have to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey
var isKeyboardAppear = false
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if !isKeyboardAppear {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
isKeyboardAppear = true
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if isKeyboardAppear {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
isKeyboardAppear = false
}
}
This works for MVC 5:
<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
Link text
</a>
ngInit
can help to initialize variables.
<div ng-app='app'>
<div ng-controller="MyController" ng-init="myVar='test'">
{{myVar}}
</div>
</div>
I've just finished developing the plugin and it is available for everyone to use! Hope you will enjoy it.
First of all, make sure you have the jQuery
library is included. The best way to get the latest jQuery version is to update your head tag with:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
After downloading the files, make sure you include them in your project:
<link rel="stylesheet" type="text/css" href="css/splitchar.css">
<script type="text/javascript" src="js/splitchar.js"></script>
All you have to do is to asign the class splitchar
, followed by the desired style to the element wrapping your text. e.g
<h1 class="splitchar horizontal">Splitchar</h1>
After all this is done, just make sure you call the jQuery function in your document ready file like this:
$(".splitchar").splitchar();
In order to make the text look exactly as you want it to, all you have to do is apply your design like this:
.horizontal { /* Base CSS - e.g font-size */ }
.horizontal:before { /* CSS for the left half */ }
.horizontal:after { /* CSS for the right half */ }
That's it! Now you have the Splitchar
plugin all set. More info about it at http://razvanbalosin.com/Splitchar.js/.
1) is based on the fact that calling a DLL function is always using an extra indirect jump. Today, this is usually negligible. Inside the DLL there is some more overhead on i386 CPU's, because they can't generate position independent code. On amd64, jumps can be relative to the program counter, so this is a huge improvement.
2) This is correct. With optimizations guided by profiling you can usually win about 10-15 percent performance. Now that CPU speed has reached its limits it might be worth doing it.
I would add: (3) the linker can arrange functions in a more cache efficient grouping, so that expensive cache level misses are minimised. It also might especially effect the startup time of applications (based on results i have seen with the Sun C++ compiler)
And don't forget that with DLLs no dead code elimination can be performed. Depending on the language, the DLL code might not be optimal either. Virtual functions are always virtual because the compiler doesn't know whether a client is overwriting it.
For these reasons, in case there is no real need for DLLs, then just use static compilation.
EDIT (to answer the comment, by user underscore)
Here is a good resource about the position independent code problem http://eli.thegreenplace.net/2011/11/03/position-independent-code-pic-in-shared-libraries/
As explained x86 does not have them AFAIK for anything else then 15 bit jump ranges and not for unconditional jumps and calls. That's why functions (from generators) having more then 32K have always been a problem and needed embedded trampolines.
But on popular x86 OS like Linux you do not need to care if the .so/DLL file is not generated with the gcc
switch -fpic
(which enforces the use of the indirect jump tables). Because if you don't, the code is just fixed like a normal linker would relocate it. But while doing this it makes the code segment non shareable and it would need a full mapping of the code from disk into memory and touching it all before it can be used (emptying most of the caches, hitting TLBs) etc. There was a time when this was considered slow.
So you would not have any benefit anymore.
I do not recall what OS (Solaris or FreeBSD) gave me problems with my Unix build system because I just wasn't doing this and wondered why it crashed until I applied -fPIC
to gcc
.
You can use COPY. You need to specify the directory explicitly. It won't be created by itself
COPY go /usr/local/go
Reference: Docker CP reference
Pleas find bellow Program
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedListManual {
Node node;
public void pushElement(int next_node) {
Node nd = new Node(next_node);
nd.next = node;
node = nd;
}
public int getSize() {
Node temp = node;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
public void getElement() {
Node temp = node;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
LinkedListManual obj = new LinkedListManual();
obj.pushElement(1);
obj.pushElement(2);
obj.pushElement(3);
obj.getElement(); //get element
System.out.println(obj.getSize()); //get size of link list
}
}
I got your problem , and here is my answer:
prices = [5, 12, 45]
list=['1','2','3']
for i in range(1,3):
vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])
so while printing:
price1 = 5
price2 = 12
price3 = 45
For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.
$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));
you should use extend()
>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]
other info: append vs. extend
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );
This works great for me for text only, and easy on the eye.
Check your problem is solved.
insert
into tablename (timestamp_value)
values (TO_TIMESTAMP(:ts_val, 'YYYY-MM-DD HH24:MI:SS'));
if you want the current time stamp to be inserted then:
insert
into tablename (timestamp_value)
values (CURRENT_TIMESTAMP);
You probably did not install MySQL via yum? The version of MySQLDB in the repository is tied to the version of MySQL in the repository. The versions need to match.
Your choices are:
Use This its is very useful for your solution:
this
inside the step callback isn't the element but the object passed to animate()
$('.Count').each(function (_, self) {
jQuery({
Counter: 0
}).animate({
Counter: $(self).text()
}, {
duration: 1000,
easing: 'swing',
step: function () {
$(self).text(Math.ceil(this.Counter));
}
});
});
Another way to do this and keep the references to this
would be
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
The modern way to do this is with flexbox, adding align-items: flex-end;
on the container.
With this content:
<div class="Container">
<div>one</div>
<div>two</div>
</div>
Use this style:
.Container {
display: flex;
align-items: flex-end;
}
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
In Python 2.6+, you could use io.open()
that is default (builtin open()
) on Python 3:
import io
with io.open(filename, 'w', encoding=character_encoding) as file:
file.write(unicode_text)
It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding)
multiple times). Unlike codecs
module, io
module has a proper universal newlines support.
Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.
Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.
Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row
:
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
You could then access one:
MyStringArrays.ElementAt(0)[1]
If you use linqpad, here is a very simple scenario of your example:
class Datatable
{
public List<data> rows { get; set; }
public Datatable(){
rows = new List<data>();
}
}
class data
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
void Main()
{
var datatable = new Datatable();
var r = new data();
r.Name = "Jim";
r.Address = "USA";
r.Age = 23;
datatable.rows.Add(r);
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
var s = MyStringArrays.ElementAt(0)[1];
Console.Write(s);//"USA"
}
I wrote a long version, with all the options I might need: http://sam.nipl.net/code/python/find.py
I guess it will fit here too:
#!/usr/bin/env python
import os
import sys
def ls(dir, hidden=False, relative=True):
nodes = []
for nm in os.listdir(dir):
if not hidden and nm.startswith('.'):
continue
if not relative:
nm = os.path.join(dir, nm)
nodes.append(nm)
nodes.sort()
return nodes
def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
root = os.path.join(root, '') # add slash if not there
for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
if relative:
parent = parent[len(root):]
if dirs and parent:
yield os.path.join(parent, '')
if not hidden:
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
if files:
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
def test(root):
print "* directory listing, with hidden files:"
print ls(root, hidden=True)
print
print "* recursive listing, with dirs, but no hidden files:"
for f in find(root, dirs=True):
print f
print
if __name__ == "__main__":
test(*sys.argv[1:])
For what it's worth, a shorter way to write code to check each command for success is:
command1 || echo "command1 borked it"
command2 || echo "command2 borked it"
It's still tedious but at least it's readable.
Use the Config class:
Config::set('site_settings', $site_settings);
Config::get('site_settings');
http://laravel.com/docs/4.2/configuration
Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.
A quick update to Michael's excellent answer above.
For Rails 4.0+ you need to put your sort in a block like this:
class Book < ActiveRecord::Base
default_scope { order('created_at DESC') }
end
Notice that the order statement is placed in a block denoted by the curly braces.
They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:
Support for calling #default_scope without a block is removed. For example instead of
default_scope where(color: 'red')
, please usedefault_scope { where(color: 'red') }
. (Alternatively you can just redefine self.default_scope.)
As @Dan mentions in his comment below, you can do a more rubyish syntax like this:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
or with multiple columns:
class Book < ActiveRecord::Base
default_scope { order({begin_date: :desc}, :name) }
end
Thanks @Dan!
ReadFully Reads b.length bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.
const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);
// Make sure we're a module
export {};
Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.
Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.
In case you use yarn
:
yarn config set strict-ssl false
If you have a module defined as an android library project you'll get .aar files for all build flavors (debug and release by default) in the build/outputs/aar/
directory of that project.
your-library-project
|- build
|- outputs
|- aar
|- appframework-debug.aar
- appframework-release.aar
If these files don't exist start a build with
gradlew assemble
for macOS users
./gradlew assemble
A library project has a build.gradle
file containing apply plugin: com.android.library
. For reference of this library packaged as an .aar
file you'll have to define some properties like package and version.
Example build.gradle
file for library (this example includes obfuscation in release):
apply plugin: 'com.android.library'
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
minSdkVersion 9
targetSdkVersion 21
versionCode 1
versionName "0.1.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
In your app project you can drop this .aar
file in the libs
folder and update the build.gradle
file to reference this library using the below example:
apply plugin: 'com.android.application'
repositories {
mavenCentral()
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
android {
compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 20
versionCode 4
versionName "0.4.0"
applicationId "yourdomain.yourpackage"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
}
}
}
dependencies {
compile 'be.hcpl.android.appframework:appframework:0.1.0@aar'
}
Alternative options for referencing local dependency files in gradle can be found at: http://kevinpelgrims.com/blog/2014/05/18/reference-a-local-aar-in-your-android-project
If you need to share these .aar
files within your organization check out maven. A nice write up on this topic can be found at: https://web.archive.org/web/20141002122437/http://blog.glassdiary.com/post/67134169807/how-to-share-android-archive-library-aar-across
An aar file is just a .zip
with an alternative extension and specific content. For details check this link about the aar format.
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
It is possible by using the legend tag. Refer to http://www.w3schools.com/html5/tag_legend.asp
I stumbled upon this today: Element.redraw() for prototype.js
Using:
Element.addMethods({
redraw: function(element){
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
(function(){n.parentNode.removeChild(n)}).defer();
return element;
}
});
However, I've noticed sometimes that you must call redraw() on the problematic element directly. Sometimes redrawing the parent element won't solve the problem the child is experiencing.
Good article about the way browsers render elements: Rendering: repaint, reflow/relayout, restyle
Adding to Brian Agnew's answer.
You can also do //div[@id='..' or @class='...]
and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')]
.
shell> mysqladmin flush-logs
shell> mv host_name.err-old backup-directory
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
Use Date object:
var time = Date.parse('02.02.1999');
document.writeln(time);
Give: 917902800000
//an easy way:
str := fmt.Sprint(data)
This worked for me
[ImageViewName setImage:[UIImage imageNamed: @"ImageName.png"]];
Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.
Because this captures all exceptions. It's unlikely that your program can recover from any of them.
You should handle only exceptions that you know how to recover from. If you don't anticipate a certain kind of exception, don't handle it, crash loudly (write details to the log), then diagnose logs and fix code.
Swallowing exceptions is bad, don't do this.
If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P
Yesterday, I started to write my own way to bind data.
It's very funny to play with it.
I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.
https://jsfiddle.net/2ozoovne/1/
<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />
Here is the code:
(function(){
if ( ! ( 'SmartBind' in window ) ) { // never run more than once
// This hack sets a "proxy" property for HTMLInputElement.value set property
var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
newDescriptor.set=function( value ){
if ( 'settingDomBind' in this )
return;
var hasDataBind=this.hasAttribute('data-bind');
if ( hasDataBind ) {
this.settingDomBind=true;
var dataBind=this.getAttribute('data-bind');
if ( ! this.hasAttribute('data-bind-context-id') ) {
console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
} else {
var bindContextId=this.getAttribute('data-bind-context-id');
if ( bindContextId in SmartBind.contexts ) {
var bindContext=SmartBind.contexts[bindContextId];
var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
SmartBind.setDataValue( dataTarget, value);
} else {
console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
}
}
delete this.settingDomBind;
}
nativeHTMLInputElementValue.set.bind(this)( value );
}
Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);
var uid= function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
// SmartBind Functions
window.SmartBind={};
SmartBind.BindContext=function(){
var _data={};
var ctx = {
"id" : uid() /* Data Bind Context Id */
, "_data": _data /* Real data object */
, "mapDom": {} /* DOM Mapped objects */
, "mapDataTarget": {} /* Data Mapped objects */
}
SmartBind.contexts[ctx.id]=ctx;
ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data")) /* Proxy object to _data */
return ctx;
}
SmartBind.getDataTarget=function(bindContext, bindPath){
var bindedObject=
{ bindContext: bindContext
, bindPath: bindPath
};
var dataObj=bindContext;
var dataObjLevels=bindPath.split('.');
for( var i=0; i<dataObjLevels.length; i++ ) {
if ( i == dataObjLevels.length-1 ) { // last level, set value
bindedObject={ target: dataObj
, item: dataObjLevels[i]
}
} else { // digg in
if ( ! ( dataObjLevels[i] in dataObj ) ) {
console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
break;
}
dataObj=dataObj[dataObjLevels[i]];
}
}
return bindedObject ;
}
SmartBind.contexts={};
SmartBind.add=function(bindContext, domObj){
if ( typeof domObj == "undefined" ){
console.error("No DOM Object argument given ", bindContext);
return;
}
if ( ! domObj.hasAttribute('data-bind') ) {
console.warn("Object has no data-bind attribute", domObj);
return;
}
domObj.setAttribute("data-bind-context-id", bindContext.id);
var bindPath=domObj.getAttribute('data-bind');
if ( bindPath in bindContext.mapDom ) {
bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
} else {
bindContext.mapDom[bindPath]=[domObj];
}
var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
bindContext.mapDataTarget[bindPath]=bindTarget;
domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
}
SmartBind.setDataValue=function(bindTarget,value){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
bindTarget.target[bindTarget.item]=value;
}
}
SmartBind.getDataValue=function(bindTarget){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
return bindTarget.target[bindTarget.item];
}
}
SmartBind.getProxyHandler=function(bindContext, bindPath){
return {
get: function(target, name){
if ( name == '__isProxy' )
return true;
// just get the value
// console.debug("proxy get", bindPath, name, target[name]);
return target[name];
}
,
set: function(target, name, value){
target[name]=value;
bindContext.mapDataTarget[bindPath+"."+name]=value;
SmartBind.processBindToDom(bindContext, bindPath+"."+name);
// console.debug("proxy set", bindPath, name, target[name], value );
// and set all related objects with this target.name
if ( value instanceof Object) {
if ( !( name in target) || ! ( target[name].__isProxy ) ){
target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
}
// run all tree to set proxies when necessary
var objKeys=Object.keys(value);
// console.debug("...objkeys",objKeys);
for ( var i=0; i<objKeys.length; i++ ) {
bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
continue;
target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
}
// TODO it can be faster than run all items
var bindKeys=Object.keys(bindContext.mapDom);
for ( var i=0; i<bindKeys.length; i++ ) {
// console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
// console.log("its ok, lets update dom...", bindKeys[i]);
SmartBind.processBindToDom( bindContext, bindKeys[i] );
}
}
}
return true;
}
};
}
SmartBind.processBindToDom=function(bindContext, bindPath) {
var domList=bindContext.mapDom[bindPath];
if ( typeof domList != 'undefined' ) {
try {
for ( var i=0; i < domList.length ; i++){
var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
if ( 'target' in dataTarget )
domList[i].value=dataTarget.target[dataTarget.item];
else
console.warn("Could not get data target", bindContext, bindPath);
}
} catch (e){
console.warn("bind fail", bindPath, bindContext, e);
}
}
}
}
})();
Then, to set, just:
var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));
var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));
setTimeout( function() {
document.getElementById('b').value='Via Script works too!'
}, 2000);
document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})
For now, I've just added the HTMLInputElement value bind.
Let me know if you know how to improve it.
I had a similar issue when working on local. You url is going to be the path to the local file e.g. file:///Users/PeterP/Desktop/folder/index.html.
Please note that I am on a MAC.
I got round this by installing http-server globally. https://www.npmjs.com/package/http-server
Steps:
npm install http-server -g
http-server ~/Desktop/folder/
PS: I assume you have node installed, otherwise you wont get very far running npm commands.
Despite the plethora of wrong answers here that attempt to circumvent the error by numerically manipulating the predictions, the root cause of your error is a theoretical and not computational issue: you are trying to use a classification metric (accuracy) in a regression (i.e. numeric prediction) model (LinearRegression
), which is meaningless.
Just like the majority of performance metrics, accuracy compares apples to apples (i.e true labels of 0/1 with predictions again of 0/1); so, when you ask the function to compare binary true labels (apples) with continuous predictions (oranges), you get an expected error, where the message tells you exactly what the problem is from a computational point of view:
Classification metrics can't handle a mix of binary and continuous target
Despite that the message doesn't tell you directly that you are trying to compute a metric that is invalid for your problem (and we shouldn't actually expect it to go that far), it is certainly a good thing that scikit-learn at least gives you a direct and explicit warning that you are attempting something wrong; this is not necessarily the case with other frameworks - see for example the behavior of Keras in a very similar situation, where you get no warning at all, and one just ends up complaining for low "accuracy" in a regression setting...
I am super-surprised with all the other answers here (including the accepted & highly upvoted one) effectively suggesting to manipulate the predictions in order to simply get rid of the error; it's true that, once we end up with a set of numbers, we can certainly start mingling with them in various ways (rounding, thresholding etc) in order to make our code behave, but this of course does not mean that our numeric manipulations are meaningful in the specific context of the ML problem we are trying to solve.
So, to wrap up: the problem is that you are applying a metric (accuracy) that is inappropriate for your model (LinearRegression
): if you are in a classification setting, you should change your model (e.g. use LogisticRegression
instead); if you are in a regression (i.e. numeric prediction) setting, you should change the metric. Check the list of metrics available in scikit-learn, where you can confirm that accuracy is used only in classification.
Compare also the situation with a recent SO question, where the OP is trying to get the accuracy of a list of models:
models = []
models.append(('SVM', svm.SVC()))
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
#models.append(('SGDRegressor', linear_model.SGDRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('BayesianRidge', linear_model.BayesianRidge())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LassoLars', linear_model.LassoLars())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('ARDRegression', linear_model.ARDRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('PassiveAggressiveRegressor', linear_model.PassiveAggressiveRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('TheilSenRegressor', linear_model.TheilSenRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LinearRegression', linear_model.LinearRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
where the first 6 models work OK, while all the rest (commented-out) ones give the same error. By now, you should be able to convince yourself that all the commented-out models are regression (and not classification) ones, hence the justified error.
A last important note: it may sound legitimate for someone to claim:
OK, but I want to use linear regression and then just round/threshold the outputs, effectively treating the predictions as "probabilities" and thus converting the model into a classifier
Actually, this has already been suggested in several other answers here, implicitly or not; again, this is an invalid approach (and the fact that you have negative predictions should have already alerted you that they cannot be interpreted as probabilities). Andrew Ng, in his popular Machine Learning course at Coursera, explains why this is a bad idea - see his Lecture 6.1 - Logistic Regression | Classification at Youtube (explanation starts at ~ 3:00), as well as section 4.2 Why Not Linear Regression [for classification]? of the (highly recommended and freely available) textbook An Introduction to Statistical Learning by Hastie, Tibshirani and coworkers...
I had a similar problem on Ubuntu due to having multiple copies of ruby installed. (1.8 and 1.9.1) Unfortunately I need both of them. The solution is to use:
$ sudo update-alternatives --config ruby
There are 2 choices for the alternative ruby (providing /usr/bin/ruby).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/ruby1.8 50 auto mode
1 /usr/bin/ruby1.8 50 manual mode
2 /usr/bin/ruby1.9.1 10 manual mode
Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/ruby1.9.1 to provide /usr/bin/ruby (ruby) in manual mode.
After doing that bundle install succeeded.
const dateFormat = 'MM-DD-YYYY';
const currentDateStringType = moment(new Date()).format(dateFormat);
const currentDate = moment(new Date() ,dateFormat); // use this
moment.suppressDeprecationWarnings = true;
I've read this whole thread, and I just want to point out what seems like an inconsistency to me.
The compiler prevents you from doing the assignment with Lists:
List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList; // Compiler error
But the compiler is perfectly fine with arrays:
Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray; // No problem
The argument about whether the assignment is known to be safe falls apart here. The assignment I did with the array is not safe. To prove that, if I follow that up with this:
myAnimalsArray[1] = new Giraffe();
I get a runtime exception "ArrayTypeMismatchException". How does one explain this? If the compiler really wants to prevent me from doing something stupid, it should have prevented me from doing the array assignment.
The Image pull policy will always actually help to pull the image every single time a new pod is created (this can be in any case like scaling the replicas, or pod dies and new pod is created)
But if you want to update the image of the current running pod, deployment is the best way. It leaves you flawless update without any problem (mainly when you have a persistent volume attached to the pod) :)
If you have a std::wstring object, you can call c_str()
on it to get a wchar_t*
:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar
routine. That will give you an LPWSTR
, which is equivalent to wchar_t*
.
You can use this:
bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
def bank_holiday(month):
month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
print(bankHoliday[month])
bank_holiday(int(input("Which month would you like to check out: ")))
I had the same problem and for me it was because the vc2010 redist x86 was too recent.
Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named
and check if you have the following error
Installation Blockers:
A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.
Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).
then go to Control Panel>Program & Features and uninstall all the
After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.
[[ -s file ]] --> Checks if file has size greater than 0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
If needed, this checks all the *.txt files in the current directory; and reports all the empty file:
for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done
The simplest way to remove duplicates whilst preserving order is to use collections.OrderedDict (Python 2.7+).
from collections import OrderedDict
d = OrderedDict()
for x in mylist:
d[x] = True
print d.iterkeys()
Either as most people answered: the file doesn't exist / you're not specifying the path correctly.
Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).
For gnuplot 4.6.0 on windows 7, terminal type set to windows
Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")
Make sure you use this syntax:
plot 'path\path\desireddatafile.txt'
NOT
plot "< path\path\desireddatafile.txt>"
NOR
plot "path\path\desireddatafile.txt"
also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.
Based on Mr Zorn's answer, I use a static method in my abstract Utility class:
public abstract class Utility {
...
public static View.OnTouchListener imgPress(){
return imgPress(0x77eeddff); //DEFAULT color
}
public static View.OnTouchListener imgPress(final int color){
return new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
view.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
view.invalidate();
break;
}
case MotionEvent.ACTION_UP:
v.performClick();
case MotionEvent.ACTION_CANCEL: {
ImageView view = (ImageView) v;
//Clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
};
}
...
}
Then I use it with onTouchListener:
ImageView img=(ImageView) view.findViewById(R.id.image);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { /* Your click action */ }
});
img_zc.setOnTouchListener(Utility.imgPress()); //Or Utility.imgPress(int_color_with_alpha)
It is very simple if you have a lot of images, and you want a simple onTouch effect, without any XML drawable and only one image.
Actually the way of setting environment variables is different between different Operating System.
set PUBLIC_URL=http://xxxx.com&&npm start
(Note: the lack of whitespace is intentional.)
PUBLIC_URL=http://xxxx.com npm start
cross-env
{
"scripts": {
"serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
}
}
But if it does not solve the problem, you probably have installed sql 2008 R2, so the solution that worked to me was this wamp server problems yellow symbol
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
Just use the build-in feature of Angular CLI
ng update
to update to the latest version.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
You can use this way, but be sure that there is no Page.Redirect()
is used.
If you want to redirect to another page then you can try this:
page.aspx:
<asp:Button AccessKey="S" ID="submitBtn" runat="server" OnClick="Submit" Text="Submit"
Width="90px" ValidationGroup="vg" CausesValidation="true" OnClientClick = "Confirm()" />
JavaScript code:
function Confirm()
{
if (Page_ClientValidate())
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Data has been Added. Do you wish to Continue ?"))
{
confirm_value.value = "Yes";
}
else
{
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
and this is your code behind snippet :
protected void Submit(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Response.Redirect("~/AddData.aspx");
}
else
{
Response.Redirect("~/ViewData.aspx");
}
}
This will sure work.
I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE @ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:
DECLARE @ORDER_NO char(50)
SELECT @ORDER_NO = 'OR/201910/0012%'
SELECT * FROM orders WHERE ord_no LIKE RTRIM(@ORDER_NO)
Try something like this
PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };
// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();
You might need to re-adjust slightly on the widths and borders but that is a one shot to do.
Imagine your task is to classify a speech to a language.
You can do it by either:
or
The first one is the generative approach and the second one is the discriminative approach.
Check this reference for more details: http://www.cedar.buffalo.edu/~srihari/CSE574/Discriminative-Generative.pdf.
It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:
import itertools
m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i) # skips m = 5
As an aside, you woudn't want to use (*range(m), *range(m + 1, n))
even though it works because it will expand the iterables into a tuple and this is memory inefficient.
Credit: comment by njzk2, answer by Locke
You have 9 fields listed, but only 8 values. Try adding the method.
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
A simpler option: just uncomment the following part of the configuration (which is originally commented out) in the /etc/vim/vimrc file:
if has("autocmd")
filetype plugin indent on
endif
Use this :
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
To add new ViewController
once you have have an existing ViewController
, follow below step:
Click on background of Main.storyboard
.
Search and select ViewController
from object library at the
utility window.
Drag and drop it in background to create a new ViewController
.
For me just worked iisreset (run cmd as administrator -> iisreset). Maybe somebody could give it a try.
Similar to @monowerker, I needed to reindex an array using an object's key...
$new = array();
$old = array(
(object)array('id' => 123),
(object)array('id' => 456),
(object)array('id' => 789),
);
print_r($old);
array_walk($old, function($item, $key, &$reindexed_array) {
$reindexed_array[$item->id] = $item;
}, &$new);
print_r($new);
This resulted in:
Array
(
[0] => stdClass Object
(
[id] => 123
)
[1] => stdClass Object
(
[id] => 456
)
[2] => stdClass Object
(
[id] => 789
)
)
Array
(
[123] => stdClass Object
(
[id] => 123
)
[456] => stdClass Object
(
[id] => 456
)
[789] => stdClass Object
(
[id] => 789
)
)
You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href
based on their values with CSS only..
Attributes selectors allows you play around some extra with id
and class
attributes
Here is an awesome read on Attribute Selectors
a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
color: green;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
a[id*="google"] {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
a[class*="stack"] {_x000D_
color: yellow;_x000D_
}
_x000D_
<a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
<br>_x000D_
<a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
<br>_x000D_
<a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
_x000D_
Browser support:
IE6+, Chrome, Firefox & Safari
You can check detail here.
Depending on the structure of the string, you can use lstrip
:
str = str.lstrip(':')
But this would remove all colons at the beginning, i.e. if you have ::foo
, the result would be foo
. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.
TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");
Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Unless you're looking for something specific, you can already do Regular Expression matching using regular Javascript with strings.
For example, you can do matching using a string by something like this...
var phrase = "This is a phrase";
phrase = phrase.replace(/is/i, "is not");
alert(phrase);
Is there something you're looking for other than just Regular Expression matching in general?
Hey there, this works for me (I couldn't get this working with the Google API links you were using):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Beef Burrito</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
</head>
<body>
<div class="draggable" style="border: 1px solid black; width: 50px; height: 50px; position: absolute; top: 0px; left: 0px;">asdasd</div>
<script type="text/javascript">
$(".draggable").draggable();
</script>
</body>
</html>
I needed to check for A-Z, a-z, 0-9; without a regex (even though the OP asks for regex).
Blending various answers and comments here, and discussion from https://stackoverflow.com/a/9975693/292060, this tests for letter or digit, avoiding other language letters, and avoiding other numbers such as fraction characters.
if (!String.IsNullOrEmpty(testString)
&& testString.All(c => Char.IsLetterOrDigit(c) && (c < 128)))
{
// Alphanumeric.
}
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
If this issue with HTTP error 407 happened to selected packages only then the problem is not in the proxy setting and internet connection. You even may expose your PC to the internet through NAT and still will face this problem. Typically at the same time you can download desired packages in browser. The only solution I find: delete the .gradle folder in your profile (not in the project). After that sync the project, it will take a long time but restore everything.
Judge by yesterday's weather. How long did it take last time? Are you trending longer or shorter? Each shop is different.
Most agile shops need a lot less time, have drastically fewer defects, and quicker time to resolve them because of TDD. Even so, most agile shops have some measurable time spent with testing/QC.
If this is the first test run for this application, then the answer is "lets see" followed by an attempt. It depends on how quick you can get questions answered, - how testable it is, - how many features/functions - how many defects are discovered, - how quickly issues are resolved, - how many times the code cycles through testing, and - how many times testing is blocked by bugs. There is no way to tell. You could call it 50% or 175% or more, and not be wrong. Why not make a rough guess and multiply by Pi? It won't be much worse than any other answer you can make up.
You should (must) know how long it takes now and whether it's getting faster or slower, and whether the coverage is increasing or decreasing. With those three bits of information, you should be able to guess quite well.
JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula
is perfect for this when using Hibernate. You can use an SQL fragment:
@Formula("PRICE*1.155")
private float finalPrice;
Or even complex queries on other tables:
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
Where id
is the id
of the current entity.
The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.
Without more details, I can't give a more precise answer but the above link should be helpful.
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax()
method:
<script type="text/javascript">
$.ajax({
url: '@Url.Action("NameOfYourAction")',
type: 'GET',
cache: false,
success: function(result) {
// you could use the result.values dictionary here
}
});
</script>
So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:
if (foo == null || foo.isClosed()) {
return;
}
if (bar != null && bar.isBlue()) {
foo.doSomething();
}
Using |
and &
instead could result in a NullPointerException
being thrown here.
Thou shalt always encode URLs.
Here is how Ruby encodes your URL:
irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
Try:
if start not in graph:
For more info see ProgrammerSought
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
I use this in our internal common js file. I just add the class to any input that needs this behavior.
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});