You can use Column.isNull
/ Column.isNotNull
:
df.where(col("dt_mvmt").isNull())
df.where(col("dt_mvmt").isNotNull())
If you want to simply drop NULL
values you can use na.drop
with subset
argument:
df.na.drop(subset=["dt_mvmt"])
Equality based comparisons with NULL
won't work because in SQL NULL
is undefined so any attempt to compare it with another value returns NULL
:
sqlContext.sql("SELECT NULL = NULL").show()
## +-------------+
## |(NULL = NULL)|
## +-------------+
## | null|
## +-------------+
sqlContext.sql("SELECT NULL != NULL").show()
## +-------------------+
## |(NOT (NULL = NULL))|
## +-------------------+
## | null|
## +-------------------+
The only valid method to compare value with NULL
is IS
/ IS NOT
which are equivalent to the isNull
/ isNotNull
method calls.
CentOS 7: I had the libcurl and gnutls development packages installed already, but still got the "cannot load git2r.so" error when installing devtools in R. I had to "reinstall" them for it to work:
sudo yum reinstall gnutls-devel.x86_64
They have wrapped most stuff need to solve your problem, one of the tests looks like this:
String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));
String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);
This error mostly comes when we forcefully kill the weblogic server ("kill -9 process id"), so before restart kindly check all the ports status which weblogic using e.g. http port , DEBUG_PORT etc by using this command to see which whether this port is active or not.
netstat –an | grep (Admin: 7001 or something, Managed server- 7002, 7003 etc) eg: netstat –an | grep 7001
If it returns value then, option 1: wait for some time, so that background process can release the port option 2: execute stopweblogic.sh Option 3: Bounce the server/host or restart the system.
My issue was resolved by option 2.
if you want to set jvm args on eclipse you can use below:
see below two links to accomplish it:
And for Tomcat you can create a setenv.bat
file in bin folder of Tomcat and add below lines to it :
echo "hello im starting setenv"
set CATALINA_OPTS=-DNLP.home=${NLP.home} -Dhostname=${hostname}
Here is assembly code:
7f0b024734be: 48 8d 14 f5 00 00 00 lea rdx,[rsi*8]
7f0b024734c5: 00
7f0b024734c6: 48 03 13 add rdx,QWORD PTR [rbx]
7f0b024734c9: 48 8d 7a 10 lea rdi,[rdx+16]
7f0b024734cd: 8b 5f 08 mov ebx,DWORD PTR [rdi+8]
7f0b024734d0: 89 d8 mov eax,ebx
7f0b024734d2: c1 f8 03 sar eax,0x3
7f0b024734d5: 85 db test ebx,ebx
7f0b024734d7: 0f 8e cb 05 00 00 jle 0x7f0b02473aa8
And what it does is:
rdx = 0x00007f0a808d4ed2 * 8; // equals 0x0003F854046A7690. WTF???
rdx = rdx + something from old gen heap; // results 0x000600007f090486
rdi = rdx + 16; // results 0x000600007f090496
ebx = something from edi address (0x000600007f090496) + 8
Well I've had a look at the address map and there is nothing mapped to 0x000600007f090496 which is why you are getting a SEGV. Are you getting the same error with 1.6.0_26 JVM? Can you try it on a 32bit JVM? Looks like a JVM issue to me. Why would it do the first rdx=0x0... * 8 thing?
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
I ran into the above error when building and running inside Eclipse, where everything seemed to be fine, with the exception of this error. However, I discovered that a Maven build failed and that I needed to include Gson in my pom.xml. After fixing the pom.xml, everything fell into place.
Many of the above, plus TED talks and Shareware Radio. Links here: http://successfulsoftware.net/category/podcasts/
A static library is just an archive of .o
object files. Extract them with ar
(assuming Unix) and pack them back into one big library.
You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.
Aggregate the results from that table into a results cell.
The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.
This is to supplement zerkms's answer.
To pass data across language barriers, you would need a way to represent the data as a string by serializing the data. One of the serialization methods for JavaScript is JSON. In zerkms's example, the code would be placed inside of an aspx page. To combine his example and yours together on one aspx page, you would have,
<%
int[] numbers = new int[5];
// Fill up numbers...
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>
somewhere later on the aspx page
<script type="text/javascript">
var jsVariable = <%= serializer.Serialize(numbers) %>;
</script>
This answer though, assumes that you are generating JavaScript from the initial page load. As per the comments in your post, this could have been done via AJAX. In that case, you would have the server respond with the result of the serialization and then deserialize it in JavaScript using your favorite framework.
Note: Also do not mark this as an answer since I wanted the syntax highlighting to make another answer more clear.
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
double quotes worked in oracle when I had the keyword as one of the column name.
eg:
select t."size" from table t
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
Your have dropped the Project in your workspace, and then trying to import it, that's the problem.
This has two solutions:
1. More your project folder outside your workspace in some other location and then try.
2. Go to File ---> new Project ---> Select the existing project radio button ---> browse to the project folder in your workspace ---> finish
Assume D:\MyDirectory\MyWorkSpace - Path of your WorkSpace
Drop your project which you want to import in Eclipse in MyDirectory folder Not in MyWorkSpace, and try.
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
Try str_detect()
from the stringr package, which detects the presence or absence of a pattern in a string.
Here is an approach that also incorporates the %>%
pipe and filter()
from the dplyr package:
library(stringr)
library(dplyr)
CO2 %>%
filter(str_detect(Treatment, "non"))
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
...
This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect
finds fixed matches or uses a regex - see the documentation for the stringr package.
If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s///
should be all you need:
#!/usr/bin/perl -w
use strict;
main();
sub main{
my $foo = "blahblahblah";
print '$foo: ' , replace("lah","ar",$foo) , "\n"; #$foo: barbarbar
}
sub replace {
my ($from,$to,$string) = @_;
$string =~s/$from/$to/ig; #case-insensitive/global (all occurrences)
return $string;
}
In postgres \d is used to describe the table structure.
e.g. \d schema_name.table_name
this command will provide you the basic info of table such as, columns, type and modifiers.
If you want more info about table use
\d+ schema_name.table_name
this will give you extra info such as, storage, stats target and description
Here are some options for using AJAX to upload files:
AjaxFileUpload - Requires a form element on the page, but uploads the file without reloading the page. See the Demo.
Uploadify - A Flash-based method of uploading files.
Ten Examples of AJAX File Upload - This was posted this year.
UPDATE: Here is a JQuery plug-in for Multiple File Uploading.
Because this is the top result on google on jquery ui and bootstrap.js I decided to add this as community wiki.
I am using:
and somehow when I include bootstrap.js it disables the dropdown of the jquery ui autocomplete.
my three workarounds:
I had a similar task to do, but it contained some aspects that were not sufficiently covered by the other answers here:
I did not try fast-export and hg-fast-export, since they require that you have Python and some Mercurial Python modules on your machine, which I didn't have.
I did try hg-init with TortoiseHG, and this answer gave me a good start. But it looked like it only converts the current branch, not all at once (*). So I read the hg-init docs and this blog post and added
[git]
branch_bookmark_suffix=_bookmark
to my mercurial.ini, and did
hg bookmarks -r default master
hg bookmarks -r my_branch my_branch_bookmark
hg gexport
(Repeat the 2nd line for every branch you want to convert, and repeat it again if you should happen to do another commit before executing the 3rd line). This creates a folder git
within .hg
, which turns out to be a bare Git repo with all the exported branches. I could clone this repo and had a working copy as desired.
Or almost...
Running
git status
on my working copy showed all files with non-ASCII characters in their names as untracked files. So I continued researching and followed this advice:
git rm -rf --cached \*
git add --all
git commit
And finally the repo was ready to be pushed up to Bitbucket :-)
I also tried the Github importer as mentioned in this answer. I used Bitbucket as the source system, and Github did quite a good job, i.e. it converted all branches automatically. However, it showed '?'-characters for all non-ASCII characters in my commit messages (Web-UI and locally) and filenames (Web-UI only), and while I could fix the filenames as described above, I had no idea what to do with the commit messages, and so I'd prefer the hg-init approach. Without the encoding issue the Github importer would have been a perfect and fast solution (as long as you have a paid Github account or can tolerate that your repo is public for as long as it takes to pull it from Github to your local machine).
(*) So it looked like before I discovered that I have to bookmark all the branches I want to export. If you do and push to a bare (!) repo, like the linked answer says, you get all the branches.
Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.
So what you do is register the driver so that the JDBC system can know what to do with the URL:
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Then you form the URL:
String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"
And finally, use it to get a connection:
Connection c = DriverManager.getConnection(url);
In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.
In terms of what properties MySQL supports, see here.
EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.
The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.
However, there are other considerations at play here too.
Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.
Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).
If you refer to classic VxWorks RTOS kernel, they define three mechanisms:
Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.
Download the json jar from here. This will solve your problem.
WHERE username LIKE '%[_]d'; -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
Warning: The following is only suitable for small tables (think < 1000 rows)
Here is a solution that uses entity framework (not SQL) to delete the rows, so it is not SQL Engine(R/DBM) specific.
This assumes that you're doing this for testing or some similar situation. Either
Simply call:
VotingContext.Votes.RemoveRange(VotingContext.Votes);
Assuming this context:
public class VotingContext : DbContext
{
public DbSet<Vote> Votes{get;set;}
public DbSet<Poll> Polls{get;set;}
public DbSet<Voter> Voters{get;set;}
public DbSet<Candidacy> Candidates{get;set;}
}
For tidier code you can declare the following extension method:
public static class EntityExtensions
{
public static void Clear<T>(this DbSet<T> dbSet) where T : class
{
dbSet.RemoveRange(dbSet);
}
}
Then the above becomes:
VotingContext.Votes.Clear();
VotingContext.Voters.Clear();
VotingContext.Candidacy.Clear();
VotingContext.Polls.Clear();
await VotingTestContext.SaveChangesAsync();
I recently used this approach to clean up my test database for each testcase run (it´s obviously faster than recreating the DB from scratch each time, though I didn´t check the form of the delete commands that were generated).
Why can it be slow?
So if you're working with serious amount of data you'll kill the SQL server process (it will consume all the memory) and same thing for the IIS process since EF will cache all the data same way as SQL server. Don't use this one if your table contains serious amount of data.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">
You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools"
and tools:ignore="GoogleAppIndexingWarning"
to the <manifest>
tag.
A simple snnipet:
public static String camelCase(String in) {
if (in == null || in.length() < 1) { return ""; } //validate in
String out = "";
for (String part : in.toLowerCase().split("_")) {
if (part.length() < 1) { //validate length
continue;
}
out += part.substring(0, 1).toUpperCase();
if (part.length() > 1) { //validate length
out += part.substring(1);
}
}
return out;
}
I had the same issue (XCode 11) and nothing worked what was written here.
My issue was that I had iOS Beta (13.3) on my Phone. After reverting that everything worked fine again.
Idea: Maybe the device caches some Information about the provisioning profile too, so a factory reset of the phone might also fix it?
There are no limits to the number of objects you can store in your S3 bucket. AWS claims it to have unlimited storage. However, there are some limitations -
That being said if you really have a lot of objects to be stored in S3 bucket consider randomizing your object name prefix to improve performance.
When your workload is a mix of request types, introduce some randomness to key names by adding a hash string as a prefix to the key name. By introducing randomness to your key names the I/O load will be distributed across multiple index partitions. For example, you can compute an MD5 hash of the character sequence that you plan to assign as the key and add 3 or 4 characters from the hash as a prefix to the key name.
More details - https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-performance-improve/
-- As of June 2018
To be thorough I normally create a pair of functions, one that takes Enum 1 and returns Enum 2 and another that takes Enum 2 and returns Enum 1. Each consists of a case statement mapping inputs to outputs and the default case throws an exception with a message complaining about an unexpected value.
In this particular case you could take advantage of the fact that the integer values of Male and Female are the same, but I'd avoid that as it's hackish and subject to breakage if either enum changes in the future.
Something along the lines of (using JSTL):
<p>Selected Values:
<ul>
<c:forEach items="${paramValues['select2']}" var="selectedValue">
<li><c:out value="${selectedValue}" /></li>
</c:forEach>
</ul>
</p>
Use tolist()
:
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
Quick review,
From x86 assembly tutorial,
The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.
Your num is 1 byte. Try declaring it with DD
so that it becomes 4 bytes and matches with pop
semantics.
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.
Another function that would help you look at missing data would be df_status from funModeling library
library(funModeling)
iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.
df_status(iris.2)
This will give you the number and percentage of NAs in each column.
I found it best to just remove the DOM completely.
$(".form-group #selectId option[value='39']").remove();
Cross browser compatible. Works on IE11 too
When you are creating the router, you can specify the linkExactActiveClass
as a property to set the class that will be used for the active router link.
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes,
linkActiveClass: "active", // active class for non-exact links.
linkExactActiveClass: "active" // active class for *exact* links.
})
This is documented here.
I test examples in js. Simplest solution - just add word u need inside / /:
var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result
Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:
var reg = /\bcat\b/
reg.test('acatb');//1 test
false // result
reg.test('have cat here');//2 test
true // result
We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.
var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5
If we need get all matched words in string/sentence/text, we can use g modifier (global match):
"cat good cat good cat".match(/\bcat\b/g).length
// 3
Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.
"bad dog bad".match(/\bcat|dog\b/g).length
// 1
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
What is new in .NET Framework 4.5 & What's new and expected in .NET Framework 4.5:
differences in ASP.NET in these frameworks
Compare What's New in ASP.NET 4 and Visual Web Developer and What's New in ASP.NET 4.5 and Visual Studio 11 Beta:
Asp.net 4.0
Web.config
File Refactoring And for Asp.net 4.5 there is also a long list of improvements:
HttpRequest
handling differences in C# also in these frameworks
Go Through C# 4.0 - New C# Features in the .NET Framework and What's New for Visual C# in Visual Studio 11 Beta.
Edit:
The languages documentation for C# and VB breaking changes:
VB: Visual Basic Breaking Changes in Visual Studio 2012
C#: Visual C# Breaking Changes in Visual Studio 2012
Hope this help you get what are you looking for..
Is just casting the value returned by time()
#include <stdio.h>
#include <time.h>
int main(void) {
printf("Timestamp: %d\n",(int)time(NULL));
return 0;
}
what you want?
$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167
To get microseconds since the epoch, from C11 on, the portable way is to use
int timespec_get(struct timespec *ts, int base)
Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime
or gettimeofday
(marked obsolete in POSIX.1-2008, which recommends clock_gettime
).
The code for both functions is nearly identical:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
int main(void) {
struct timespec tms;
/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */
/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
int64_t micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;
/* round up if necessary */
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return 0;
}
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
Delay operates on a queue. and as far as i know css manipulation (other than through animate) is not queued.
We use it to initiate asynchronous processing that we don't want to interrupt or conflict with an existing transaction.
For example, say you've got an expensive and very important piece of logic like "buy stuff", an important part of buy stuff would be 'notify stuff store'. We make the notify call asynchronous so that whatever logic/processing that is involved in the notify call doesn't block or contend with resources with the buy business logic. End result, buy completes, user is happy, we get our money and because the queue is guaranteed delivery the store gets notified as soon as it opens or as soon as there's a new item in the queue.
All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.
MVVM is originated from PresentationModel. When we apply MVC, MVVM, and Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.
At the moment, without an third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value. What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical.
For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test, and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to the Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.
You must to download MySQLConnection NET from here.
Then you need add MySql.Data.DLL
to MSVisualStudio like this:
C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
If you want to know more visit: enter link description here
To use in the code you must import the library:
using MySql.Data.MySqlClient;
An example with connectio to Mysql database (NO SSL MODE) by means of Click event:
using System;
using System.Windows;
using MySql.Data.MySqlClient;
namespace Deportes_WPF
{
public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;
public Login()
{
InitializeComponent();
server = "server_name";
database = "database_name";
user = "user_id";
password = "password";
port = "3306";
sslM = "none";
connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
private void conexion()
{
try
{
connection.Open();
MessageBox.Show("successful connection");
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message + connectionString);
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
conexion();
}
}
}
Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.
Generally you'll use Forms
controls, they're simpler. ActiveX
controls allow for more flexible design and should be used when the job just can't be done with a basic Forms
control.
Many user's computers by default won't trust ActiveX
, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX
is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.
Open the command line (Start
-> Run
-> "cmd"
)
Go to the location of your setup.py file and run python setup.py build
Notes:
There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.
Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1
Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.
SELECT DISTINCT city
FROM station
WHERE city RLIKE '^[^aeiouAEIOU]'OR city RLIKE'[^aeiouAEIOU]$'
The Bitmap class is an implementation of the Image class. The Image class is an abstract class;
The Bitmap class contains 12 constructors that construct the Bitmap object from different parameters. It can construct the Bitmap from another bitmap, and the string address of the image.
See more in this comprehensive sample.
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Huffman encoding is a sensible option here. Gzip and friends do this, but the way they work is to build a Huffman tree for the input, send that, then send the data encoded with the tree. If the tree is large relative to the data, there may be no not saving in size.
However, it is possible to avoid sending a tree: instead, you arrange for the sender and receiver to already have one. It can't be built specifically for every string, but you can have a single global tree used to encode all strings. If you build it from the same language as the input strings (English or whatever), you should still get good compression, although not as good as with a custom tree for every input.
If you have more than one dropdown try:
HTML:
<select id="dropdown1" onchange="myFunction(this)">
<option value='...'>Option1
<option value='...'>Option2
</select>
<select id="dropdown2" onchange="myFunction(this)">
<option value='...'>Option1
<option value='...'>Option2
</select>
JavaScript:
function myFunction(sel) {
var selected = sel.value;
}
If you use Visual Studio Code (vscode), using the very popular vscode chrome debug extension (https://github.com/Microsoft/vscode-chrome-debug) you can setup a launch configuration file launch.json
and specify to open the developer tool during a debug session.
This the launch.json
I use for my React projects :
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:3000",
"runtimeArgs": ["--auto-open-devtools-for-tabs"],
"webRoot": "${workspaceRoot}/src"
}
]
}
The important line is "runtimeArgs": ["--auto-open-devtools-for-tabs"],
From vscode you can now type F5
, Chrome opens your app and the console tab as well.
Workaround to pass variable like by reference:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
And yup, actually you can do it without access a global variable:
inc = (function () {
var variableName = 0;
var init = function () {
variableName += 1;
alert(variableName);
}
return init;
})();
inc();
Try adding to td
:
display: -webkit-box; // to make td as block
word-break: break-word; // to make content justify
overflowed tds will align with new row.
Those are automatic properties
Basically another way of writing a property with a backing field.
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.
<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->
Otherwise, you can put !important
at the end of your CSS like this: color:#ffffff!important;
but I would advise against using !important
at all costs.
A previous answer using LPAD()
is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.
UPDATE
mytable
SET
mycolumn = CONCAT(
REPEAT(
"0",
8 - LENGTH(mycolumn)
),
mycolumn
)
WHERE
LENGTH(mycolumn) < 8;
On Ubuntu, for versions of Sublime older than 3.2, what worked for me was changing the dpi scale in Preferences > Settings — User by adding this line:
"dpi_scale": 1.10
For Sublime 3.2, you can use the following line instead:
"ui_scale": 1.10
Adjust the scale value as needed. After this change, you have to restart Sublime Text for it to take effect.
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
I believe VirtualBox is throwing this error for a number of reasons. Very annoying that it's one error for so many things but, I guess it's the same requirement it's just that the root cause is different.
Potential gotchas:
So for my little mess around machine that I'm resurrecting that has 8GB RAM but only a ye-olde Core i3, I'm having success if I install: 32 bit version of linux, allocating 2.5GB RAM.
Oh, and wherever I say "VT-x" above, that obviously applies equally to AMD's "AMD-V" virtualization tech.
I hope that helps.
If the code is coming from a file, you can get its full name
sys._getframe().f_code.co_filename
You can also retrieve the function name as f_code.co_name
I used the following commands to find and retrieve my deleted branch. The first steps are from gcb's description.
$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\ -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline
Now look for the git commit id (GIT-SHA) based on the commit comments and use it in the command below. Checkout a new branch called NEW-BRANCH with the previously found GIT-SHA:
$ git checkout -b NEW-BRANCH GIT-SHA
For integer types, you can do
a ^= b;
b ^= a;
a ^= b;
using the bit-wise xor operator ^
. As all the other suggestions, you probably shouldn't use it in production code.
For a reason I don't know, the single line version a ^= b ^= a ^= b
doesn't work (maybe my Java compiler has a bug). The single line worked in C with all compilers I tried. However, two-line versions work:
a ^= b ^= a;
b ^= a;
as well as
b ^= a;
a ^= b ^= a;
A proof that it works: Let a0 and b0 be the initial values for a
and b
. After the first line, a
is a1 = a0 xor b0; after the second line, b
is b1 = b0 xor a1 = b0 xor (a0 xor b0) = a0. After the third line, a
is a2 = a1 xor b1 = a1 xor (b0 xor a1) = b0.
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns : is xml name space and the URL : "http://schemas.android.com/apk/res/android" is nothing but
XSD which is [XML schema definition] : which is used define rules for XML file .
Example :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:hint="User Name"
/>
</LinearLayout>
Let me explain What Kind of Rules ? .
Such Kind of Rules are define in XML XSD : "http://schemas.android.com/apk/res/android"
little bit late but I hope this helps you .
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
If you want to pass the form to the controller for validation purposes you can simply pass it as an argument to the method handling the submission. Use the form name, so for the original question it would be something like:
<button ng-click="submit(customerForm)">Save</button>
Put it inside your <footer>
by all means, but the most fitting element is the small element.
The HTML5 spec for this says:
Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
It is impossible, and unnecessary, to know the motivation for using "
in element content, but possible motives include: misunderstanding of HTML rules; use of software that generates such code (probably because its author thought it was “safer”); and misunderstanding of the meaning of "
: many people seem to think it produces “smart quotes” (they apparently never looked at the actual results).
Anyway, there is never any need to use "
in element content in HTML (XHTML or any other HTML version). There is nothing in any HTML specification that would assign any special meaning to the plain character " there.
As the question says, it has its role in attribute values, but even in them, it is mostly simpler to just use single quotes as delimiters if the value contains a double quote, e.g. alt='Greeting: "Hello, World!"'
or, if you are allowed to correct errors in natural language texts, to use proper quotation marks, e.g. alt="Greeting: “Hello, World!”"
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object
Once you set your Global Jenkins credentials, you can apply this step:
stage('Update GIT') {
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
withCredentials([usernamePassword(credentialsId: 'example-secure', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
def encodedPassword = URLEncoder.encode("$GIT_PASSWORD",'UTF-8')
sh "git config user.email [email protected]"
sh "git config user.name example"
sh "git add ."
sh "git commit -m 'Triggered Build: ${env.BUILD_NUMBER}'"
sh "git push https://${GIT_USERNAME}:${encodedPassword}@github.com/${GIT_USERNAME}/example.git"
}
}
}
}
}
This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);
server.get('/usersList', (req, res) =>
User.find({}, (err, users) =>
res.send(users.reduce((userMap, item) => {
userMap[item.id] = item
return userMap
}, {}));
);
);
cheers!
Problem - I was not able to connect to DB through sql developer.
Solution - First thing to note is that SQL Developer is only UI to access to your database. I need to connect remote database not the localhost so I need not to install the oracle 8i/9i. Only I need is oracle client to install. After installation it got the path in environment variable like C:\oracle\product\10.2.0\client_1\bin. Still I was not able to connect the db.
Things to be checked.
If all points are ok for you then check from where you are running sql developer .exe file. I pasted sql developer folder to C:\oracle folder and run the .exe file from here and I am able to connect the database. and my problem of 'IO Error: The Network Adapter could not establish the connection' got resolved. Hurrey... :) :)
I was getting the same error when trying through windows authentication. Sounds ludicrous but just in case it helps someone else: it was because my domain account got locked somehow while I was still logged in (!). Unlocking the account fixed it.
If you are entering several lines of text at once, I find this to be the most readable format.
file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")
The \ at the end of each line escapes the new line (which would cause an error).
It can be useful to prevent the distracted user to make an involuntary bad choice, but in any case, you have to do the check on the server side anyway.
The best way is to be clear in the upload page. After that, if the user stupidly upload a big file with the wrong type, that's their loss of time, no?
To run the project to latest devices from the older versions of Xcode, follow the following steps :
Go To Finder -> Applications -> Right Click on latest Xcode version -> select show package content -> Developer -> Platforms -> iPhoneOS.platform -> DeviceSupport -> Copy the latest version folder and paste at the same location of your old Xcode i.e in the DeviceSupport folder of your old Xcode.
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
In addition to setting the registry entry for AuthServerWhitelist you should also set AuthSchemes: "ntlm,negotiate" (or just "ntlm" as appropriate for your situation). Using the above templates the policy for that will be "Supported authentication schemes"
GCC compilers always try to compile your program if this is at all possible. However, in some
cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers
such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example,
the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter
-pedantic-errors
option converts such diagnostic warnings into errors that will cause compilation
to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming
compiler will generate warnings or errors.
You can't access outside private fields of a class. private fields are starting with __ . for example -
class car:
def __init__(self):
self.__updatesoftware()
def drive(self):
print("driving")
def __updatesoftware(self):
print("updating software:")
obj = car()
obj.drive()
obj.__updatesoftware() ## here it will throw an error because
__updatesoftware is an private method.
While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.
A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.
git checkout --orphan BRANCHNAME
This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.
Now for whatever reason, git needs a bit of cleanup after an orphan checkout.
rm .git/index
rm -r *
Make sure everything is committed before deleting
Once the orphan branch is clean, you can use it normally.
Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.
# repo 1
git push origin master:master-1
# repo 2
git push origin master:master-2
The element is supported by all browsers and defines an embedded object within an HTML document.
Bottom line: OBJECT is Good, EMBED is Old. Beside's IE's PARAM tags, any content between OBJECT tags will get rendered if the browser doesn't support OBJECT's referred plugin, and apparently, the content gets http requested regardless if it gets rendered or not. Reference
Working code: https://www.w3schools.com/code/tryit.asp?filename=G7L8BK6XC0A6
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<object width="400px" height="400px" data="https://s3.amazonaws.com/dq-blog-files/pandas-cheat-sheet.pdf"></object>_x000D_
</body>_x000D_
</html>
_x000D_
Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...
Here is an example where a TextView is displayed on top of an ImageView:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
</FrameLayout>
This answer should work for Windows users that have had trouble getting this working with Visual Studio with any of the other answers.
Download the dirent.h file from the github page. But is better to just use the Raw dirent.h file and follow my steps below (it is how I got it to work).
Github page for dirent.h for Windows: Github page for dirent.h
Raw Dirent File: Raw dirent.h File
Go to your project and Add a new Item (Ctrl+Shift+A). Add a header file (.h) and name it dirent.h.
Paste the Raw dirent.h File code into your header.
Include "dirent.h" in your code.
Put the below void filefinder()
method in your code and call it from your main
function or edit the function how you want to use it.
#include <stdio.h>
#include <string.h>
#include "dirent.h"
string path = "C:/folder"; //Put a valid path here for folder
void filefinder()
{
DIR *directory = opendir(path.c_str());
struct dirent *direntStruct;
if (directory != NULL) {
while (direntStruct = readdir(directory)) {
printf("File Name: %s\n", direntStruct->d_name); //If you are using <stdio.h>
//std::cout << direntStruct->d_name << std::endl; //If you are using <iostream>
}
}
closedir(directory);
}
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.
preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);
I was having a similar issue with formatting CardViews in a recylerView.
I got this simple solution working, not sure if it's the best solution, but it worked for me.
mv_cardView.getBackground().setTint(Color.BLUE)
It gets the background Drawable of the cardView and tints it.
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
SELECT T.TABLE_NAME, C.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
AND COLUMN_NAME = 'ColName'
This returns tables only and ignores views for anyone who is interested!
For me the solution was besides using "Ntlm" as credential type:
XxxSoapClient xxxClient = new XxxSoapClient();
ApplyCredentials(userName, password, xxxClient.ClientCredentials);
private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
{
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
clientCredentials.Windows.ClientCredential.UserName = userName;
clientCredentials.Windows.ClientCredential.Password = password;
clientCredentials.Windows.AllowNtlm = true;
clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
}
check this.. Brief:Pick each element of array and compare it with all elements of the array, weather it is equal to the picked on or not.
int popularity1 = 0;
int popularity2 = 0;
int popularity_item, array_item; //Array contains integer value. Make it String if array contains string value.
for(int i =0;i<array.length;i++){
array_item = array[i];
for(int j =0;j<array.length;j++){
if(array_item == array[j])
popularity1 ++;
{
if(popularity1 >= popularity2){
popularity_item = array_item;
popularity2 = popularity1;
}
popularity1 = 0;
}
//"popularity_item" contains the most repeted item in an array.
Htmlparser2 by FB55 seems to be a good alternative.
Use stat
to get the creation time. You can compare the time in the format YYYY-MM-DD HH:MM:SS
lexicographically.
This work on Linux with modification time, creation time is not supported. On AIX, the -c
option might not be supported, but you should be able to get the information anyway, using grep
if nothing else works.
#! /bin/bash
from='2013-08-01 00:00:00.0000000000' # 01-Aug-13
to='2013-08-31 23:59:59.9999999999' # 31-Aug-13
for file in * ; do
modified=$( stat -c%y "$file" )
if [[ $from < $modified && $modified < $to ]] ; then
echo "$file"
fi
done
Simpler version of yfeldblum's answer, that is simpler and works well also with large files:
require 'csv'
CSV.foreach(filename, headers: true) do |row|
Moulding.create!(row.to_hash)
end
No need for with_indifferent_access
or symbolize_keys
, and no need to read in the file to a string first.
It doesnt't keep the whole file in memory at once, but reads in line by line and creates a Moulding per line.
Despite some other answers: YES it IS possible:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
translates to the following one liner:
statement1 if expression1 else (statement2 if expression2 else statement3)
in fact you can nest those till infinity. Enjoy ;)
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
It would appear as though this event has some clipboardData
property attached to it (it may be nested within the originalEvent
property). The clipboardData
contains an array of items and each one of those items has a getAsString()
function that you can call. This returns the string representation of what is in the item.
Those items also have a getAsFile()
function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry()
function).
For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:
$(element).bind("paste", function (e) {
e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
debugger;
// pStringRepresentation now contains the string representation of what was pasted.
// This does not include HTML or any markup. Essentially jQuery's $(element).text()
// function result.
});
});
You'll want to perform an iteration through the items, keeping a string concatenation result.
The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.
It works for me after getting rid of "::1" in /etc/hosts.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
Install the Python extension (Python should be installed in your system). To install the Python Extension, press Ctrl + Shift + X and then type 'python' and enter. Install the extension.
Open the file containing Python code. Yes! A .py file.
Now to run the .py code, simply right click on the editor screen and hit 'Run Python File in the Terminal'. That's it!
Now this is the additional step. Actually I got irritated by clicking again and again, so I set up the keyboard shortcut.
If you use the Eclipse IDE with the SVN plugin you can do as follows:
This will revert the files to the revision that you want. Just keep in mind that SVN will see the changes as a new commit. That is, the change gets a new revision number, and there is no link between the old revision and the new one. You should specify in the commit comments that you are reverting those files to a specific revision.
Just had this problem.
I fixed it by navigating to:
Tools -> Options -> Debugging -> Symbols
Then unchecking all non-local sources for Symbol file (.pdb) locations
e.g. Microsoft Symbol Servers and msdl.microsoft.com/download/symbols
install pip install pypiwin32
from win32com.client import Dispatch
speak = Dispatch("SAPI.SpVoice").Speak
speak("Ciao")
After you installed the gtts module in cmd: pip install gtts
from gtts import gTTS
import os
tts = gTTS(text="This is the pc speaking", lang='en')
tts.save("pcvoice.mp3")
# to start the file from python
os.system("start pcvoice.mp3")
sleep(3)
is in unistd.h
, not stdlib.h
. Type man 3 sleep
on your command line to confirm for your machine, but I presume you're on a Mac since you're learning Objective-C, and on a Mac, you need unistd.h
.
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
Quick answer: No, at least not with native SMS service.
Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.
Here is a simple solution
try adding this dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).
Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184
When you're exporting to HTML, using <br>
works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:
+---------------+---------------+--------------------+
| Fruit | Price | Advantages |
+===============+===============+====================+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!
<script>
var marks = 0;
function getRandomNumbers(){ // generate a random number between 1 & 10
var number = Math.floor((Math.random() * 10) + 1);
return number;
}
function getNew(){
/*
This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;
document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"
}
function checkAns(){
/*
After entering the answer, the entered answer will be compared with the correct answer.
If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
The updated total marks should be always displayed at the total marks box.
*/
var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);
if(answer==(num1+num2)){
marks = marks + 10;
document.getElementById("resultBox").innerHTML = "Correct";
document.getElementById("resultBox").style.backgroundColor = "green";
document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
}
else{
marks = marks - 3;
document.getElementById("resultBox").innerHTML = "Wrong";
document.getElementById("resultBox").style.backgroundColor = "red";
document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}
}
</script>
</head>
<body onLoad="getNew()">
<div class="container">
<h1>Let's add numbers</h1>
<div class="sum">
<input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
</div>
<h2>Enter the answer below and click 'Check'</h2>
<div class="answer">
<input id="ans" type="text" value="">
</div>
<input id="btnchk" onClick="checkAns()" type="button" value="Check" >
<div id="resultBox">***</div>
<input id="btnnew" onClick="getNew()" type="button" value="New">
<div id="totalMarks">Total marks : 0</div>
</div>
</body>
</html>
If you are using windows, just search for miniconda and you'll find the folder. Go into the folder and you'll find a miniconda uninstall exe file. Run it.
It may be asking too much of MySQL to expect it to produce well formed json directly from a query. Instead, consider producing something more convenient, like CSV (using the INTO OUTFILE '/path/to/output.csv' FIELDS TERMINATED BY ','
snippet you already know) and then transforming the results into json in a language with built in support for it, like python or php.
Edit python example, using the fine SQLAlchemy:
class Student(object):
'''The model, a plain, ol python class'''
def __init__(self, name, email, enrolled):
self.name = name
self.email = email
self.enrolled = enrolled
def __repr__(self):
return "<Student(%r, %r)>" % (self.name, self.email)
def make_dict(self):
return {'name': self.name, 'email': self.email}
import sqlalchemy
metadata = sqlalchemy.MetaData()
students_table = sqlalchemy.Table('students', metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('name', sqlalchemy.String(100)),
sqlalchemy.Column('email', sqlalchemy.String(100)),
sqlalchemy.Column('enrolled', sqlalchemy.Date)
)
# connect the database. substitute the needed values.
engine = sqlalchemy.create_engine('mysql://user:pass@host/database')
# if needed, create the table:
metadata.create_all(engine)
# map the model to the table
import sqlalchemy.orm
sqlalchemy.orm.mapper(Student, students_table)
# now you can issue queries against the database using the mapping:
non_students = engine.query(Student).filter_by(enrolled=None)
# and lets make some json out of it:
import json
non_students_dicts = ( student.make_dict() for student in non_students)
students_json = json.dumps(non_students_dicts)
With Vim on Windows, use Ctrl + Q in place of Ctrl + V.
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.
Use below one,
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
Here you go
col-lg-2 : if the screen is large (lg) then this component will take space of 2 elements considering entire row can fit 12 elements ( so you will see that on large screen this component takes 16% space of a row)
col-lg-6 : if the screen is large (lg) then this component will take space of 6 elements considering entire row can fit 12 elements -- when applied you will see that the component has taken half the available space in the row.
Above rule is only applied when the screen is large. when the screen is small this rule is discarded and only one component per row is shown.
Below image shows various screen size widths :
An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.
@JsonFormat.Shape.STRING
public Enum OrderType {...}
uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”
@JsonFormat.Shape.NUMBER
Public Enum OrderTYpe{...}
uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1
@JsonFormat.Shape.OBJECT
Public Enum OrderType{...}
treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}
JsonFormat.Shape.OBJECT is what you need in your case.
A little more complicated way is your solution, specifying a serializer for the Enum.
Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html
the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.
if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.
What helped me get over that error - cb() never called...
is downgrading my NPM version.
I had version 6.14.9, and I downgraded to version 6.14.6 by typing:
npm install -g [email protected]
note: nothing seemed to help. I tried many of the suggested solutions, including "npm cache clean" or uninstalling NPM and reinstalling.
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
In reference to the error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified.
That error means that the Data Source Name (DSN) you are specifying in your connection configuration is not being found in the windows registry.
It is important that your ODBC driver's executable and linking format (ELF) is the same as your application. In other words, you need a 32-bit driver for a 32-bit application or a 64-bit driver for a 64-bit application.
If these do not match, it is possible to configure a DSN for a 32-bit driver and when you attempt to use that DSN in a 64-bit application, the DSN won't be found because the registry holds DSN information in different places depending on ELF (32-bit versus 64-bit).
Be sure you are using the correct ODBC Administrator tool. On 32-bit and 64-bit Windows, the default ODBC Administrator tool is in c:\Windows\System32\odbcad32.exe
. However, on a 64-bit Windows machine, the default is the 64-bit version. If you need to use the 32-bit ODBC Administrator tool on a 64-bit Windows system, you will need to run the one found here: C:\Windows\SysWOW64\odbcad32.exe
Where I see this tripping people up is when a user uses the default 64-bit ODBC Administrator to configure a DSN; thinking it is for a 32-bit DSN. Then when the 32-bit application attempts to connect using that DSN, "Data source not found..." occurs.
It's also important to make sure the spelling of the DSN matches that of the configured DSN in the ODBC Administrator. One letter wrong is all it takes for a DSN to be mismatched.
Here is an article that may provide some additional details
It may not be the same product brand that you have, however; it is a generic problem that is encountered when using ODBC data source names.
In reference to the OLE DB Provider portion of your question, it appears to be a similar type of problem where the application is not able to locate the configuration for the specified provider.
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.
The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).
The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.
The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.
Below is a minimal code to achieve the effect.
This also works responsively since the border-radius
is in percentage.
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample
<form id="formAddName">
<fieldset>
<legend>Add Name </legend>
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" />
<button>Add</button>
</fieldset>
</form>
<ol id="demo"></ol>
<script>
var list = document.getElementById('demo');
var entry = document.getElementById('formAddName');
entry.onsubmit = function(evt) {
evt.preventDefault();
var firstName = document.getElementById('firstName').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
}
</script>
Use the HTML
<div id="full-size">
<div id="wrapper">
Your content goes here.
</div>
</div>
and use the CSS:
html, body {margin:0;padding:0;height:100%;}
#full-size {
height:100%;
width:100%;
position:absolute;
top:0;
left:0;
overflow:hidden;
}
#wrapper {
/*You can add padding and margins here.*/
padding:0;
margin:0;
}
Make sure that the HTML is in the root element.
Hope this helps!
If you have the misfortune of needing to do this from a Windows batch file, here is the incantation you are looking for:
set REV=unknown
for /f "usebackq tokens=1,2 delims=: " %%A in (`svn info`) do if "%%A" == "Revision" set REV=%%B
echo Current SVN revision is %REV%
This runs "svn info", iterating through each line of generated output. It uses a colon as a delimiter between the first and second token on the line. When the first token is "Revision" it sets the environment variable REV to the second token.
install react-router-dom
then create two components one for valid users and other for invalid users.
try this on app.js
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';
import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;
class App extends React.Component {
render() {
return (
<Router>
<div>
<Route exact path="/" render={() =>(
loggedin ? ( <Route component={ValidUser} />)
: (<Route component={InValidUser} />)
)} />
</div>
</Router>
)
}
}
export default App;
I feel like this has been well covered, maybe except for the following:
Simple KEY
/ INDEX
(or otherwise called SECONDARY INDEX
) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.
Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.
If you feel like your data should be UNIQUE
, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.
You can only use FULLTEXT
(or otherwise called SEARCH INDEX
) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines
You can only use FULLTEXT
on CHAR
, VARCHAR
and TEXT
column types
FULLTEXT
index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html
To be more precise the shebang #!
, when it is the first two bytes of an executable (x
mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve
don't mention the shebang.
It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).
A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python
) in the user's $PATH
is to use the env
program (always at /usr/bin/env
on all Linux) like e.g.
#!/usr/bin/env python
Any ELF executable can be an interpreter. You could even use #!/bin/cat
or #!/bin/true
if you wanted to! (but that would be often useless)
select convert(varchar(8), getdate(), 3)
simply use this for dd/mm/yy and this
select convert(varchar(8), getdate(), 1)
for mm/dd/yy
I encountered the same problem and solved it by
git checkout -f branch
Well, be careful with the -f
switch. You will lose any uncommitted changes if you use the -f
switch. While there may be some use cases where it is helpful to use -f
, in most cases, you may want to stash
your changes and then switch
branches. The stashing
procedure is explained above.
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
As I see it, there are three ways to go with this,
1) The easy way.
double rand_easy(void)
{ return (double) rand() / (RAND_MAX + 1.0);
}
2) The safe way (standard conforming).
double rand_safe(void)
{
double limit = pow(2.0, DBL_MANT_DIG);
double denom = RAND_MAX + 1.0;
double denom_to_k = 1.0;
double numer = 0.0;
for ( ; denom_to_k < limit; denom_to_k *= denom )
numer += rand() * denom_to_k;
double result = numer / denom_to_k;
if (result == 1.0)
result -= DBL_EPSILON/2;
assert(result != 1.0);
return result;
}
3) The custom way.
By eliminating rand()
we no longer have to worry about the idiosyncrasies of any particular version, which gives us more leeway in our own implementation.
Note: Period of the generator used here is ≅ 1.8e+19.
#define RANDMAX (-1ULL)
uint64_t custom_lcg(uint_fast64_t* next)
{ return *next = *next * 2862933555777941757ULL + 3037000493ULL;
}
uint_fast64_t internal_next;
void seed_fast(uint64_t seed)
{ internal_next = seed;
}
double rand_fast(void)
{
#define SHR_BIT (64 - (DBL_MANT_DIG-1))
union {
double f; uint64_t i;
} u;
u.f = 1.0;
u.i = u.i | (custom_lcg(&internal_next) >> SHR_BIT);
return u.f - 1.0;
}
Whatever the choice, functionality may be extended as follows,
double rand_dist(double min, double max)
{ return rand_fast() * (max - min) + min;
}
double rand_open(void)
{ return rand_dist(DBL_EPSILON, 1.0);
}
double rand_closed(void)
{ return rand_dist(0.0, 1.0 + DBL_EPSILON);
}
Final notes: The fast version - while written in C - may be adapted for use in C++ to be used as a replacement for std::generate_canonical
, and will work for any generator emitting values with sufficient significant bits.
Most 64 bit generators take advantage of their full width, so this can likely be used without modification (shift adjustment). e.g. this works as-is with the std::mt19937_64
engine.
If your script always requires an Administrator's privileges then:
runas /user:Administrator "python your_script.py"
Here is probably the simplest way to go about it (with a reproducible example):
library(plyr)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))
ddply(df, .(ID), summarize, Obs_1_mean=mean(Obs_1), Obs_1_std_dev=sd(Obs_1),
Obs_2_mean=mean(Obs_2), Obs_2_std_dev=sd(Obs_2))
ID Obs_1_mean Obs_1_std_dev Obs_2_mean Obs_2_std_dev
1 1 -0.13994642 0.8258445 -0.15186380 0.4251405
2 2 1.49982393 0.2282299 0.50816036 0.5812907
3 3 -0.09269806 0.6115075 -0.01943867 1.3348792
EDIT: The following approach saves you a lot of typing when dealing with many columns.
ddply(df, .(ID), colwise(mean))
ID Obs_1 Obs_2 Obs_3
1 1 -0.3748831 0.1787371 1.0749142
2 2 -1.0363973 0.0157575 -0.8826969
3 3 1.0721708 -1.1339571 -0.5983944
ddply(df, .(ID), colwise(sd))
ID Obs_1 Obs_2 Obs_3
1 1 0.8732498 0.4853133 0.5945867
2 2 0.2978193 1.0451626 0.5235572
3 3 0.4796820 0.7563216 1.4404602
Use this at your own risk. (I have tested it on XP and Server 2008 x64 R2)
For this hack you will need SysinternalsSuite by Mark Russinovich:
Step one: Open an elevated cmd.exe prompt (Run as administrator)
Step two:
Elevate again to root using PSExec.exe:
Navigate to the folder containing SysinternalsSuite and execute the following command
psexec -i -s cmd.exe
you are now inside of a prompt that is nt authority\system
and you can prove this by typing whoami
. The -i
is needed because drive mappings need to interact with the user
Step Three:
Create the persistent mapped drive as the SYSTEM account with the following command
net use z: \\servername\sharedfolder /persistent:yes
It's that easy!
WARNING: You can only remove this mapping the same way you created it, from the SYSTEM account. If you need to remove it, follow steps 1 and 2 but change the command on step 3 to net use z: /delete
.
NOTE: The newly created mapped drive will now appear for ALL users of this system but they will see it displayed as "Disconnected Network Drive (Z:)". Do not let the name fool you. It may claim to be disconnected but it will work for everyone. That's how you can tell this hack is not supported by M$.
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
The Router Guide has more details on programmatic navigation.
If I remember correctly, I set the DataSource property to null to clear the DataGridView:
datagridview.DataSource = null;
Adding to Blundell's answer,
If you have more fragments, with plenty of onClicks:
Activity:
Fragment someFragment1 = (Fragment)getFragmentManager().findFragmentByTag("someFragment1 ");
Fragment someFragment2 = (Fragment)getFragmentManager().findFragmentByTag("someFragment2 ");
Fragment someFragment3 = (Fragment)getFragmentManager().findFragmentByTag("someFragment3 ");
...onCreate etc instantiating your fragments
public void myClickMethod(View v){
if (someFragment1.isVisible()) {
someFragment1.myClickMethod(v);
}else if(someFragment2.isVisible()){
someFragment2.myClickMethod(v);
}else if(someFragment3.isVisible()){
someFragment3.myClickMethod(v);
}
}
In Your Fragment:
public void myClickMethod(View v){
switch(v.getid()){
// Just like you were doing
}
}
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
if the map is short you can do:
ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs
If it is longer then:
ImmutableMap.builder()
.put(key, value)
.put(key2, value2)
// ...
.build();
You can use the TelephonyManager
to do this:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tm.getLine1Number();
The documentation for getLine1Number()
says this method will return null
if the number is "unavailable", but it does not say when the number might be unavailable.
You'll need to give your application permission to make this query by adding the following to your Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
(You shouldn't use TelephonyManager.getDefault()
to get the TelephonyManager
as that is a private undocumented API call and may change in future.)
Check for syntax errors in the php.ini file, specially before the Date paramaters, that prevent the file from being parsed correctly.
Try recreate()
it will cause this Activity to be recreated.
Well, I have read this post and seems it is not good enough to fix this issue.
Spring based application on the tomcat 8 will not work.
Here is the solution
Step 1 ? Add the following dependency in your pom.xml
<!-- JSTL Support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Step 2 ? Add All following two statement in your JSP page, ensure that you are using isELIgnored="false" attribute in <%@ page %> tag
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" isELIgnored="false" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Step 3 ? Remove all the other configuration that you have done till now in web.xml or anywhere else :)
Step 4 ? Clean the Tomcat and restart Tomcat.
Side Note ? Actually, JSTL will work with only 3.x Servlet specifications on Tomcat 8.
[http://www.kriblog.com/j2ee/jsp/jstl-with-spring-4-on-tomcat-8.html]
There is a library called NineOldAndroids, which allows you to use the Honeycomb animation library all the way down to version one.
This means you can define left, right, translationX/Y with a slightly different interface.
Here is how it works:
ViewHelper.setTranslationX(view, 50f);
You just use the static methods from the ViewHelper class, pass the view and which ever value you want to set it to.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
This VBA code will refresh all pivot tables/charts in the workbook.
Sub RefreshAllPivotTables()
Dim PT As PivotTable
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
For Each PT In WS.PivotTables
PT.RefreshTable
Next PT
Next WS
End Sub
Another non-programatic option is:
This will refresh the pivot table each time the workbook is opened.
cv2
uses numpy
for manipulating images, so the proper and best way to get the size of an image is using numpy.shape
. Assuming you are working with BGR images, here is an example:
>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
600 800 3
In case you were working with binary images, img
will have two dimensions, and therefore you must change the code to: height, width = img.shape
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
for(var i=0; i<5; i++) {_x000D_
var sno = i+1;_x000D_
(function myLoop (i) { _x000D_
setTimeout(function () { _x000D_
alert(i); // Do your function here _x000D_
}, 1000*i);_x000D_
})(sno);_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I got this issue after copying mytable.idb table file from another location. To fix this problem I did the following:
ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;
Copy mytable.idb
ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;
Restart MySql
i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.
I am adding necessary explanation to this scenario
You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager.
But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.
In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot.
Important codes
// obtain the process id of the winlogon process that
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
if ((uint)p.SessionId == dwSessionId)
{
winlogonPid = (uint)p.Id;
}
}
// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
CloseHandle(hProcess);
return false;
}
// Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
// copy the access token of the winlogon process;
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
{
CloseHandle(hProcess);
CloseHandle(hPToken);
return false;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = (int)Marshal.SizeOf(si);
// interactive window station parameter; basically this indicates
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";
// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
// create a new process in the current User's logon session
bool result = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
applicationName, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
dwCreationFlags, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out procInfo // receives information about new process
);
You can use this code:
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
AlertDialogActivity.this);
// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog2.setMessage("Are you sure you want delete this file?");
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);
// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on YES", Toast.LENGTH_SHORT)
.show();
}
});
// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on NO", Toast.LENGTH_SHORT)
.show();
dialog.cancel();
}
});
// Showing Alert Dialog
alertDialog2.show();
EDIT:
Those three different elements all have different rendering rules.
So for:
table#bar
you need to set the width to 100% otherwise it will be only be as wide as it determines it needs to be. However, if the table rows total width is greater than the width of bar
it will expand to its needed width. IF i recall you can counteract this by setting display: block !important;
though its been awhile since ive had to fix that. (im sure someone will correct me if im wrong).
textarea#bar
i beleive is a block level element so it will follow the rules the same as the div. The only caveat here is that textarea
take an attributes of cols
and rows
which are measured in character columns. If this is specified on the element it will override the width specified by the css.
input#bar
is an inline element, so by default you cant assign it width. However the similar to textarea
's cols
attribute, it has a size
attribute on the element that can determine width. That said, you can always specifiy a width by using display: block;
in your css for it. Then it will follow the same rendering rules as the div.
td#foo
will be rendered as a table-cell
which has some craziness to it. Bottom line here is that for your purposes its going to act just like div#foo
as far as restricting the width of its contents. The only issue here is going to be potential unwrappable text in the column somewhere which would make it ignore your width setting. Also all cells in the column are going to get the width of the widest cell.
Thats the default behavior of block level element - ie. if width is auto
(the default) then it will be 100% of the inner width of the containing element. so in essence:
#foo {width: 800px;}
#bar {padding-left: 2px; padding-right: 2px; margin-left: 2px; margin-right: 2px;}
will give you exactly what you want.
In simple words:
innerText
will show the value as is and ignores any HTML
formatting which may
be included.innerHTML
will show the value and apply any HTML
formatting.I made it a bit different (with tess-two). Maybe it will be useful for somebody.
So you need to initialize first the API.
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(datapath, language, ocrEngineMode);
Then set the following variables
baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!?@#$%&*()<>_-+=/:;'\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, ".,0123456789");
baseApi.setVariable("classify_bln_numeric_mode", "1");
In this way the engine will check only the numbers.
What exactly are you doing in //do stuff
?
You may be able to do something like:
(scrollLeft < 1000) ? //do stuff
: (scrollLeft > 1000 && scrollLeft < 2000) ? //do stuff
: (scrollLeft > 2000) ? //do stuff
: //etc.
If you are using ASP.NET MVC Core 3 or newer, IHostingEnvironment
has been deprecated and replaced with IWebHostEnvironment
public Startup(IWebHostEnvironment webHostEnvironment)
{
var webRootPath = webHostEnvironment.WebRootPath;
}
I did it many times. To bypass the JavaScript warning, I add two parens:
if ((result = get_something())) { }
You should avoid it, if you really want to use it, write a comment above it saying what you are doing.
Provided that the remote repository is origin, and that you're interested in master:
git fetch origin
git reset --hard origin/master
This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.
All your local commits not common to the remote will be gone.
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
Use map
with operator.add
:
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
or zip
with a list comprehension:
>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]
>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop
"
is on the official list of valid HTML 4 entities, but '
is not.
From C.16. The Named Character Reference ':
The named character reference
'
(the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use'
instead of'
to work as expected in HTML 4 user agents.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Replace every col-md-
with col-xs-
eg: replace every col-md-6
to col-xs-6
.
This is the thing that worked for me to get me rid of this problem you can see what you have to replace.
Use detectOS.js:
var Detect = {
init: function () {
this.OS = this.searchString(this.dataOS);
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
dataOS : [
{
string: navigator.platform,
subString: 'Win',
identity: 'Windows'
},
{
string: navigator.platform,
subString: 'Mac',
identity: 'macOS'
},
{
string: navigator.userAgent,
subString: 'iPhone',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPad',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPod',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'Android',
identity: 'Android'
},
{
string: navigator.platform,
subString: 'Linux',
identity: 'Linux'
}
]
};
Detect.init();
console.log("We know your OS – it's " + Detect.OS + ". We know everything about you.");
Sharding is just another name for "horizontal partitioning" of a database. You might want to search for that term to get it clearer.
From Wikipedia:
Horizontal partitioning is a design principle whereby rows of a database table are held separately, rather than splitting by columns (as for normalization). Each partition forms part of a shard, which may in turn be located on a separate database server or physical location. The advantage is the number of rows in each table is reduced (this reduces index size, thus improves search performance). If the sharding is based on some real-world aspect of the data (e.g. European customers vs. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard.
Some more information about sharding:
Firstly, each database server is identical, having the same table structure. Secondly, the data records are logically split up in a sharded database. Unlike the partitioned database, each complete data record exists in only one shard (unless there's mirroring for backup/redundancy) with all CRUD operations performed just in that database. You may not like the terminology used, but this does represent a different way of organizing a logical database into smaller parts.
Update: You wont break MVC. The work of determining the correct shard where to store the data would be transparently done by your data access layer. There you would have to determine the correct shard based on the criteria which you used to shard your database. (As you have to manually shard the database into some different shards based on some concrete aspects of your application.) Then you have to take care when loading and storing the data from/into the database to use the correct shard.
Maybe this example with Java code makes it somewhat clearer (it's about the Hibernate Shards project), how this would work in a real world scenario.
To address the "why sharding
": It's mainly only for very large scale applications, with lots of data. First, it helps minimizing response times for database queries. Second, you can use more cheaper, "lower-end" machines to host your data on, instead of one big server, which might not suffice anymore.
Vibur DBCP is another library for that purpose. Several examples showing how to configure it for use with Hibernate, Spring+Hibernate, or programatically, can be found on its website: http://www.vibur.org/
Also, see the disclaimer here.
So here is an other way:
background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");
The FOR loop worked well, I modified it a tiny bit:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int number;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout << "Enter number: \n";
cin >> number;
sum=sum+number;
}
cout<<"sum is: "<< sum<<endl;
}
HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
You could just use: {in and out function callback}
$(".result").hover(function () {
$(this).toggleClass("result_hover");
});
For your example, better will be to use CSS pseudo class :hover
: {no js/jquery needed}
.result {
height: 72px;
width: 100%;
border: 1px solid #000;
}
.result:hover {
background-color: #000;
}
I'd like to recommend var_export($array)
- it doesn't show types, but it generates syntax you can use in your code :)
I came up with this one, that supports anchor and image tags, and supports single and double quotes.
<[a|img]+\\s+(?:[^>]*?\\s+)?[src|href]+=[\"']([^\"']*)['\"]
So
<a href="/something.ext">click here</a>
Will match:
Match 1: /something.ext
And
<a href='/something.ext'>click here</a>
Will match:
Match 1: /something.ext
Same goes for img src attributes
After you run MySQL Shell and you have seen following:
mysql-js>
Firstly, you should:
mysql-js>\sql
Secondly:
mysql-sql>\connect username@servername (root@localhost)
And finally:
Enter password:*********
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
If your file has a return statement like this:
<?php return array(
'AF' => 'Afeganistão',
'ZA' => 'África do Sul',
...
'ZW' => 'Zimbabué'
);
You can get this to a variable like this:
$data = include $filePath;
Here is a javascript function:
function measure(lat1, lon1, lat2, lon2){ // generally used geo measurement function
var R = 6378.137; // Radius of earth in KM
var dLat = lat2 * Math.PI / 180 - lat1 * Math.PI / 180;
var dLon = lon2 * Math.PI / 180 - lon1 * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d * 1000; // meters
}
Explanation: https://en.wikipedia.org/wiki/Haversine_formula
The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes.
Do you want to do this?
SELECT id, parent_id, name,
(select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id
Edit Another option based on OMG's one (but I think that will perform equally):
select
t1.id,
t1.parent_id,
t1.name,
t2.name AS parent_name,
t2.id AS parent_id
from
(select id, parent_id, name
from tbl
start with id = 1
connect by prior id = parent_id) t1
left join
tbl t2 on t2.id = t1.parent_id
For those that use .NET Standard project in combination with .NET Framework projects:
In the .NET Standard way, packages that are included in a .NET Standard project will correctly be used across other .NET Core and .NET Standard projects.
Im the .NET Framework way, if you are referring to a .NET Standard project from an .NET Framework (MVC) project, you need to manually download and install the same nuget packages.
So the answer to my question was that I had to download and install Microsoft.AspNet.WebApi.Client
in the web project (.NET Framework) that is using a .NET Standard project where Microsoft.AspNet.WebApi.Client
is needed. In fact, I already had this installed but there was a version difference.
I just add this answer for others to see, it might not directly answer OP's question but it did save me time by first checking this instead of doing the top-voted answers.
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
Swift 4/3
You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.
class ResizeBorderView: UIView {
var color = UIColor.white
var lineWidth: CGFloat = 1
var edges = [UIRectEdge](){
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
if edges.contains(.top) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
path.stroke()
}
if edges.contains(.bottom) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
path.stroke()
}
if edges.contains(.left) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
path.stroke()
}
if edges.contains(.right) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
path.stroke()
}
}
}
ResourceManager and .resx are bit messy.
You could use Lexical.Localization¹ which allows embedding default value and culture specific values into the code, and be expanded in external localization files for futher cultures (like .json or .resx).
public class MyClass
{
/// <summary>
/// Localization root for this class.
/// </summary>
static ILine localization = LineRoot.Global.Type<MyClass>();
/// <summary>
/// Localization key "Ok" with a default string, and couple of inlined strings for two cultures.
/// </summary>
static ILine ok = localization.Key("Success")
.Text("Success")
.fi("Onnistui")
.sv("Det funkar");
/// <summary>
/// Localization key "Error" with a default string, and couple of inlined ones for two cultures.
/// </summary>
static ILine error = localization.Key("Error")
.Format("Error (Code=0x{0:X8})")
.fi("Virhe (Koodi=0x{0:X8})")
.sv("Sönder (Kod=0x{0:X8})");
public void DoOk()
{
Console.WriteLine( ok );
}
public void DoError()
{
Console.WriteLine( error.Value(0x100) );
}
}
¹ (I'm maintainer of that library)
In case you want to increase the font of the labels of the histogram when setting labels=TRUE
bp=hist(values, labels = FALSE,
main='Histogram',
xlab='xlab',ylab='ylab', cex.main=2, cex.lab=2,cex.axis=2)
text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)
Here's a polyfill for the Number
predicate functions:
"use strict";
Number.isNaN = Number.isNaN ||
n => n !== n; // only NaN
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Number.isFinite = Number.isFinite ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE; // and +Infinity
Number.isInteger = Number.isInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE // and +Infinity
&& !(n % 1); // and non-whole numbers
Number.isSafeInteger = Number.isSafeInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
&& n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
&& !(n % 1); // and non-whole numbers
All major browsers support these functions, except isNumeric
, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:
"use strict";
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Alternatively, just inline the expression n === +n
manually.
Josh is correct but he left out one variation:
ALTER ROLE <role_name> IN DATABASE <db_name> SET search_path TO schema1,schema2;
Set the search path for the user, in one particular database.
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
Check if the project having HRESULT: 0x80131040 error is being used/referenced by any project. If yes, kindly check if these project have similar .dll being referenced and the version is the same. If they're are not of same version number, then it is causing the said error.
I know this is very old question, however there is a very lightweight (~.5Kb) JavaScript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.
The library is Keydrown.
Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:
kd.P.down(function () {
console.log('The "P" key is being held down!');
});
kd.P.up(function () {
console.clear();
});
// This update loop is the heartbeat of Keydrown
kd.run(function () {
kd.tick();
});
I've incorporated Keydrown into my client-side JavaScript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)
I hope this helps.
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
The favicon is declared in the head tag with something like:
<link rel="shortcut icon" type="image/ico" href="favicon.ico">
You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.
// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);??
From your comment:
this line
DateTime Date = reader.GetDateTime(0);
was throwing the exception
The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:
SELECT * from INFO
Replace it with a query that retrieves only the two columns you're interested in:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO
Then try reading the values again:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1); // equivalent to time(7) from your database
Or:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];