Here are the steps that worked for me:
Just try this code this code work with me
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
//console.log(lat +" "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
//console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
if(results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
}
console.log(country.long_name);
console.log(country.short_name);
} else {
alert("No results found");
console.log("No results found");
}
});
}, function (err) {
});
Well, you asked how to store Latitude/Longitude and my answer is: Don't, you might consider using the WGS 84 ( in Europe ETRS 89 ) as it is the standard for Geo references.
But that detail aside I used a User Defined Type in the days before SQL 2008 finally include geo support.
EDIT:
Forgot to say that this solution is in pure js, the only thing you need is a browser that supports promises https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise
For those who still needs to accomplish such, I've written my own solution that combines promises with timeouts.
Code:
/*
class: Geolocalizer
- Handles location triangulation and calculations.
-- Returns various prototypes to fetch position from strings or coords or dragons or whatever.
*/
var Geolocalizer = function () {
this.queue = []; // queue handler..
this.resolved = [];
this.geolocalizer = new google.maps.Geocoder();
};
Geolocalizer.prototype = {
/*
@fn: Localize
@scope: resolve single or multiple queued requests.
@params: <array> needles
@returns: <deferred> object
*/
Localize: function ( needles ) {
var that = this;
// Enqueue the needles.
for ( var i = 0; i < needles.length; i++ ) {
this.queue.push(needles[i]);
}
// return a promise and resolve it after every element have been fetched (either with success or failure), then reset the queue.
return new Promise (
function (resolve, reject) {
that.resolveQueueElements().then(function(resolved){
resolve(resolved);
that.queue = [];
that.resolved = [];
});
}
);
},
/*
@fn: resolveQueueElements
@scope: resolve queue elements.
@returns: <deferred> object (promise)
*/
resolveQueueElements: function (callback) {
var that = this;
return new Promise(
function(resolve, reject) {
// Loop the queue and resolve each element.
// Prevent QUERY_LIMIT by delaying actions by one second.
(function loopWithDelay(such, queue, i){
console.log("Attempting the resolution of " +queue[i-1]);
setTimeout(function(){
such.find(queue[i-1], function(res){
such.resolved.push(res);
});
if (--i) {
loopWithDelay(such,queue,i);
}
}, 1000);
})(that, that.queue, that.queue.length);
// Check every second if the queue has been cleared.
var it = setInterval(function(){
if (that.queue.length == that.resolved.length) {
resolve(that.resolved);
clearInterval(it);
}
}, 1000);
}
);
},
/*
@fn: find
@scope: resolve an address from string
@params: <string> s, <fn> Callback
*/
find: function (s, callback) {
this.geolocalizer.geocode({
"address": s
}, function(res, status){
if (status == google.maps.GeocoderStatus.OK) {
var r = {
originalString: s,
lat: res[0].geometry.location.lat(),
lng: res[0].geometry.location.lng()
};
callback(r);
}
else {
callback(undefined);
console.log(status);
console.log("could not locate " + s);
}
});
}
};
Please note that it's just a part of a bigger library I wrote to handle google maps stuff, hence comments may be confusing.
Usage is quite simple, the approach, however, is slightly different: instead of looping and resolving one address at a time, you will need to pass an array of addresses to the class and it will handle the search by itself, returning a promise which, when resolved, returns an array containing all the resolved (and unresolved) address.
Example:
var myAmazingGeo = new Geolocalizer();
var locations = ["Italy","California","Dragons are thugs...","China","Georgia"];
myAmazingGeo.Localize(locations).then(function(res){
console.log(res);
});
Console output:
Attempting the resolution of Georgia
Attempting the resolution of China
Attempting the resolution of Dragons are thugs...
Attempting the resolution of California
ZERO_RESULTS
could not locate Dragons are thugs...
Attempting the resolution of Italy
Object returned:
The whole magic happens here:
(function loopWithDelay(such, queue, i){
console.log("Attempting the resolution of " +queue[i-1]);
setTimeout(function(){
such.find(queue[i-1], function(res){
such.resolved.push(res);
});
if (--i) {
loopWithDelay(such,queue,i);
}
}, 750);
})(that, that.queue, that.queue.length);
Basically, it loops every item with a delay of 750 milliseconds between each of them, hence every 750 milliseconds an address is controlled.
I've made some further testings and I've found out that even at 700 milliseconds I was sometimes getting the QUERY_LIMIT error, while with 750 I haven't had any issue at all.
In any case, feel free to edit the 750 above if you feel you are safe by handling a lower delay.
Hope this helps someone in the near future ;)
Please note that there is a mistake in the url provided in this answer:
For a PUT mapping request: the url should be as follows:
http://localhost:9200/name_of_index/_mappings/document_type
and NOT
I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:
http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true
OUTPUT = json or xml;
for detail information about google map api go through url:
http://code.google.com/apis/maps/documentation/geocoding/index.html
Hope this will help
Based on Elliot Wood's function, and if anyone is interested in a C function, this one is working...
#define SIM_Degree_to_Radian(x) ((float)x * 0.017453292F)
#define SIM_PI_VALUE (3.14159265359)
float GPS_Distance(float lat1, float lon1, float lat2, float lon2)
{
float theta;
float dist;
theta = lon1 - lon2;
lat1 = SIM_Degree_to_Radian(lat1);
lat2 = SIM_Degree_to_Radian(lat2);
theta = SIM_Degree_to_Radian(theta);
dist = (sin(lat1) * sin(lat2)) + (cos(lat1) * cos(lat2) * cos(theta));
dist = acos(dist);
// dist = dist * 180.0 / SIM_PI_VALUE;
// dist = dist * 60.0 * 1.1515;
// /* Convert to km */
// dist = dist * 1.609344;
dist *= 6370.693486F;
return (dist);
}
You may change it to double. It returns the value in km.
Here the simple and perfect code for calculating the distance between two latitude and longitude. The following code have been found from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/
$latitudeFrom = '22.574864';
$longitudeFrom = '88.437915';
$latitudeTo = '22.568662';
$longitudeTo = '88.431918';
//Calculate distance from latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance = ($miles * 1.609344).' km';
I arrived at a much simpler and robust solution which is using geodesic
from geopy
package since you'll be highly likely using it in your project anyways so no extra package installation needed.
Here is my solution:
from geopy.distance import geodesic
origin = (30.172705, 31.526725) # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)
print(geodesic(origin, dist).meters) # 23576.805481751613
print(geodesic(origin, dist).kilometers) # 23.576805481751613
print(geodesic(origin, dist).miles) # 14.64994773134371
Wrap your $adr
in urlencode()
.
I was having this problem and this solved it for me.
You want a geocoding application. These are available either online or as an application backend.
Online applications:
Backend applications:
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
BigDataCloud also has a nice API for this, also for nodejs users.
they have API for client - free. But also for backend, using API_KEY (free according to quota).
the code looks like:
const client = require('@bigdatacloudapi/client')(API_KEY);
async foo() {
...
const location: string = await client.getReverseGeocode({
latitude:'32.101786566878445',
longitude: '34.858965073072056'
});
}
Inside of your loop, you have the key, which you can use to retrieve the value from the Map
:
for (String key: mss1.keySet()) {
System.out.println(key + ": " + mss1.get(key));
}
To return just the names of the registered submodules, you can use this command:
grep path .gitmodules | sed 's/.*= //'
Think of it as git submodule --list
which doesn't exist.
public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
.Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}
if using sql server 2005, there is a hidden stored procedure that allows you to execute a command or a set of commands against all tables inside a database. Here is how you would call TRUNCATE TABLE
with this stored procedure:
EXEC [sp_MSforeachtable] @command1="TRUNCATE TABLE ?"
Here is a good article that elaborates further.
For MySql, however, you could use mysqldump and specify the --add-drop-tables
and --no-data
options to drop and create all tables ignoring the data. like this:
mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE]
You can simply use the imutils package to do the rotation. it has two methods
more info you can get on this blog: https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/
Also, you can do this:
(this.DNATranscriber as any)[character];
Edit.
It's HIGHLY recommended that you cast the object with the proper type instead of any
. Casting an object as any
only help you to avoid type errors when compiling typescript but it doesn't help you to keep your code type-safe.
E.g.
interface DNA {
G: "C",
C: "G",
T: "A",
A: "U"
}
And then you cast it like this:
(this.DNATranscriber as DNA)[character];
Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz"
but only sees "abcd...wxy
.
This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.
One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage
:
chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
console.log(data);
});
Now before your callback is called, the browser would attempt to parse the message using JSON.parse
which can give you "unexpected end of input" errors if the supplied byte length does not match the data.
Try this query
SELECT data_collector_id , count (data_collector_id ) as frequency
from rent_flats
where is_contact_person_landlord = 'True'
GROUP BY data_collector_id
ORDER BY count(data_collector_id) DESC
The problem is the charset that is being used by apache to serve the pages. I work with Linux, so I don't know anything about XAMPP. I had the same problem too, what I did to solve the problem was to add the charset to the charset
config file (It is commented by default).
In my case I have it in /etc/apache2/conf.d/charset
but, since you're using Windows the location is different. So I'm giving you this like an idea of how to solve it.
At the end, my charset config file is like this:
# Read the documentation before enabling AddDefaultCharset.
# In general, it is only a good idea if you know that all your files
# have this encoding. It will override any encoding given in the files
# in meta http-equiv or xml encoding tags.
AddDefaultCharset UTF-8
I hope it helps.
Actually, DB::connection('name')->select(..)
doesnt work for me, because 'name' has to be in double quotes: "name"
Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.
Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of
env('DB_DATABASE', 'name')
I needed to place something like
'myNewName'
since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name
Therefore, every time I wanted to select something from another database I always ended up in my default database
First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.
df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})
And the mapping that you desire:
mapping = dict(enumerate([2,5,6,8,12,16,26,32]))
df['D'] = df['A'].map(mapping)
Done!
print df
Output:
A D
0 0 2
1 4 12
2 5 16
3 6 26
4 7 32
5 7 32
6 6 26
7 5 16
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
Unfortunately this is a restriction of the Google maps service.
I am currently working on an application using the geocoding feature, and I'm saving each unique address on a per-user basis. I generate the address information (city, street, state, etc) based on the information returned by Google maps, and then save the lat/long information in the database as well. This prevents you from having to re-code things, and gives you nicely formatted addresses.
Another reason you want to do this is because there is a daily limit on the number of addresses that can be geocoded from a particular IP address. You don't want your application to fail for a person for that reason.
Add this to your button's click listener:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
try {
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(getContext(), "Error text", Toast.LENGTH_SHORT).show();
}
If you have a website url as a variable instead of hardcoded string then don't forget to handle an ActivityNotFoundException and show error. Or you may receive invalid url and app will simply crash. (Pass random string instead of url
variable and see for youself )
Can't you use
id = id.substring(0, id.length()-4);
And what Eric said, ofcourse.
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.
So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.
Once you bound successfully, your query in it's current shape is all you need.
BTW: Choosing "ObjectCategory=Person"
over "ObjectClass=user"
was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.
The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.
Let's say you have a list of integers, and want to find the items that match those integers.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var items = from p in context.Items
where numbers.Contains(p.ItemId)
select p;
Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0
If you're using PaperClip, downloading from a URL is now handled automatically.
Assuming you've got something like:
class MyModel < ActiveRecord::Base
has_attached_file :image, ...
end
On your model, just specify the image as a URL, something like this (written in deliberate longhand):
@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)
You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.
Paperclip will take it from there.
source: paperclip documentation
That is because Low
is a string.
.toFixed()
only works with a number.
Try doing:
Low = parseFloat(Low).toFixed(..);
I would like to use the concatenate
and ravel
of the numpy
as below
import numpy as np
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
out = np.concatenate(np.array(l)).ravel()
I've seen this on my Github for Windows.
I recommend uninstalling Github for Windows and installing it again.
Before this, I tried several ways with no success, but this solution worked for me!
Instead of gdb
, run gdbtui
. Or run gdb
with the -tui
switch. Or press C-x C-a after entering gdb
. Now you're in GDB's TUI mode.
Enter layout asm
to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish
etc. are abbreviated to a single key, allowing you to walk through your program very quickly.
+---------------------------------------------------------------------------+ B+>|0x402670 <main> push %r15 | |0x402672 <main+2> mov %edi,%r15d | |0x402675 <main+5> push %r14 | |0x402677 <main+7> push %r13 | |0x402679 <main+9> mov %rsi,%r13 | |0x40267c <main+12> push %r12 | |0x40267e <main+14> push %rbp | |0x40267f <main+15> push %rbx | |0x402680 <main+16> sub $0x438,%rsp | |0x402687 <main+23> mov (%rsi),%rdi | |0x40268a <main+26> movq $0x402a10,0x400(%rsp) | |0x402696 <main+38> movq $0x0,0x408(%rsp) | |0x4026a2 <main+50> movq $0x402510,0x410(%rsp) | +---------------------------------------------------------------------------+ child process 21518 In: main Line: ?? PC: 0x402670 (gdb) file /opt/j64-602/bin/jconsole Reading symbols from /opt/j64-602/bin/jconsole...done. (no debugging symbols found)...done. (gdb) layout asm (gdb) start (gdb)
Add a line Configuration.ProxyCreationEnabled = false;
in constructor of your context model partial class definition.
public partial class YourDbContextModelName : DbContext
{
public YourDbContextModelName()
: base("name=YourDbContextConn_StringName")
{
Configuration.ProxyCreationEnabled = false;//this is line to be added
}
public virtual DbSet<Employee> Employees{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
While, the fix as per Valeri works, but its only for tfjs.
If you're expecting for body-pix or any other tensor-flow/models, you would be facing the same. It is an open issue too and the team is working on the fix!
https://github.com/dequelabs/axe-core/issues/1977
But, if you don't have problem in degrading the version (if anyone wants to use body-pix) from latest docs, below both links works fine as I've tested the same:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"></script>
Choose some columns to coerce to factors:
cols <- c("A", "C", "D", "H")
Use lapply()
to coerce and replace the chosen columns:
data[cols] <- lapply(data[cols], factor) ## as.factor() could also be used
Check the result:
sapply(data, class)
# A B C D E F G
# "factor" "integer" "factor" "factor" "integer" "integer" "integer"
# H I J
# "factor" "integer" "integer"
Swift 3+
button.setImage(UIImage(named: "selected_image"), for: [.selected, .highlighted])
OR
button.setImage(UIImage(named: "selected_image"), for: UIControlState.selected.union(.highlighted))
It means that the button current in selected
state, then you touch it, show the highlight
state.
it's android:button="@drawable/selector_checkbox"
to make it work
Found this solution and this worked perfectly for me.
sudo -H pip install virtualenv
The -H sets it to the HOME directory, which seems to be the issue for most people.
You can use :nth-last-child()
; in fact, besides :nth-last-of-type()
I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.
ul li:nth-last-child(2)
I like Dan's answer, esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available.
Added a check for white-space after a valid string...these three lines
while (isspace(*end)) {
end++;
}
Added a check for parsing errors too.
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
Here is the complete function..
#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>
enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
char *end = (char *)s;
errno = 0;
l = strtol(s, &end, base);
if ((errno == ERANGE) && (l == LONG_MAX)) {
return OVERFLOW;
}
if ((errno == ERANGE) && (l == LONG_MIN)) {
return UNDERFLOW;
}
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
while (isspace((unsigned char)*end)) {
end++;
}
if (*s == '\0' || *end != '\0') {
return INCONVERTIBLE;
}
return SUCCESS;
}
If you want an easy and stress-free way to write logs line by line in a file, then I recommend fs-extra:
const os = require('os');
const fs = require('fs-extra');
const file = 'logfile.txt';
const options = {flag: 'a'};
async function writeToFile(text) {
await fs.outputFile(file, `${text}${os.EOL}`, options);
}
writeToFile('First line');
writeToFile('Second line');
writeToFile('Third line');
writeToFile('Fourth line');
writeToFile('Fifth line');
Tested with Node v8.9.4.
I think that right implementations should be
public class Thing
{
public int value;
public Thing (int x)
{
this.value = x;
}
@Override
public boolean equals(Object object)
{
boolean sameSame = false;
if (object != null && object instanceof Thing)
{
sameSame = this.value == ((Thing) object).value;
}
return sameSame;
}
}
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
As I understand, you want to recursively copy test directory into /home/server/
path...
This can be done as:
-cp -rf /home/server/folder/test/* /home/server/
Hope this helps
For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes
or attributes=
methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.
Both methods follow this usage:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }
@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }
Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save
is called.
attributes=
differs slightly from assign_attributes
in Rails 3. attributes=
will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes
has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
The following invalid code will silently fail by simply returning without setting the attributes:
@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]
attributes=
will silently behave as though the assignments were made successfully, when really, they were not.
This invalid code will raise an exception when assign_attributes
tries to stringify the hash keys of the enclosing array:
@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])
assign_attributes
will raise a NoMethodError
exception for stringify_keys
, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.
The only difference between these cases is the method used for mass assignment: attributes=
silently succeeds, and assign_attributes
raises an exception to inform that an error has occurred.
These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[]
the results of the final .map
. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.
The lesson with Rails 3 is this: always use assign_attributes
instead of attributes=
.
In Rails 4, attributes=
is simply an alias to assign_attributes
. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.
If you're pre-flighting assignments in preparation to a save
, you might be interested in validating before save, as well. You can use the valid?
and invalid?
methods for this. Both return boolean values. valid?
returns true if the unsaved model passes all validations or false if it does not. invalid?
is simply the inverse of valid?
valid?
can be used like this:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?
This will give you the ability to handle any validations issues in advance of calling save
.
Use FractionallySizedBox
widget.
FractionallySizedBox(
widthFactor: 1.0, // width w.r.t to parent
heightFactor: 1.0, // height w.r.t to parent
child: *Your Child Here*
}
This widget is also very useful when you want to size your child at a fractional of its parent's size.
Example:
If you want the child to occupy 50% width of its parent, provide
widthFactor
as0.5
As explained by Ron, there are two variables, local and global. The local variable is always used, and is the same as global upon connection.
SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;
SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable
When setting the GLOBAL variable, the local one isn't changed for any existing connections. You need to reconnect or set the local variable too.
Perhaps unintuitive, MYSQL does not enforce foreign keys when FOREIGN_KEY_CHECKS are re-enabled. This makes it possible to create an inconsistent database even though foreign keys and checks are on.
If you want your foreign keys to be completely consistent, you need to add the keys while checking is on.
Per MSDN it is
By default, the maximum size of an Array is 2 gigabytes (GB).
In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.
However, the array will still be limited to a total of 4 billion elements.
Refer Here http://msdn.microsoft.com/en-us/library/System.Array(v=vs.110).aspx
Note: Here I am focusing on the actual length of array by assuming that we will have enough hardware RAM.
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
I did it in this way.
In tasks/main.yml
- name: template test
template:
src=myTemplateFile.j2
dest={{item}}
with_dict: some_dict
and in vars/main.yml
some_dict:
/path/to/dest1:
var1: 1
var2: 2
/path/to/dest2:
var1: 3
var2: 4
and in templates/myTemplateFile.j2
some_var = {{ item.value.var1 }}
some_other_var = {{ item.value.var2 }}
Hope this solves your problem.
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Solution:-
mongoimport --db databaseName --collection tableName --file filepath.json
Example:-
Place your file in admin folder:-
C:\Users\admin\tourdb\places.json
Run this command on your teminal:-
mongoimport --db tourdb --collection places --file ~/tourdb/places.json
Output:-
admin@admin-PC MINGW64 /
$ mongoimport --db tourdb --collection places --file ~/tourdb/places.json
2019-08-26T14:30:09.350+0530 connected to: localhost
2019-08-26T14:30:09.447+0530 imported 10 documents
For more link
2 / 4 = 0 with a remainder of 2
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/ Hope that helps!
You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features.
import js2py
js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")
result = js2py.eval_js(js) # executing JavaScript and converting the result to python string
Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).
To install:
pip install js2py
One thing that i didn't see in other answers is To clarify another answers that there is a difference between returning std::unique_ptr that has been created within a function, and one that has been given to that function.
The example could be like this:
class Test
{int i;};
std::unique_ptr<Test> foo1()
{
std::unique_ptr<Test> res(new Test);
return res;
}
std::unique_ptr<Test> foo2(std::unique_ptr<Test>&& t)
{
// return t; // this will produce an error!
return std::move(t);
}
//...
auto test1=foo1();
auto test2=foo2(std::unique_ptr<Test>(new Test));
You can get the selected item from Spinner by using,
interested.getSelectedItem().toString();
SELECT DISTINCT will always be the same, or faster, than a GROUP BY. On some systems (i.e. Oracle), it might be optimized to be the same as DISTINCT for most queries. On others (such as SQL Server), it can be considerably faster.
<button>
's are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
In my case, the problem was styling header as "Header 1" but that style was not exist in the Word that I get the error because it was not an Office in English Language.
You can use -[NSString integerValue]
, -[NSString floatValue]
, etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:]
which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter
(including whether it will allow floating point values).
go to Services, find SQL Server Browser, right click --> Properties --> General tab --> Startup Type --> select automatic . Then go back to configuration management, start it.
For the merge commit message, I found that I cannot amend it by using rebase
, at least on gitlab. It shows the merge as a commit but I cannot rebase onto that #sha. I found this post is helpful.
git checkout <sha of merge>
git commit --amend # edit message
git rebase HEAD previous_branch
This three lines of code did the job for changing the merge commit message (like author).
You can select it using css like this:
input[disabled] { /* css attributes */ }
Return types using arrow notation is the same as previous answers:
const sum = (a: number, b: number) : number => a + b;
You can't. The last stylesheet you specify will be the one html page will use. Think of it as a big single .css document.
One way of doing it is to draw the image to a bitmap context that is backed by a given buffer for a given colorspace (in this case it is RGB): (note that this will copy the image data to that buffer, so you do want to cache it instead of doing this operation every time you need to get pixel values)
See below as a sample:
// First get the image into your data buffer
CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];
You can use either TASKSCHD.MSC
or CONTROL SCHEDTASKS
Here are some more such commands.
In case you want to clone a specific branch only, then,
git clone -b <branch-name> <repo-url> <destination-folder-name>
for example,
git clone -b dev https://github.com/sferik/sign-in-with-twitter.git signin
Here is all you need to know about relative file paths:
Starting with /
returns to the root directory and starts there
Starting with ../
moves one directory backward and starts there
Starting with ../../
moves two directories backward and starts there (and so on...)
To move forward, just start with the first sub directory and keep moving forward.
Click here for more details!
Line breaks character for NSString is \r
correct way to use [NSString StringWithFormat:@"%@\r%@",string1,string2];
\r ----> carriage return
For only date use
date("Y-m-d");
and for only time use
date("H:i:s");
It's because you have a recursive function inside of rotate. It's calling itself again:
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
Take that out and it won't keep on running recursively.
I would also suggest just using this function instead:
function rotate($el, degrees) {
$el.css({
'-webkit-transform' : 'rotate('+degrees+'deg)',
'-moz-transform' : 'rotate('+degrees+'deg)',
'-ms-transform' : 'rotate('+degrees+'deg)',
'-o-transform' : 'rotate('+degrees+'deg)',
'transform' : 'rotate('+degrees+'deg)',
'zoom' : 1
});
}
It's much cleaner and will work for the most amount of browsers.
I use this form for just this sort of thing:
gci . hosts -r | ? {!$_.PSIsContainer}
.
maps to positional parameter Path
and "hosts" maps to positional parameter Filter
. I highly recommend using Filter
over Include
if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include
.
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
You might be able to use MySQLi syntax, which would allow you to handle it better.
Define the database connections, then whenever you want to query one of the database, specify the right connection.
E.g.:
$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection
Then to query them on the same page, use something like:
$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");
Changing to MySQLi in this way will help you.
You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
Since it's C++, use an inline function:
template <typename INT>
INT rol(INT val) {
return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
}
C++11 variant:
template <typename INT>
constexpr INT rol(INT val) {
static_assert(std::is_unsigned<INT>::value,
"Rotate Left only makes sense for unsigned types");
return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
}
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
C:\Users\<_username>\.gradle\wrapper\dists\gradle-<_version>-all\<_number_random_maybe>\gradle-<_version>
\Android studio\gradle didn't worked for me.
And "Default gradle wrapper" wasn't configured while importing (cloning) the project from bitbucket
If it causes problem to figure out the path, here is my path :
C:\Users\prabs\.gradle\wrapper\dists\gradle-5.4.1-all\3221gyojl5jsh0helicew7rwx\gradle-5.4.1
Don't forget the 5xx errors as well for application errors.
In this case what about 409 (Conflict)? This assumes that the user can fix the problem by deleting stored resources.
Otherwise 507 (not entirely standard) may also work. I wouldn't use 200 unless you use 200 for errors in general.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
Optional Constraint Name:
If you leave out CONSTRAINT D_SomeTable_SomeCol
then SQL Server will autogenerate
a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6
Optional With-Values Statement:
The WITH VALUES
is only needed when your Column is Nullable
and you want the Default Value used for Existing Records.
If your Column is NOT NULL
, then it will automatically use the Default Value
for all Existing Records, whether you specify WITH VALUES
or not.
How Inserts work with a Default-Constraint:
If you insert a Record into SomeTable
and do not Specify SomeCol
's value, then it will Default to 0
.
If you insert a Record and Specify SomeCol
's value as NULL
(and your column allows nulls),
then the Default-Constraint will not be used and NULL
will be inserted as the Value.
Notes were based on everyone's great feedback below.
Special Thanks to:
@Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
Sadly the other posters are correct that you're
...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.
Out of completeness, the type selector is - similar to xpath - of the form [attribute=value]
but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
Perhaps your Apache is bounded to localhost only. Look in your apache configuration file for:
Listen 127.0.0.1:80
If you found it, replace it for:
Listen 80
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
a simple solution is to use the -ls option in find:
find . -name \*.ear -ls
That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:
find . -name \*.ear -printf "%p\t%k KB\n"
Which will give you the filename followed by the size in KB.
Use this code it will help for getting any type of device's screen resolution
[[UIScreen mainScreen] bounds].size.height
[[UIScreen mainScreen] bounds].size.width
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/colorAccent" />
<corners
android:bottomLeftRadius="500dp"
android:bottomRightRadius="500dp"
android:topLeftRadius="500dp"
android:topRightRadius="500dp" />
</shape>
Now, in which element you want to use this shape just add:
android:background="@drawable/custom_round_ui_shape"
Create a new XML in drawable named "custom_round_ui_shape"
In Konsole (KDE terminal) is the same, Ctrl + Shift + V
Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.
In short, the following are the steps to generate flame graphs
yum -y install perf
wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz
tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64
echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict
JAVA_PID=`pgrep java`
./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg
flame-graph.svg
can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.
There are few other approaches to generating them
-XX:+PreserveFramePointer
as the JVM options as described here-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
as described hereBut using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.
Their wiki provides details on how to leverage it. And more about flame graphs can be found here
If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript (using jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.
If you don't believe me look at the String.Concat
definition using reflector.
The last lines are...
int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;
As you can see the FastAllocateString
returns an empty but allocated string and then it is modified by FillStringChecked
Actually the FastAllocateString
is an extern method and the FillStringChecked
is unsafe so it uses pointers to copy the bytes.
Maybe there are better examples but this is the one I have found so far.
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
You should try using the Grid Template.
Here's what I've used for a two Column Layout of a <ul>
<ul class="list-group row">
<li class="list-group-item col-xs-6">Row1</li>
<li class="list-group-item col-xs-6">Row2</li>
<li class="list-group-item col-xs-6">Row3</li>
<li class="list-group-item col-xs-6">Row4</li>
<li class="list-group-item col-xs-6">Row5</li>
</ul>
This worked for me.
addAccordian(type, data) { console.log(type, data);
let form = this.form;
if (!form.controls[type]) {
let ownerAccordian = new FormArray([]);
const group = new FormGroup({});
ownerAccordian.push(
this.applicationService.createControlWithGroup(data, group)
);
form.controls[type] = ownerAccordian;
} else {
const group = new FormGroup({});
(<FormArray>form.get(type)).push(
this.applicationService.createControlWithGroup(data, group)
);
}
console.log(this.form);
}
I would recommend looking at these awesome functions from PHP core:
similar_text — Calculate the similarity between two strings
http://www.php.net/manual/en/function.similar-text.php
levenshtein — Calculate Levenshtein distance between two strings
http://www.php.net/manual/en/function.levenshtein.php
soundex — Calculate the soundex key of a string
http://www.php.net/manual/en/function.soundex.php
metaphone — Calculate the metaphone key of a string
Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:
^[a-zA-Z ._-]*$
If you use the case-insensitive modifier, you can shorten this to
^[a-z ._-]*$
Note that the space is significant (it is just a character like any other).
Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.
Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.
Improvement on Bludream's answer:
You can definitely use FontAwesome!
Make sure to include "collapsed" along with "panel-heading" class. The "collapsed" class is not included until you click on the panel so you want to include the "collapsed" class in order to display the correct chevron (i.e., chevron-right is displayed when collapsed and chevron-down when open).
HTML
<div class="panel panel-default">
<div class="panel-heading collapsed" data-toggle="collapse" data-target="#collapseOrderItems1">Products 1 <i class="chevron fa fa-fw" ></i></div>
<div class="collapse" id="collapseOrderItems1">
<p>Lorem ipsum...</p>
</div>
</div>
CSS
.panel-heading .chevron:after {
content: "\f078";
}
.panel-heading.collapsed .chevron:after {
content: "\f054";
}
Also, it is a good practice to create a new class instead of using an existing class.
See Codepen for example: http://codepen.io/anon/pen/PPxOJX
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{ // Do stuff here
}
Everybody else has explained well what is the difference.
I would like to add in Ruby On Rails, it is better to use obj.blank?
or obj.present?
instead of obj.nil?
or obj.empty?
.
obj.blank?
handles all types nil
, ''
, []
, {}
, and returns true
if values are not available and returns false
if values are available on any type of object.
If you want to run .py files in Windows, Try installing Git bash Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads" File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!
Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).
Now of the other answers solved it for me. Turns out that renaming a column and an index in the same query caused the error.
Not working:
-- rename column and rename index
ALTER TABLE `client_types`
CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
DROP INDEX client_types_template_path_unique,
ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);
Works (2 statements):
-- rename column
ALTER TABLE `client_types`
CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
-- rename index
ALTER TABLE `client_types`
DROP INDEX client_types_template_path_unique,
ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);
This was on MariaDB 10.0.20. There were no errors with the same query on MySQL 5.5.48.
if ! test -f $PIDFILE || ! psgrep `cat $PIDFILE`; then
restart_process
# Write PIDFILE
echo $! >$PIDFILE
fi
I have made a query for you. This will give you Recursive Category with a Single Query:
SELECT id,NAME,'' AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 WHERE prent is NULL
UNION
SELECT b.id,a.name,b.name AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id WHERE a.prent is NULL AND b.name IS NOT NULL
UNION
SELECT c.id,a.name,b.name AS subName,c.name AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id WHERE a.prent is NULL AND c.name IS NOT NULL
UNION
SELECT d.id,a.name,b.name AS subName,c.name AS subsubName,d.name AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id LEFT JOIN Table1 AS d ON d.prent=c.id WHERE a.prent is NULL AND d.name IS NOT NULL
ORDER BY NAME,subName,subsubName,subsubsubName
Here is a fiddle.
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
try this: File->project Structure into Project Structure Left > SDKs SDK location select Android SDK location (old version use Press +, add another sdk)
[ ].has(obj)
assuming .indexOf()
is implemented
Object.defineProperty( Array.prototype,'has',
{
value:function(o, flag){
if (flag === undefined) {
return this.indexOf(o) !== -1;
} else { // only for raw js object
for(var v in this) {
if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
}
return false;
},
// writable:false,
// enumerable:false
})
!!! do not make Array.prototype.has=function(){...
because you'll add an enumerable element in every array and js is broken.
//use like
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") // true
[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false
the use of 2nd arg (flag) forces comparation by value instead of reference
comparing raw objects
[o1].has(o2,true) // true if every level value is same
you had this
destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)
which was place holder text above you need to insert some values
class Edge{
}
public class Node{
var key: String?
var neighbors: [Edge]
var visited: Bool = false
var lat: Double
var long: Double
init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
self.neighbors = [Edge]()
self.key = key
self.visited = visited
self.lat = lat
self.long = long
}
}
class Path {
var total: Int!
var destination: Node
var previous: Path!
init(){
destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
}
}
If you want to make transparent background is gray, pls try:
.transparent{
background:rgba(1,1,1,0.5);
}
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
For multiple interval types use a nested construction as in:
UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)
For updating a given date in the column date
to 1 year + 1 day
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.
If you want to test for value equality should use the handy comparison functions in java.util.Arrays
e.g.
import java.util.Arrays;
'''''
Arrays.equals(a,b);
here is the one working fine:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")
def convertIt():
web.print_(printer)
print("Pdf generated")
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
Your response must return some sort of Response
object. You can't just return an object.
So change it to something like:
return Response::json($promotion);
or my favorite using the helper function:
return response()->json($promotion);
If returning a response doesn't work it may be some sort of encoding issue. See this article: The Response content must be a string or object implementing __toString(), \"boolean\" given."
I know it's old question but it still in first 10 links in google.
It is not very efficient to save rows one-by-one because it cause database call in the loop and you better avoid that, especially when you need to insert huge portions of data.
It's better (and significantly faster) to use batch insert.
INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
('s1', 'supplier1', 1.111),
('s2', 'supplier2', '2.222')
You can build such a query manually and than do Model.connection.execute(RAW SQL STRING)
(not recomended)
or use gem activerecord-import
(it was first released on 11 Aug 2010) in this case just put data in array rows
and call Model.import rows
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
Please use test flight to obtain UDID from testers but not using untrusted source e.g. http://get.udid.io/
You can 1. Invite testers in email from test flight webpage. Testers open the link in email and install a profile from test flight. Therefore developers can obtain UDIDs on the test flight webpage. 2. Add those UDIDs on the Apple provisioning portal.
(Ref: http://help.testflightapp.com/customer/portal/articles/829537-how-does-it-work-)
The process doesn't require testers to use Mac/ PC to obtain UDID (more convenient). And I think test flight is a company that can be trusted (no worries when passing UDID to this company).
I have tested this method and it works on iOS 8.
Edit:
I was reading the comments on the manual page and came across a bug that states that ob_implicit_flush
does not work and the following is a workaround for it:
ob_end_flush();
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_start();
If this does not work then what may even be happening is that the client does not receive the packet from the server until the server has built up enough characters to send what it considers a packet worth sending.
Old Answer:
You could use ob_implicit_flush
which will tell output buffering to turn off buffering for a while:
ob_implicit_flush(true);
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_implicit_flush(false);
The one with symbolic link support:
import path from "path"
import {
existsSync, mkdirSync, readdirSync, lstatSync,
copyFileSync, symlinkSync, readlinkSync
} from "fs"
export function copyFolderSync(src, dest) {
if (!existsSync(dest)) mkdirSync(dest)
readdirSync(src).forEach(dirent => {
const [srcPath, destPath] = [src, dest].map(dirPath => path.join(dirPath, dirent))
const stat = lstatSync(srcPath)
switch (true) {
case stat.isFile():
copyFileSync(srcPath, destPath); break
case stat.isDirectory():
copyFolderSync(srcPath, destPath); break
case stat.isSymbolicLink():
symlinkSync(readlinkSync(srcPath), destPath); break
}
})
}
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).
If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:
let john = {
firstName: "John",
lastName: "Doe",
};
let people = new Array(10).fill().map((e, i) => {(...john, id: i});
if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.
Well, I am quite surprised that the alternatives to this syntax have not been mentioned. Another common (but older) mechanism is to call a function that isn't defined and rely on the optimizer to compile-out the function call if your assertion is correct.
#define MY_COMPILETIME_ASSERT(test) \
do { \
extern void you_did_something_bad(void); \
if (!(test)) \
you_did_something_bad(void); \
} while (0)
While this mechanism works (as long as optimizations are enabled) it has the downside of not reporting an error until you link, at which time it fails to find the definition for the function you_did_something_bad(). That's why kernel developers starting using tricks like the negative sized bit-field widths and the negative-sized arrays (the later of which stopped breaking builds in GCC 4.4).
In sympathy for the need for compile-time assertions, GCC 4.3 introduced the error
function attribute that allows you to extend upon this older concept, but generate a compile-time error with a message of your choosing -- no more cryptic "negative sized array" error messages!
#define MAKE_SURE_THIS_IS_FIVE(number) \
do { \
extern void this_isnt_five(void) __attribute__((error( \
"I asked for five and you gave me " #number))); \
if ((number) != 5) \
this_isnt_five(); \
} while (0)
In fact, as of Linux 3.9, we now have a macro called compiletime_assert
which uses this feature and most of the macros in bug.h
have been updated accordingly. Still, this macro can't be used as an initializer. However, using by statement expressions (another GCC C-extension), you can!
#define ANY_NUMBER_BUT_FIVE(number) \
({ \
typeof(number) n = (number); \
extern void this_number_is_five(void) __attribute__(( \
error("I told you not to give me a five!"))); \
if (n == 5) \
this_number_is_five(); \
n; \
})
This macro will evaluate its parameter exactly once (in case it has side-effects) and create a compile-time error that says "I told you not to give me a five!" if the expression evaluates to five or is not a compile-time constant.
So why aren't we using this instead of negative-sized bit-fields? Alas, there are currently many restrictions of the use of statement expressions, including their use as constant initializers (for enum constants, bit-field width, etc.) even if the statement expression is completely constant its self (i.e., can be fully evaluated at compile-time and otherwise passes the __builtin_constant_p()
test). Further, they cannot be used outside of a function body.
Hopefully, GCC will amend these shortcomings soon and allow constant statement expressions to be used as constant initializers. The challenge here is the language specification defining what is a legal constant expression. C++11 added the constexpr keyword for just this type or thing, but no counterpart exists in C11. While C11 did get static assertions, which will solve part of this problem, it wont solve all of these shortcomings. So I hope that gcc can make a constexpr functionality available as an extension via -std=gnuc99 & -std=gnuc11 or some such and allow its use on statement expressions et. al.
If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.
Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.
If you really had to achieve this affect while keeping the children as position: absolute
, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.
Alternatively, just use float: left
/float:right
and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden
on the parent (or any other clearfix technique) to cause its height to expand to that of its children.
article {
position: relative;
overflow: hidden;
}
.one {
position: relative;
float: left;
margin-top: 10px;
margin-left: 10px;
background: red;
width: 30px;
height: 30px;
}
.two {
position: relative;
float: right;
margin-top: 10px;
margin-right: 10px;
background: blue;
width: 30px;
height: 30px;
}
* for python 2.x *
Use a trailing comma to avoid a newline.
print "Hey Guys!",
print "This is how we print on the same line."
The output for the above code snippet would be,
Hey Guys! This is how we print on the same line.
* for python 3.x *
for i in range(10):
print(i, end="<separator>") # <separator> = \n, <space> etc.
The output for the above code snippet would be (when <separator> = " "
),
0 1 2 3 4 5 6 7 8 9
"Session" is the term used to refer to a user's time browsing a web site. It's meant to represent the time between their first arrival at a page in the site until the time they stop using the site. In practice, it's impossible to know when the user is done with the site. In most servers there's a timeout that automatically ends a session unless another page is requested by the same user.
The first time a user connects some kind of session ID is created (how it's done depends on the web server software and the type of authentication/login you're using on the site). Like cookies, this usually doesn't get sent in the URL anymore because it's a security problem. Instead it's stored along with a bunch of other stuff that collectively is also referred to as the session. Session variables are like cookies - they're name-value pairs sent along with a request for a page, and returned with the page from the server - but their names are defined in a web standard.
Some session variables are passed as HTTP headers. They're passed back and forth behind the scenes of every page browse so they don't show up in the browser and tell everybody something that may be private. Among them are the USER_AGENT, or type of browser requesting the page, the REFERRER or the page that linked to the page being requested, etc. Some web server software adds their own headers or transfer additional session data specific to the server software. But the standard ones are pretty well documented.
Hope that helps.
Javascript now give a very useful functionnality to handle url parameters: URLSearchParams
var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()
If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:
$(".contentToStrip").each(function(){
$(this).replaceWith($(this).html());
});
This is what was missing in my .project file:
<projectDescription>
...
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildspec>
...
...
...
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
...
</projectDescription>
I found that the repo that had the package was not enabled. On OEL7,
$ vi /etc/yum.repos.d/ULN-Base.repo
Set enabled to 1 for ol7_optional_latest
$ yum install php-bcmath
and that worked...
I used the following command to find where the package was
$ yum --noplugins --showduplicates --enablerepo \* --disablerepo \*-source --disablerepo C5.\*,c5-media,\*debug\*,\*-source list \*bcmath
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.:
break;
case R.id.:
break;
default:
break;
}
}
I've been looking at the markdown syntax used in github [...], I can't figure out how to center an image
TL;DR
No you can't by only relying on Markdown syntax. Markdown doesn't care with positioning.
Note: Some markdown processors support inclusion of HTML (as rightfully pointed out by @waldyr.ar), and in the GitHub case you may fallback to something like <div style="text-align:center"><img src="..." /></div>
. Beware that there's no guarantee the image will be centered if your repository is forked in a different hosting environment (Codeplex, BitBucket, ...) or if the document isn't read through a browser (Sublime Text Markdown preview, MarkdownPad, VisualStudio Web Essentials Markdown preview, ...).
Note 2: Keep in mind that even within the GitHub website, the way markdown is rendered is not uniform. The wiki, for instance, won't allow such css positional trickery.
Unabridged version
The Markdown syntax doesn't provide one with the ability to control the position of an image.
In fact, it would be borderline against the Markdown philosophy to allow such formatting, as stated in the "Philosophy" section
"A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. "
Markdown files are rendered by github.com website through the use of the Ruby Redcarpet library.
Redcarpet exposes some extensions (such as strikethrough, for instance) which are not part of standard Markdown syntax and provide additional "features". However, no supported extension allow you to center an image.
select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b
where table_name='YOUR_TABLE' and a.table_name = b.name;
This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value
). Else, if default partition is defined, it would go there.
EDIT:
I presume, your TABLE DDL would be like this.
CREATE TABLE HE0_DT_INF_INTERFAZ_MES
(
COD_PAIS NUMBER,
FEC_DATA NUMBER,
INTERFAZ VARCHAR2(100)
)
partition BY RANGE(COD_PAIS, FEC_DATA)
(
PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
);
Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);
That is first COD_PAIS <= 98
and Also FEC_DATA < 20091024
Combinations And Result:
98, 20091024 FAIL
98, 20091023 PASS
99, ******** FAIL
97, ******** PASS
< 98, ******** PASS
So the below INSERT
fails with ORA-14400; because (98,20091024)
in INSERT
is EQUAL to the one in DDL
but NOT less than it.
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
VALUES(98, 20091024, 'CTA'); 2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
*
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition
But, we I attempt (97,20091024), it goes through
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
2 VALUES(97, 20091024, 'CTA');
1 row created.
The preferred modern method is to use addEventListener
either by adding the event listener direct to the element or to a parent of the elements (delegated).
An example, using delegated events, might be
var box = document.getElementById('box');_x000D_
_x000D_
document.getElementById('buttons').addEventListener('click', function(evt) {_x000D_
var target = evt.target;_x000D_
if (target.id === 'yes') {_x000D_
box.style.backgroundColor = 'red';_x000D_
} else if (target.id === 'no') {_x000D_
box.style.backgroundColor = 'green';_x000D_
} else {_x000D_
box.style.backgroundColor = 'purple';_x000D_
}_x000D_
}, false);
_x000D_
#box {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background-color: red;_x000D_
}_x000D_
#buttons {_x000D_
margin-top: 50px;_x000D_
}
_x000D_
<div id='box'></div>_x000D_
<div id='buttons'>_x000D_
<button id='yes'>yes</button>_x000D_
<button id='no'>no</button>_x000D_
<p>Click one of the buttons above.</p>_x000D_
</div>
_x000D_
That is because you have used following line to assign the value which is wrong.
x=&x;
In PL/SQL assignment is done using following.
:=
So your code should be like this.
declare
x number;
begin
x:=&x;
-- Below line will output the number you received as an input
dbms_output.put_line(x);
end;
/
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
The method argument specifies the parameter of the smooth statistic. You can see stat_smooth
for the list of all possible arguments to the method argument.
In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key)
or get(key, default)
should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }
Note also that containsKey()
or get()
are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }
. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:
mymap.find{ // "it" is the default parameter
if (it.key != "likes") return false
println "x value: ${it.value}"
return true // stop searching
}
Or with explicit parameters:
mymap.find{ key,value ->
(key != "likes") return false
println "x value: ${value}"
return true // stop searching
}
I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.
It is possible when the page itself is opened via a file:///
path.
<button onclick="window.open('file:///C:/Windows/notepad.exe')">
Launch notepad
</button>
However, the moment you put it on a webserver (even if you access it via http://localhost/
), you will get an error:
Error: Access to 'file:///C:/Windows/notepad.exe' from script denied
have you considered using a LinkedHashMap<>()..?
public static void main(String[] args) {
Map<Object, Object> handler = new LinkedHashMap<Object, Object>();
handler.put("item", "Value");
handler.put(2, "Movies");
handler.put("isAlive", true);
for (Map.Entry<Object, Object> entrY : handler.entrySet())
System.out.println(entrY.getKey() + ">>" + entrY.getValue());
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>();
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b) {
return a.getValue().compareTo(b.getValue());
}
});
}
results into an organized linked object.
item>>Value
2>>Movies
isAlive>>true
check the sorting part picked from here..
Tuesday, December 3, 2019
https://androidstudio.googleblog.com/2019/12/emulator-29211-and-amd-hypervisor-12-to.html
Via AMD Hypervisor, we added support for running the emulator on AMD CPUs on Windows:
Here are TypeScript equivalents of some common .NET delegates:
interface Action<T>
{
(item: T): void;
}
interface Func<T,TResult>
{
(item: T): TResult;
}
Everyone explained the topic very well. There is one more point i would like add about .load() method.
As per Load document if you add suffixed selector in data url then it will not execute scripts in loading content.
$(document).ready(function(){
$("#secondPage").load("mySecondHtmlPage.html #content");
})
On the other hand, after removing selector in url, scripts in new content will run. Try this example
after removing #content in url in index.html file
$(document).ready(function(){
$("#secondPage").load("mySecondHtmlPage.html");
})
There is no such in-built feature provided by other methods in discussion.
math.fabs()
always returns float, while abs()
may return integer.
you can use bc
as it can also do floats
var=$(echo "1+2"|bc)
I have no problem referring to enums directly in HTML, but in some cases there are cleaner alternatives that don't lose type-safe-ness. For instance if you choose the approach shown in my other answer, you may have declared TT in your component something like this:
public TT =
{
// Enum defines (Horizontal | Vertical)
FeatureBoxResponsiveLayout: FeatureBoxResponsiveLayout
}
To show a different layout in your HTML, you'd have an *ngIf
for each layout type, and you could refer directly to the enum in your component's HTML:
*ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"
This example uses a service to get the current layout, runs it through the async pipe and then compares it to our enum value. It's pretty verbose, convoluted and not much fun to look at. It also exposes the name of the enum, which itself may be overly verbose.
Alternatively you can do the following, and declare a more readable function in your component's .ts file :
*ngIf="isResponsiveLayout('Horizontal')"
Much cleaner! But what if someone types in 'Horziontal'
by mistake? The whole reason you wanted to use an enum in the HTML was to be typesafe right?
We can still achieve that with keyof and some typescript magic. This is the definition of the function:
isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout)
{
return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value;
}
Note the usage of FeatureBoxResponsiveLayout[string]
which converts the string value passed in to the numeric value of the enum.
This will give an error message with an AOT compilation if you use an invalid value.
Argument of type '"H4orizontal"' is not assignable to parameter of type '"Vertical" | "Horizontal"
Currently VSCode isn't smart enough to underline H4orizontal
in the HTML editor, but you'll get the warning at compile time (with --prod build or --aot switch). This also may be improved upon in a future update.
The well-described answer is already there, but I went through this SHORTER recipe:
$ brew install glfw
cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
sudo cp -R GLFW /usr/include
Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include
).
Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:
Step-1: Create two ssh key pairs:
ssh-keygen -t rsa -C "[email protected]"
Step-2: It will create two ssh keys here:
~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2
Step-3: Now we need to add these keys:
ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
- You can see the added keys list by using this command:
ssh-add -l
- You can remove old cached keys by this command:
ssh-add -D
Step-4: Modify the ssh config
cd ~/.ssh/
touch config
subl -a config
or code config
or nano config
Step-5: Add this to config file:
#Github account1
Host github.com-account1
HostName github.com
User account1
IdentityFile ~/.ssh/id_rsa_account1
#Github account2
Host github.com-account2
HostName github.com
User account2
IdentityFile ~/.ssh/id_rsa_account2
Step-6: Update your .git/config
file:
Step-6.1: Navigate to account1's project and update host:
[remote "origin"]
url = [email protected]:account1/gfs.git
If you are invited by some other user in their git Repository. Then you need to update the host like this:
[remote "origin"]
url = [email protected]:invitedByUserName/gfs.git
Step-6.2: Navigate to account2's project and update host:
[remote "origin"]
url = [email protected]:account2/gfs.git
Step-7: Update user name and email for each repository separately if required this is not an amendatory step:
Navigate to account1 project and run these:
git config user.name "account1"
git config user.email "[email protected]"
Navigate to account2 project and run these:
git config user.name "account2"
git config user.email "[email protected]"
The OP's question has been well and truly answered. However, here's a trick that may be useful in some situations: partial matching of the column name, irrespective of its position in a dataframe:
Partial matching on the name:
d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
## name1 Reported.Cases..WHO..2011. name3
## 1 NA NA NA
names(d)[grepl("Reported", names(d))] <- "name2"
## name1 name2 name3
## 1 NA NA NA
Another example: partial matching on the presence of "punctuation":
d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
## name1 Reported.Cases..WHO..2011. name3
## 1 NA NA NA
names(d)[grepl("[[:punct:]]", names(d))] <- "name2"
## name1 name2 name3
## 1 NA NA NA
These were examples I had to deal with today, I thought might be worth sharing.
There are multiple function to do this work that wrote in bottom based on priority.
Set one or more CSS properties for the set of matched elements.
$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
display: "block",
color: "red",
...
})
Display the matched elements and is roughly equivalent to calling .css("display", "block")
You can display element using .show()
instead
$("div").show()
Set one or more attributes for the set of matched elements.
If target element hasn't style
attribute, you can use this method to add inline style to element.
$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")
You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.
var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red";
// Multiple properties
div.setAttribute("style", "display:block; color:red");
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
A Simple C program to convert from little to big
#include <stdio.h>
int main() {
unsigned int little=0x1234ABCD,big=0;
unsigned char tmp=0,l;
printf(" Little endian little=%x\n",little);
for(l=0;l < 4;l++)
{
tmp=0;
tmp = little | tmp;
big = tmp | (big << 8);
little = little >> 8;
}
printf(" Big endian big=%x\n",big);
return 0;
}
If you want to retain only alphabets and spaces, you can do:
str.replace(/[^a-zA-Z ]+/g, '').replace('/ {2,}/',' ')
You can use Trim
if you want to remove from start and end.
string stringWithoutNewLine = "\n\nHello\n\n".Trim();
str.erase(str.begin() + str.size() - 1)
str.erase(str.rbegin())
does not compile unfortunately, since reverse_iterator
cannot be converted to a normal_iterator.
C++11 is your friend in this case.
In case you have a school server where the pupils worked a lot. You can just clean up the mess by:
delete from user where User != 'root' and User != 'admin';
delete from db where User != 'root' and User != 'admin';
delete from tables_priv;
delete from columns_priv;
flush privileges;
Try removing the text-alignment center and center the <h1>
or <div>
the text resides in.
h1 {
background-color:green;
margin: 0 auto;
width: 200px;
}
I was setting up cors.support.credentials to true along with cors.allowed.origins as *, which won't work.
When cors.allowed.origins is * , then cors.support.credentials should be false (default value or shouldn't be set explicitly).
For those of you on AWS (Amazon Web Services), remember to add a rule for your SSL port (in my case 443) to your security groups. I was getting this error because I forgot to open the port.
3 hours of tearing my hair out later...
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).
In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.
This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)
I think that this is as easy as I can explain it. Please, anyone is welcome to correct me or add to this.
SOAP is a message format used by disconnected systems (like across the internet) to exchange information / data. It does with XML messages going back and forth.
Web services transmit or receive SOAP messages. They work differently depending on what language they are written in.
Not sure of this is helpful but this what worked for me in Rails 4
Foo.where.not(bar: nil)
Here is the pure HTML and CSS solution.
We create a container box for navbar with position: fixed; height:100%;
Then we create an inner box with height: 100%; overflow-y: scroll;
Next, we put out content inside that box.
Here is the code:
.nav-box{_x000D_
position: fixed;_x000D_
border: 1px solid #0a2b1d;_x000D_
height:100%;_x000D_
}_x000D_
.inner-box{_x000D_
width: 200px;_x000D_
height: 100%;_x000D_
overflow-y: scroll;_x000D_
border: 1px solid #0A246A;_x000D_
}_x000D_
.tabs{_x000D_
border: 3px solid chartreuse;_x000D_
color:darkred;_x000D_
}_x000D_
.content-box p{_x000D_
height:50px;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="nav-box">_x000D_
<div class="inner-box">_x000D_
<div class="tabs"><p>Navbar content Start</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content</p></div>_x000D_
<div class="tabs"><p>Navbar content End</p></div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="content-box">_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
<p>Lorem Ipsum</p>_x000D_
</div>
_x000D_
I put the following javascript in the page header and it seems to work. It detects when the browser does not support showModalDialog and attaches a custom method that uses window.open, parses the dialog specs (height, width, scroll, etc.), centers on opener and sets focus back to the window (if focus is lost). Also, it uses the URL as the window name so that a new window is not opened each time. If you are passing window args to the modal you will need to write some additional code to fix that. The popup is not modal but at least you don't have to change a lot of code. Might need some work for your circumstances.
<script type="text/javascript">
// fix for deprecated method in Chrome 37
if (!window.showModalDialog) {
window.showModalDialog = function (arg1, arg2, arg3) {
var w;
var h;
var resizable = "no";
var scroll = "no";
var status = "no";
// get the modal specs
var mdattrs = arg3.split(";");
for (i = 0; i < mdattrs.length; i++) {
var mdattr = mdattrs[i].split(":");
var n = mdattr[0];
var v = mdattr[1];
if (n) { n = n.trim().toLowerCase(); }
if (v) { v = v.trim().toLowerCase(); }
if (n == "dialogheight") {
h = v.replace("px", "");
} else if (n == "dialogwidth") {
w = v.replace("px", "");
} else if (n == "resizable") {
resizable = v;
} else if (n == "scroll") {
scroll = v;
} else if (n == "status") {
status = v;
}
}
var left = window.screenX + (window.outerWidth / 2) - (w / 2);
var top = window.screenY + (window.outerHeight / 2) - (h / 2);
var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
targetWin.focus();
};
}
</script>
Try this
<input onclick="confirmSubmit(event);" type="button" value="Send" />
Along with this
function confirmSubmit(event){
var domElement =$(event.target);
console.log(domElement.attr('type'));
}
I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.
Schnapple asks:
Are you referring to the concept of a free database to distribute with an application, or an Access-like "single file, no installation" database?
Er, nobody who has any competence with Access application development would ever distribute a single MDB/ACCDB as application/data store. Any non-trivial Access application needs to be split into a front end with the forms/queries/reports (i.e., UI objects) and a back end (data tables only).
It's clear that what is needed here is a database application development tool like Access. None of the database-only answers are in any way responsive to that.
Please learn about Access before answering Access questions:
Access is a database application development tool that ships with a default database engine called Jet.
But an Access application can be built to work with data in almost any back end database, as long as there's an ISAM, or an ODBC or OLEDB driver for that database engine.
Microsoft itself has done a good job of obfuscating the difference between Access (development tool) and Jet (database engine), so it's not surprising that many people don't recognize the difference. But developers ought to use precise language, and when you mean the database engine, use "Jet", and when you mean the front-end development platform, use "Access".
Set file encoding to
UTF-8
and line-endings for new files to Unix, so that text files are saved in a format that is not specific to the Windows OS and most easily shared across heterogeneous developer desktops:
- Navigate to the Workspace preferences (General:Workspace)
- Change the Text File Encoding to
UTF-8
- Change the New Text File Line Delimiter to Other and choose Unix from the pick-list
- Note: to convert the line endings of an existing file, open the file in Eclipse and choose
File : Convert Line Delimiters to : Unix
Tip: You can easily convert existing file by selecting then in the Package Explorer, and then going to the menu entry File : Convert Line Delimiters to : Unix
I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities
are used like setting your config with key-value pair.
Below is an example related to Appium
used for Automating Mobile platforms like Android
and IOS
.
So we generally set DesiredCapabilities
for conveying our WebDriver
for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.
So we set our DesiredCapabilities as:
// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();
// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");
// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");
// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");
// Set android appPackage desired capability.
//You need to check for your appPackage Name for your app, you can use this app for that APK INFO
// Set your application's appPackage if you are using any other app.
capabilities.setCapability("appPackage", "com.android.appPackageName");
// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");
This DesiredCapabilities
are very specific to Appium
on Android
Platform.
For more you can refer to the official site of Selenium desiredCapabilities class
Three steps to implement your function:
Step#1 You can specify a string, including the chars A-Z and 0-9.
Like.
String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Step#2 Then if you would like to generate a random char from this candidate string. You can use
candidateChars.charAt(random.nextInt(candidateChars.length()));
Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.
Based on this, here is an example public class RandomTest {
public static void main(String[] args) {
System.out.println(generateRandomChars(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}
/**
*
* @param candidateChars
* the candidate chars
* @param length
* the number of random chars to be generated
*
* @return
*/
public static String generateRandomChars(String candidateChars, int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(candidateChars.charAt(random.nextInt(candidateChars
.length())));
}
return sb.toString();
}
}
This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.
public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{
// List of all the column names
var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();
// Get the properties from the type your are populating
var properties = typeof(T).GetProperties().ToList();
var start = worksheet.Dimension.Start;
var end = worksheet.Dimension.End;
// Resulting list
var list = new List<T>();
// Iterate the rows starting at row 2 (ie start.Row + 1)
for (int row = start.Row + 1; row <= end.Row; row++)
{
var instance = new T();
for (int col = start.Column; col <= end.Column; col++)
{
object value = worksheet.Cells[row, col].Text;
// Get the column name zero based (ie col -1)
var column = (string)header.Skip(col - 1).First().Value;
// Gets the corresponding property to set
var property = properties.Property(resolvers, column);
try
{
var propertyName = property.PropertyType.IsGenericType
? property.PropertyType.GetGenericArguments().First().FullName
: property.PropertyType.FullName;
// Implement setter code as needed.
switch (propertyName)
{
case "System.String":
property.SetValue(instance, Convert.ToString(value));
break;
case "System.Int32":
property.SetValue(instance, Convert.ToInt32(value));
break;
case "System.DateTime":
if (DateTime.TryParse((string) value, out var date))
{
property.SetValue(instance, date);
}
property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
break;
case "System.Boolean":
property.SetValue(instance, (int)value == 1);
break;
}
}
catch (Exception e)
{
// instance property is empty because there was a problem.
}
}
list.Add(instance);
}
return list;
}
// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
if (excelDate < 1)
throw new ArgumentException("Excel dates cannot be smaller than 0.");
var dateOfReference = new DateTime(1900, 1, 1);
if (excelDate > 60d)
excelDate = excelDate - 2;
else
excelDate = excelDate - 1;
return dateOfReference.AddDays(excelDate);
}
In git-config, set core.autocrlf
to true
to make git automatically convert line endings correctly for your platform, e.g. run this command for a global setting:
git config --global core.autocrlf true
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();
After doing what everyone else said above, i.e.:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... my navigation bar was still white. So I added this line:
navigationController?.navigationBar.backgroundColor = .clear
... et voila! That seemed to do the trick.
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
This is very simple and easily manage.
jQuery(document).ready(function(){
jQuery("#search").click(function(){
jQuery("#loader").show("slow");
jQuery("#response_result").hide("slow");
jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
});
});
})
function finishAjax(id,response){
jQuery("#loader").hide("slow");
jQuery('#response_result').html(unescape(response));
jQuery("#"+id).show("slow");
return true;
}
For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):
If Double.IsNaN(MyVariableName) Then
MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If
If you try to use a variable that has a NaN value you will get the following error:
Value was either too large or too small for a Decimal.
String a = "jklmn489pjro635ops";
int sum = 0;
String num = "";
boolean notFirst = false;
for (char c : a.toCharArray()) {
if (Character.isDigit(c)) {
sum = sum + Character.getNumericValue(c);
System.out.print((notFirst? " + " : "") + c);
notFirst = true;
}
}
System.out.println(" = " + sum);
You are producing a filtered list by using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still 'three'
, even if it was subsequently filtered out from the list being produced.
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == 'two':
break
If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == 'two'), None)
which will set i
to None
if there is no such matching element.
The above is not that useful a filter; your are essentially testing if the value 'two'
is in the list. You can use in
for that:
elem = 'two' if 'two' in my_list else None
@andrey answer in one line (tested in Swift 4.1):
extension UIResponder {
public var parentViewController: UIViewController? {
return next as? UIViewController ?? next?.parentViewController
}
}
usage:
let vc: UIViewController = view.parentViewController
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
This works:
<div id="start-element">Click Me</div>
$(document).on("click","#test-element",function() {
alert("click");
});
$(document).on("click","#start-element",function() {
$(this).attr("id", "test-element");
});
Here is the Fiddle
The nuget commandline tool does not come with the vsix file, it's a separate download
I suspect you're getting text/html encoding in response to your request so I believe the issue is:
dataType : 'json',
try changing it to
dataType : 'html',
From http://api.jquery.com/jQuery.get/:
dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
dd if=/dev/zero of=my_file.txt count=12345
A function to access the values:
def shape(tensor):
s = tensor.get_shape()
return tuple([s[i].value for i in range(0, len(s))])
Example:
batch_size, num_feats = shape(logits)
In some situations we have to get image from drawable or raw folder using image name instead if generated id
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Provide the following in the search dialog:
Find What: ^$\r\n
Replace With: (Leave it empty)
Click Replace All
I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.
1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)
2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.
3) add your user account to the group that has permission on the folder (mine was www-data).
Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});
I had the same problem but previous solutions not work for me. The only solution works for me is the following URL.
https://enlightensoft.wordpress.com/2013/01/15/maven-error-reading-error-in-opening-zip-file/
[EDIT]
Here I explain more about it
Suppose you got an error like below
[ERROR] error: error reading C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar; error in opening zip file
Then you have to follow these steps.
C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar
C:\Users\user\.m2\repository\org\jdom\jdom\1.1\
Then you can build your project using mvn clean install
hope this will help somebody.
In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.
Thought I'll add this one to the mix:
Collections.addAll(result, preprocessor.preprocess(lines));
This is the change that Intelli recommends.
from the javadocs:
Adds all of the specified elements to the specified collection._x000D_
Elements to be added may be specified individually or as an array._x000D_
The behavior of this convenience method is identical to that of_x000D_
<tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely_x000D_
to run significantly faster under most implementations._x000D_
_x000D_
When elements are specified individually, this method provides a_x000D_
convenient way to add a few elements to an existing collection:_x000D_
<pre>_x000D_
Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");_x000D_
</pre>
_x000D_