First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.
The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "
Source and example of polyfill here:
http://www.programmerinterview.com/index.php/html5/html5-polyfill/
solve this issue for angular
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript>
tags. That way if javaScript is off, the CSS :hover
will be used, otherwise the JavaScript effect will be used.
Example:
<noscript>
<style type="text/css">
ul#mainFilter a:hover {
/* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
function(o){ /* ...do your stuff... */ },
function(o){ /* ...do your stuff... */ });
</script>
In addition to the most upvoted answer here, one can also chain axhline
after calling plot
on a pandas
's DataFrame
.
import pandas as pd
(pd.DataFrame([1, 2, 3])
.plot(kind='bar', color='orange')
.axhline(y=1.5));
You can use angular interceptor to manage http request calls
<div class="loader">
<div id="loader"></div>
</div>
<script>
var app = angular.module("myApp", []);
app.factory('httpRequestInterceptor', ['$rootScope', '$location', function ($rootScope, $location) {
return {
request: function ($config) {
$('.loader').show();
return $config;
},
response: function ($config) {
$('.loader').hide();
return $config;
},
responseError: function (response) {
return response;
}
};
}]);
app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
function ($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
}]);
</script>
Answers above are shown how to remove an array and here is how to pull an object from an array.
Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/
db.survey.update( // select your doc in moongo
{ }, // your query, usually match by _id
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
{ multi: true } // set this to true if you want to remove multiple elements.
)
Basically you should use the java.lang.Package
class which use the classloader to give you informations about your classes.
example:
String.class.getPackage().getImplementationVersion();
Package.getPackage(this).getImplementationVersion();
Package.getPackage("java.lang.String").getImplementationVersion();
I think logback is known to use this feature to trace the JAR name/version of each class in its produced stacktraces.
see also http://docs.oracle.com/javase/8/docs/technotes/guides/versioning/spec/versioning2.html#wp90779
I had the same issue and I resolved it by closing the editor i.e. Visual Studio Code
, started it again, run ng serve
and it worked.
I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code
import {JsonObject1name, JsonObject2name} from 'your Json file path';
Now you can access JsonObject1,2 names in data section of export default part as below:
data: () => ({
schema: JsonObject1name,
schema1: JsonObject2name,
model: {}
}),
Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :
<SchemaForm id="unique name representing your Json object1" class="form" v-model="model" :schema="schema" :components="components">
</SchemaForm>
<SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
</SchemaForm>
SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.
I hope this answer helps someone. I can help if there are any questions.
Since C++11, you can copy arrays directly with std::array
:
std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B
Here is the documentation about std::array
i got solution what you are getting as per imp help=y
it is mentioned that imp is only valid for TRANSPORT_TABLESPACE
as below:
Keyword Description (Default) Keyword Description (Default)
--------------------------------------------------------------------------
USERID username/password FULL import entire file (N)
BUFFER size of data buffer FROMUSER list of owner usernames
FILE input files (EXPDAT.DMP) TOUSER list of usernames
SHOW just list file contents (N) TABLES list of table names
IGNORE ignore create errors (N) RECORDLENGTH length of IO record
GRANTS import grants (Y) INCTYPE incremental import type
INDEXES import indexes (Y) COMMIT commit array insert (N)
ROWS import data rows (Y) PARFILE parameter filename
LOG log file of screen output CONSTRAINTS import constraints (Y)
DESTROY overwrite tablespace data file (N)
INDEXFILE write table/index info to specified file
SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N)
FEEDBACK display progress every x rows(0)
TOID_NOVALIDATE skip validation of specified type ids
FILESIZE maximum size of each dump file
STATISTICS import precomputed statistics (always)
RESUMABLE suspend when a space related error is encountered(N)
RESUMABLE_NAME text string used to identify resumable statement
RESUMABLE_TIMEOUT wait time for RESUMABLE
COMPILE compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION import streams general metadata (Y)
STREAMS_INSTANTIATION import streams instantiation metadata (N)
DATA_ONLY import only data (N)
The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set
So, Please create table space for your user:
CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
From here.
For IIS7 and above, you also need to add the lines below:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'
Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:
From windows cmd you can use start
:
"dev": "start npm run start-watch && start npm run wp-server"
Every command launched this way starts in its own window.
if you just run the main.py
under the app
, just import like
from mymodule import myclass
if you want to call main.py
on other folder, use:
from .mymodule import myclass
for example:
+-- app
¦ +-- __init__.py
¦ +-- main.py
¦ +-- mymodule.py
+-- __init__.py
+-- run.py
main.py
from .mymodule import myclass
run.py
from app import main
print(main.myclass)
So I think the main question of you is how to call app.main
.
You will have to iterate step by step into nested JSON.
for e.g a JSON received from Google geocoding api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Bhopal, Madhya Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
},
"location" : {
"lat" : 23.2599333,
"lng" : 77.412615
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
}
},
"place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615
//recieve JSON in json object
JSONObject json = new JSONObject(output.toString());
JSONArray result = json.getJSONArray("results");
JSONObject result1 = result.getJSONObject(0);
JSONObject geometry = result1.getJSONObject("geometry");
JSONObject locat = geometry.getJSONObject("location");
//"iterate onto level of location";
double lat = locat.getDouble("lat");
double lng = locat.getDouble("lng");
For windows authentication
select your project.
Press F4
Disable "Anonymous Authentication" and enable "Windows Authentication"
See this excellent blog post from Aaron Bertrand about why you should change your string format and how the boundary values are handled in date range queries.
A simple solution would be to iterate through the Controls
list in a foreach
loop. Something like this:
foreach (Control child in Controls)
{
// Code that executes for each control.
}
So now you have your iterator, child
, which is of type Control
. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:
child.MouseDown += new MouseEventHandler(dragDown);
Saw this in a comment and I thought it was the simplest explanation.
filter(A, B) is the AND filter(A).filter(B) is OR
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
If we have parameter like below in our POM XML
<version>${project.version}.${svn.version}</version>
<packaging>war</packaging>
I run maven command line as follows :
mvn clean install package -Dproject.version=10 -Dsvn.version=1
In my case everything said above was OK, but I still have been receiving ORA-12545: Network Transport: Unable to resolve connect hostname
I tried to ping the Oracle machine and found out I cannot see it and added it to the hosts file. Then I received another error message ORA-12541: TNS:no listener
. After investigation I realized that pinging the same hostname from different machines getting different IP addresses(I don't know why) and I changed the IP address in my host file, which resolved the problem on 100%.
I'm bothering to write my experience as it seems obvious, but although I was sure the problem is in the above settings I totally forgot to check if I really can see the remote DB machine out there. Keep it in mind when you are out of ideas what is going on.....
These links helped me a lot:
http://www.moreajays.com/2013/03/ora-12545-connect-failed-because-target.html http://www.orafaq.com/wiki/ORA-12541
I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone! So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.
xrange uses an iterator (generates values on the fly), range returns a list.
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
What's so confusing about it... getters are functions that are called when you get a property, setters, when you set it. example, if you do
obj.prop = "abc";
You're setting the property prop, if you're using getters/setters, then the setter function will be called, with "abc" as an argument. The setter function definition inside the object would ideally look something like this:
set prop(var) {
// do stuff with var...
}
I'm not sure how well that is implemented across browsers. It seems Firefox also has an alternative syntax, with double-underscored special ("magic") methods. As usual Internet Explorer does not support any of this.
Try with:
#! /bin/bash
i=0
while read line
do
array[ $i ]="$line"
(( i++ ))
done < <(ls -ls)
echo ${array[1]}
In your version, the while
runs in a subshell, the environment variables you modify in the loop are not visible outside it.
(Do keep in mind that parsing the output of ls
is generally not a good idea at all.)
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
I've searched on Google for an app like this for a while, and I've found only options with heavy and ugly interfaces.
Then I opened Mac App Store and found CodeRunner. Very nice and clean interface. Support many languages like Python, Lua, Perl, Ruby, Javascript, etc. The price is U$10, but it's worth it!
There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check Oracle Version.
SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;
SQL> SELECT * FROM v$version;
The easiest way is to use a regular expression.
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
I would make the class final
and every method would be static
.
So the class cannot be extended and the methods can be called by Classname.methodName
. If you add members, be sure that they work thread safe ;)
This code will work like charm and use the restTemple object for rest of the code.
RestTemplate restTemplate = new RestTemplate();
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
return true;
}
};
SSLContext sslContext = null;
try {
sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
restTemplate.setRequestFactory(requestFactory);
}
Here is another way:
df[[i for i in list(df.columns) if i != '<your column>']]
You just pass all columns to be shown except of the one you do not want.
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit: "Address can have a max of 100 characters"
The placeholders I am aware of are:
Much thanks to bloudraak for initially pointing this out.
use this
SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;
tested and workes fine...
EntityFunctions
is obsolete. Consider using DbFunctions
instead.
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => DbFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
Just noting that I've just changed my config.xml to look like Sebastian's example.
Something that's also helpful in debugging all this especially if you don't do local builds... is to download the XAP/IPA/APK files as built from PhoneGap cloud and create folders for each. Rename each file with a .ZIP extension and extract the contents of each to their respective folders. So basically, you can now see what's in the package that will be shipped to the phone.
Doing this, I can see that for the Microsoft Phone platform it's largely ignoring all my attempts at replacing the icon or splash screen. If you then replace the ApplicationIcon.png and SplashScreenImage.jpg, then re-zip the folderset and rename it again as a .XAP file you can then deploy it to your phone and it will work perfectly. Somehow, there's a way of just getting the PhoneGap build to turn your icon.png and icon.jpg into those two files. Perhaps Masood's suggestion is a possibility here and utilize a hook script.
Doing the same for the .IPA file (iOS) results in several files like icon-something.png at the parent level above www. They all appear to be blank.
Doing the same for the .APK file (Android) results in a res/drawable-something set of folders and it appears to have my icon.png in each one. It's the closest to a success I can claim at the moment.
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
With the v3 API, you can easily close the InfoWindow
with the InfoWindow.close()
method. You simply need to keep a reference to the InfoWindow
object that you are using. Consider the following example, which opens up an InfoWindow
and closes it after 5 seconds:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API InfoWindow Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 500px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.36388, 131.04492),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
infowindow.open(map, marker);
setTimeout(function () { infowindow.close(); }, 5000);
</script>
</body>
</html>
If you have a separate InfoWindow
object for each Marker
, you may want to consider adding the InfoWindow
object as a property of your Marker
objects:
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker.infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
Then you would be able to open and close that InfoWindow
as follows:
marker.infowindow.open(map, marker);
marker.infowindow.close();
The same applies if you have an array of markers:
var markers = [];
marker[0] = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker[0].infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
// ...
marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();
To send a Whatsapp message from a website, use the below URL.
Here the phone and text are parameters were one of them is required.
This URL is also can be used. It displays a blank screen if there is no application found!
URL: whatsapp://send?text=The text to share!
Note: All the above will work in web, only if WhatsApp desktop app is installed
Idempotent Operations: Operations that have no side-effects if executed multiple times.
Example: An operation that retrieves values from a data resource and say, prints it
Non-Idempotent Operations: Operations that would cause some harm if executed multiple times. (As they change some values or states)
Example: An operation that withdraws from a bank account
All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.
As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.
Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.
In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.
I find this approach useful:
Create click event:
$( button ).on('click', function(e) {
let id = e.node.data.id;
$('#myModal').modal('show', {id: id});
});
Create show.bs.modal event:
$('#myModal').on('show.bs.modal', function (e) {
// access parsed information through relatedTarget
console.log(e.relatedTarget.id);
});
Extra:
Make your logic inside show.bs.modal to check whether the properties are parsed, like for instance as this:
id: ( e.relatedTarget.hasOwnProperty( 'id' ) ? e.relatedTarget.id : null )
fwiw, an example using "RestEasy" implementation of JAX-RS 2.x to build a special "trust all" client...
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import javax.ejb.Stateless;
import javax.net.ssl.SSLContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.TrustStrategy;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
@Stateless
@Path("/postservice")
public class PostService {
private static final Logger LOG = LogManager.getLogger("PostService");
public PostService() {
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {
//...object passed to the POST method...
PostDTO requestObject = new PostDTO();
requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));
//...build special "trust all" client to call POST method...
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));
//...object returned from the POST method...
PostRespDTO responseObject = response.readEntity(PostRespDTO.class);
response.close();
return responseObject;
}
//...get special "trust all" client...
private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
HttpClientBuilder builder = HttpClientBuilder.create();
NoopHostnameVerifier noop = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
}
private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
}
related Maven dependencies
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
I've used an interesting conditional formatting in a recent file of mine and thought it would be useful to others too. So this answer is meant for completeness to the previous ones.
It should demonstrate what this amazing feature is capable of, and especially how the $ thing works.
The color from D to G depend on the values in columns A, B and C. But the formula needs to check values that are fixed horizontally (user, start, end), and values that are fixed vertically (dates in row 1). That's where the dollar sign gets useful.
There are 2 users in the table, each with a defined color, respectively foo (blue) and bar (yellow).
We have to use the following conditional formatting rules, and apply both of them on the same range (D2:G3
):
=AND($A2="foo", D$1>=$B2, D$1<=$C2)
=AND($A2="bar", D$1>=$B2, D$1<=$C2)
In English, the condition means:
User is name
, and date of current cell is after start
and before end
Notice how the only thing that changes between the 2 formulas, is the name of the user. This makes it really easy to reuse with many other users!
Important: Variable rows and columns are relative to the start of the range. But fixed values are not affected.
It is easy to get confused with relative positions. In this example, if we had used the range D1:G3
instead of D2:G3
, the color formatting would be shifted 1 row up.
To avoid that, remember that the value for variable rows and columns should correspond to the start of the containing range.
In this example, the range that contains colors is D2:G3
, so the start is D2
.
User
, start
, and end
vary with rows
-> Fixed columns A B C, variable rows starting at 2: $A2
, $B2
, $C2
Dates
vary with columns
-> Variable columns starting at D, fixed row 1: D$1
I'm not sure if this is what you want but:
Directory.GetFiles(@"c:\mydir", "*.flv");
Or:
Path.GetExtension(@"c:\test.flv")
Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable
using not empty operator on my dataModel
that extends javax.faces.model.ListDataModel
Code sample:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}
I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity The following code starts this application:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
This might be useful for someone.
Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.
To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.
def compute_PMF(data):
import numpy as np
from collections import Counter
_, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
h = Counter(np.digitize(data,bins) - 1)
weights = np.asarray(list(h.values()))
weights = weights / weights.sum()
values = np.asarray(list(h.keys()))
return weights, values
####
Refs:
[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html
I got this problem when I used br tag in single product page of woocommerce. I was trying to edit the template that suddenly everything ... . that was a nightmare. My customer could kill me. try not to use this br tag anywhere.
This is not your answer and this is an alternate way to process the form submission
$('.signinform').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'index.php/user/signin', // target element(s) to be updated with server response
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
"Helvetica Neue Condensed Bold" get working with firefox:
.class {
font-family: "Helvetica Neue";
font-weight: bold;
font-stretch: condensed;
}
But it's fail with Opera.
instead of overwriting, create it as different css and call it in your element as other css(multiple css).
Something like:
.flex-control-thumbs li
{ margin: 0; }
Internal CSS:
.additional li
{width: 25%; float: left;}
<ul class="flex-control-thumbs additional"> </ul> /* assuming parent is ul */
Your HttpServletRequest
object has a getParameter(String paramName)
method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
![Clear Cache] Ctrl+Shift+Delete
http://i.stack.imgur.com/QpqhJ.jpg
Sometimes it’s necessary to do a hard refresh to see the updates take effect. But it’s unlikely that average web users know what a hard refresh is, nor can you expect them to keep refreshing the page until things straighten out.
Here’s one way to do it:<link rel="stylesheet" href="style.css?v=1.1">
Need to use top comment but also pay attention to nextLine(). To eliminate this error only call
sc.nextLine()
Once from inside your while loop
while (sc.hasNextLine()) {sc.nextLine()...}
You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.
Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.
Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.
For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.
Note : This example requires jQuery
{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
{{{buttons}}}.map((o)=>{
$("#key-{{name}}").append($(''
+'<button class="checkbox">'
+'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
+'</button>'
));
});
// A little test script
$("#key-{{{name}}} .checkbox").on("click",function(){
alert($("input",this).val());
});
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
{value:1,text:"One"},
{value:2,text:"Two"},
{value:3,text:"Three"}]'
}}
Deadlock is a common problem in multiprocessing/multiprogramming problems in OS. Say there are two processes P1, P2 and two globally shareable resource R1, R2 and in critical section both resources need to be accessed
Initially, the OS assigns R1 to process P1 and R2 to process P2. As both processes are running concurrently they may start executing their code but the PROBLEM arises when a process hits the critical section. So process R1 will wait for process P2 to release R2 and vice versa... So they will wait for forever (DEADLOCK CONDITION).
A small ANALOGY...
Your Mother(OS),
You(P1),
Your brother(P2),
Apple(R1),
Knife(R2),
critical section(cutting apple with knife).Your mother gives you the apple and the knife to your brother in the beginning.
Both are happy and playing(Executing their codes).
Anyone of you wants to cut the apple(critical section) at some point.
You don't want to give the apple to your brother.
Your brother doesn't want to give the knife to you.
So both of you are going to wait for a long very long time :)
Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent
attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)
Instead, the best approach would be to:
To allow each panel to toggle individually, on the data-toggle="collapse"
element, set the data-target
attribute to the .collapse
panel ID selector (instead of setting the data-parent
attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.
Roughly, each panel should look like this:
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"
data-toggle="collapse"
data-target="#collapseOne">
Collapsible Group Item #1
</h4>
</div>
<div id="collapseOne"
class="panel-collapse collapse">
<div class="panel-body"></div>
</div>
</div>
To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:
$('#accordion').on('show.bs.collapse', function () {
if (active) $('#accordion .in').collapse('hide');
});
Then use show
and hide
to toggle the visibility of each of the panels and data-toggle
to enable and disable the controls.
$('#collapse-init').click(function () {
if (active) {
active = false;
$('.panel-collapse').collapse('show');
$('.panel-title').attr('data-toggle', '');
$(this).text('Enable accordion behavior');
} else {
active = true;
$('.panel-collapse').collapse('hide');
$('.panel-title').attr('data-toggle', 'collapse');
$(this).text('Disable accordion behavior');
}
});
This answer is here: Python: how to suppress logging statements from third party libraries?
You can leave the default logging level for basicConfig, and then you set the DEBUG level when you get the logger for your module.
logging.basicConfig(format='%(asctime)s %(module)s %(filename)s:%(lineno)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.debug("my debug message")
Java lexicographically order:
Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):
import java.util.ArrayList;
public class HelloLambda {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Kambiz");
names.add("kambiz");
names.add("k1ambiz");
names.add("1Bmbiza");
names.add("Samantha");
names.add("Jakey");
names.add("Lesley");
names.add("Hayley");
names.add("Benjamin");
names.add("Anthony");
names.stream().
filter(e -> e.contains("a")).
sorted().
forEach(System.out::println);
}
}
1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz
Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
As a few people have mentioned, the parameters in paramMap
should be accessed using the common Map
API:
To get a snapshot of the params, when you don't care that they may change:
this.bankName = this.route.snapshot.paramMap.get('bank');
To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)
this.route.paramMap.subscribe( paramMap => {
this.bankName = paramMap.get('bank');
})
Since Angular 4, params
have been deprecated in favor of the new interface paramMap
. The code for the problem above should work if you simply substitute one for the other.
If you inject ActivatedRoute
in your component, you'll be able to extract the route parameters
import {ActivatedRoute} from '@angular/router';
...
constructor(private route:ActivatedRoute){}
bankName:string;
ngOnInit(){
// 'bank' is the name of the route parameter
this.bankName = this.route.snapshot.params['bank'];
}
If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:
ngOnInit(){
this.route.params.subscribe( params =>
this.bankName = params['bank'];
)
}
For the docs, including the differences between the two check out this link and search for "activatedroute"
varchar(max)
for SQLServer2005
varchar(65535)
for MySQL 5.0.3 and later
This will allocate storage as need and shouldn't affect performance.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js
. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';
const root = document.getElementById('someElementIdHere');
ReactDOM.render(
<Application />,
root,
);
Your <Application />
component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router
, redux
, redux-saga
, react-devtools
come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.
When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about
, you should create the route in whatever routing package you're using and create a component of About.js
with whatever information you need.
This is what worked for me
curl --form file='@filename' URL
It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.
So firstly, the only mistake the OP made was in not using the @
symbol before the file name. Secondly, my answer which uses file=...
only worked for me because the form field I was trying to do the upload for was called file
. If your form field is called something else, use that name instead.
From the curl
manpages; under the description for the option --form
it says:
This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Chances are that if you are trying to do a form upload, you will most likely want to use the @
prefix to upload the file rather than <
which uploads the contents of the file.
Now I must also add that one must be careful with using the <
symbol because in most unix shells, <
is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <
]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl
command does not behave the way you expect.
On that same note, I will also recommend quoting the @
symbol.
You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?
I say this because curl
offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data
option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.
Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.
I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.
public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
float max = 0;
if (l == null || l.length == 0) {
return null;
}
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
b.include(l[count]);
}
LatLng center = b.build().getCenter();
float distance = 0;
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
distance = distance(center, l[count]);
if (distance > max) {
max = distance;
}
}
double scale = max / 1000;
int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
return new Pair<LatLng, Integer>(center, zoom);
}
This function return Pair object which you can use like
Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));
you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.
It is time to revisit this old question.
You should not use solutions relying on toLowerCase
. They are inefficient and simply don't work in some languages (Turkish for instance). Prefer this:
['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))
Check the documentation for browser compatibility and all there is to know about the sensitivity
option.
You simply combine the ideas of a link to another page, as with href=foo.html
, and a link to an element on the same page, as with href=#bar
, so that the fragment like #bar
is written immediately after the URL that refers to another page:
<a href="foo.html#bar">Some nice link text</a>
The target is specified the same was as when linking inside one page, e.g.
<div id="bar">
<h2>Some heading</h2>
Some content
</div>
or (if you really want to link specifically to a heading only)
<h2 id="bar">Some heading</h2>
An alternative using perl would be:
perl -pe 's/(.*) (.*)$/$2/' file
where you may change \t
for whichever the delimiter of file
is
If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu
under jQuery, and I place everything there.
The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.
Also, for convenience, I usually sub-space the plugin namespace with an i
namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.
This is how it works:
// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();
Now I can just do $.miniMenu.i.globalVar = 3
or $.miniMenu.i.parseSomeStuff = function(...) {...}
whenever I need to save something globally, and I still keep it out of the global namespace.
Do this if you absolutely need to use the -Format
option:
$dateStr = Get-Date $date -Format "yyyMMdd"
However
$dateStr = $date.toString('yyyMMdd')
is probably more efficient.. :)
The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.
pthread.h
is a header for the Unix/Linux (POSIX) API for threads. A POSIX layer such as Cygwin would probably compile an app with #include <pthreads.h>
.
The native Windows threading API is exposed via #include <windows.h>
and it works slightly differently to Linux's threading.
Still, there's a replacement "glue" library maintained at http://sourceware.org/pthreads-win32/ ; note that it has some slight incompatibilities with MinGW/VS (e.g. see here).
EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:
NO you can't, atleast not in a portable way approved by the C++ standard.
The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.
If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
};
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
}
A Workaround: friend
to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.
Modified Code Sample:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
friend void MytrustedFriend();
};
void MytrustedFriend()
{
MyClass obj;
obj.c = 10; //Allowed
}
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
//Call the friend function
MytrustedFriend();
return 0;
}
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
From Mozilla Developer Network:
The border-spacing CSS property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML, but an optional second value can be used to set different horizontal and vertical spacing.
That last part is often overseen. Example:
.your-table {
border-collapse: separate; /* allow spacing between cell borders */
border-spacing: 0 5px; /* NOTE: syntax is <horizontal value> <vertical value> */
UPDATE
I now understand that the OP wants specific, seperate rows to have increased spacing. I've added a setup with tbody
elements that accomplishes that without ruining the semantics. However, I'm not sure if it is supported on all browsers. I made it in Chrome.
The example below is for showing how you can make it look like the table exists of seperate rows, full blown css sweetness. Also gave the first row more spacing with the tbody
setup. Feel free to use!
Support notice: IE8+, Chrome, Firefox, Safari, Opera 4+
.spacing-table {_x000D_
font-family: 'Helvetica', 'Arial', sans-serif;_x000D_
font-size: 15px;_x000D_
border-collapse: separate;_x000D_
table-layout: fixed;_x000D_
width: 80%;_x000D_
border-spacing: 0 5px; /* this is the ultimate fix */_x000D_
}_x000D_
.spacing-table th {_x000D_
text-align: left;_x000D_
padding: 5px 15px;_x000D_
}_x000D_
.spacing-table td {_x000D_
border-width: 3px 0;_x000D_
width: 50%;_x000D_
border-color: darkred;_x000D_
border-style: solid;_x000D_
background-color: red;_x000D_
color: white;_x000D_
padding: 5px 15px;_x000D_
}_x000D_
.spacing-table td:first-child {_x000D_
border-left-width: 3px;_x000D_
border-radius: 5px 0 0 5px;_x000D_
}_x000D_
.spacing-table td:last-child {_x000D_
border-right-width: 3px;_x000D_
border-radius: 0 5px 5px 0;_x000D_
}_x000D_
.spacing-table thead {_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
.spacing-table tbody {_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
border-spacing: 0 10px;_x000D_
}
_x000D_
<table class="spacing-table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Lead singer</th>_x000D_
<th>Band</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Bono</td>_x000D_
<td>U2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Chris Martin</td>_x000D_
<td>Coldplay</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Mick Jagger</td>_x000D_
<td>Rolling Stones</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>John Lennon</td>_x000D_
<td>The Beatles</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
On your branch - say master, pull and allow unrelated histories
git pull origin master --allow-unrelated-histories
Worked for me.
Very simple:
Use COUNT_BIG(*) AS NumStreams
For Boot 2.0.0+ this works for me: server.servlet.context-path = /api
If we need to check Edge please go head with this
if(navigator.userAgent.indexOf("Edge") > 1 ){
//do something
}
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array
)
CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$
DECLARE
ids INT[];
BEGIN
ids = string_to_array($1,',');
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 = '1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
An update
Now on windows no need to run react-native start. The packager will run automatically.
The given solution requires enough free HDD, the actual problem was the HDD memory shortage. So If you don't have an alternative server or free disk space, you need some other alternative.
I faced this error with my production server (Linode VPS) when I was running a bulk download into MySQL. Its not a proper solution but VERY QUICK FIX, which we often need in production to bring things UP FAST.
I'm using 2d cross product in my calculation to find the new correct rotation for an object that is being acted on by a force vector at an arbitrary point relative to its center of mass. (The scalar Z one.)
string management is an expensive process. keeping strings immutable allows repeated strings to be reused, rather than re-created.
This is the function I'm using for this. I combined two answers in one function for single or multiple delimiters.
function getStringBetweenDelimiters($p_string, $p_from, $p_to, $p_multiple=false){
//checking for valid main string
if (strlen($p_string) > 0) {
//checking for multiple strings
if ($p_multiple) {
// getting list of results by end delimiter
$result_list = explode($p_to, $p_string);
//looping through result list array
foreach ( $result_list AS $rlkey => $rlrow) {
// getting result start position
$result_start_pos = strpos($rlrow, $p_from);
// calculating result length
$result_len = strlen($rlrow) - $result_start_pos;
// return only valid rows
if ($result_start_pos > 0) {
// cleanying result string + removing $p_from text from result
$result[] = substr($rlrow, $result_start_pos + strlen($p_from), $result_len);
}// end if
} // end foreach
// if single string
} else {
// result start point + removing $p_from text from result
$result_start_pos = strpos($p_string, $p_from) + strlen($p_from);
// lenght of result string
$result_length = strpos($p_string, $p_to, $result_start_pos);
// cleaning result string
$result = substr($p_string, $result_start_pos+1, $result_length );
} // end if else
// if empty main string
} else {
$result = false;
} // end if else
return $result;
} // end func. get string between
For simple use (returns two):
$result = getStringBetweenDelimiters(" one two three ", 'one', 'three');
For getting each row in a table to result array :
$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);
Sometimes "ARM Translation Installer v1.1" is not working.. Here is the simple solution to install Google Play.
Go to this link: http://www.mediafire.com/download/jdn83v1v3bregyu/Galaxy+S4++HTC+One++Xperia+Z+-+4.2.2+-+with+Google+Apps+-+API+17+-+1080x1920.zip
Download the file from the link and extract to get the Android virtual device with Google Play store. The file will be in the name as “Galaxy S4 HTC One Xperia Z – 4.2.2 – with Google Apps – API 17 – 1080×1920".
Close all your Genymotion store running in the background.
Copy that extracted file in to the following folder. C:\Users\'username'\AppData\Local\Genymobile\Genymotion\deployed
After you copy you should see this path: C:\Users\'username'\AppData\Local\Genymobile\Genymotion\deployed\Galaxy S4 HTC One Xperia Z - 4.2.2 - with Google Apps - API 17 - 1080x1920
Inside the “Galaxy S4 HTC One Xperia Z – 4.2.2 – with Google Apps – API 17 – 1080×1920" folder you will see many *.vmdk and *.vbox files.
Now open VirtualBox and select Machine->Add and browse for the above folder and import the *.vbox file.
Restart Genymotion. Done.
i need to change the sheet name by the name of the file was opened
Sub Get_Data_From_File5()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim currentName As String
currentName = ActiveSheet.Name
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.csv*),*csv*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A1:g5000").Copy
ThisWorkbook.Worksheets(currentName).Range("Aw1:bc5000").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
You can simply use:
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(string.Join(",", items));
Happy coding!
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.
The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.
-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS
BEGIN
DECLARE @dateTime_min DATETIME ;
SET @dateTime_min = '1/1/1753 12:00:00 AM'
RETURN @dateTime_min ;
END ;
GO
-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
TestTableId INT IDENTITY(1, 1)
PRIMARY KEY CLUSTERED ,
Value VARCHAR(50) ,
Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;
-- INSERT VALUE INTO TABLE
INSERT INTO TestTable
( Value )
VALUES ( 'Value' ) ;
-- SELECT FROM TABLE
SELECT TestTableId ,
VALUE ,
Modified
FROM TestTable ;
-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;
If you have a full DB dump:
PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql
If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers
. You can then use this:
cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin
On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump
is incompatible with pg_restore
. With some additional keys, however, it is. WTF?
We can make it by :
Ctrl+i or Ctrl+Shift+F
Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
interface IEmployee
{
string Name
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
public static int numberOfEmployees;
private string _name;
public string Name // read-write instance property
{
get => _name;
set => _name = value;
}
private int _counter;
public int Counter // read-only instance property
{
get => _counter;
}
// constructor
public Employee() => _counter = ++numberOfEmployees;
}
Answer by Robert Longson (@RobertLongson) with modifications:
<svg width="100%" height="100%">
<defs>
<filter x="0" y="0" width="1" height="1" id="solid">
<feFlood flood-color="yellow"/>
<feComposite in="SourceGraphic" operator="xor"/>
</filter>
</defs>
<text filter="url(#solid)" x="20" y="50" font-size="50"> solid background </text>
<text x="20" y="50" font-size="50">solid background</text>
</svg>
and we have no bluring and no heavy "getBBox" :) Padding is provided by white spaces in text-element with filter. It's worked for me
Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.
However, if you want to stick to the standard, you can write something like this:
#include <stdio.h>
#include <stdlib.h>
FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);
string[fsize] = 0;
Here string
will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)
If your TextView has fixed width, alternative solution can be to create a View which will look like an underline and position it right below your TextView.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/myTextView"
android:layout_width="20dp"
android:layout_height="wrap_content"/>
<View
android:layout_width="20dp"
android:layout_height="1dp"
android:layout_below="@+id/myTextView"
android:background="#CCCCCC"/>
</RelativeLayout>
The main name change is here (img 1), but also change readme.md (img 2)
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
If you are using SQL Server:
ORDER_BY cast(registration_no as int) ASC
This should work:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))
count()
only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.
I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport)
to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does
You can read database value in to a variable and then set the variable as follows
$app_container->assign('checked_flag', $db_data=='0' ? '' : 'checked');
And in html you can just use the checked_flag variable as follows
<input type="checkbox" id="chk_test" name="chk_test" value="1" {checked_flag}>
Shallow copy with copy.copy()
#!/usr/bin/env python3
import copy
class C():
def __init__(self):
self.x = [1]
self.y = [2]
# It copies.
c = C()
d = copy.copy(c)
d.x = [3]
assert c.x == [1]
assert d.x == [3]
# It's shallow.
c = C()
d = copy.copy(c)
d.x[0] = 3
assert c.x == [3]
assert d.x == [3]
Deep copy with copy.deepcopy()
#!/usr/bin/env python3
import copy
class C():
def __init__(self):
self.x = [1]
self.y = [2]
c = C()
d = copy.deepcopy(c)
d.x[0] = 3
assert c.x == [1]
assert d.x == [3]
Documentation: https://docs.python.org/3/library/copy.html
Tested on Python 3.6.5.
I changed the configuration of maven-compiler-plugin to add executable
and fork
with value true.
<configuration>
<fork>true</fork>
<source>1.6</source>
<target>1.6</target>
<executable>C:\Program Files\Java\jdk1.6.0_18\bin\javac</executable>
</configuration>
It worked for me.
You could use robocopy:
robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E
The best solution is to create a new branch with --orphan
option as shown below
git checkout --orphan <branch name>
By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.
By default the --orphan
option doesn't remove the files in the working directory, so you can delete the working directory files by this:
git rm --cached -r
--orphan
does:
--orphan <new_branch>
Create a new orphan branch, named<new_branch>
, started from<start_point>
and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.
The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.
This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.
If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.
According to this document, add the following code to onCreate
getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION |
SYSTEM_UI_FLAG_LAYOUT_STABLE | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
Use a backslash:
echo "\"" # Prints one " character.
You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".
$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];
http://jsbin.com/ewitun/1/edit
The same with plain ES6:
$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
var t = document.getElementById(id);
if (t.scrollTop == 0) t.scrollTop=1;
while (t.scrollTop == 0) {
if (t.rows > minRows)
t.rows--; else
break;
t.scrollTop = 1;
if (t.rows < maxRows)
t.style.overflowY = "hidden";
if (t.scrollTop > 0) {
t.rows++;
break;
}
}
while(t.scrollTop > 0) {
if (t.rows < maxRows) {
t.rows++;
if (t.scrollTop == 0) t.scrollTop=1;
} else {
t.style.overflowY = "auto";
break;
}
}
}
I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.
var Obj1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
];
var Obj2 = [
{_id:2, name:'John'},
{_id:4, name:'Bobby'}
];
var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
return o1['id'] === o2['_id']
});
console.log(Obj3);
// {id:1, name:'Sandra'}
I've been testing alternatives to C# Web browser component for few days now and here is my list:
1. Using newer IE versions 8,9:
Web Browser component is IE7 not IE8? How to change this?
Pros:
Cons:
This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.
OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari
Pros:
Cons:
OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..
I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.
3. GeckoFX
Pros:
Cons:
GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.
I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:
If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.
If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:
Firefox separates lines with CHR(10) only
Internet Explorer separates lines with CHR(13) + CHR(10)
Apple (pre-OSX) separates lines with CHR(13) only
So you may need something like:
set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.
$("[id*='chkAddressChange']").click(function () {
var checked = $(this).is(':checked');
if (checked) {
$('.DisabledInputs').removeAttr('disabled');
} else {
$('.DisabledInputs').attr('disabled', 'disabled');
}
});
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
Use the timezone as shown below for a timezone-aware date time. The default is UTC:
from django.utils import timezone
today = timezone.now()
Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:
let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
db = dbConnection;
afterwards();
});
function afterwards(){
//do stuff
db.disconnect();
}
or if inside Async function:
(async ()=>{
const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient:
true })
//do stuff
db.disconnect()
})
otherwise when i was checking it in my environment it has an error.
Another option is using the map function of the purrr package.
library(purrr)
map(df,class)
You can use Equals or CompareTo.
Equals: Returns a value indicating whether two DateTime instances have the same date and time value.
CompareTo Return Value:
DateTime is nullable:
DateTime? first = new DateTime(1992,02,02,20,50,1);
DateTime? second = new DateTime(1992, 02, 02, 20, 50, 2);
if (first.Value.Date.Equals(second.Value.Date))
{
Console.WriteLine("Equal");
}
or
DateTime? first = new DateTime(1992,02,02,20,50,1);
DateTime? second = new DateTime(1992, 02, 02, 20, 50, 2);
var compare = first.Value.Date.CompareTo(second.Value.Date);
switch (compare)
{
case 1:
Console.WriteLine("this instance is later than value.");
break;
case 0:
Console.WriteLine("this instance is the same as value.");
break;
default:
Console.WriteLine("this instance is earlier than value.");
break;
}
DateTime is not nullable:
DateTime first = new DateTime(1992,02,02,20,50,1);
DateTime second = new DateTime(1992, 02, 02, 20, 50, 2);
if (first.Date.Equals(second.Date))
{
Console.WriteLine("Equal");
}
or
DateTime first = new DateTime(1992,02,02,20,50,1);
DateTime second = new DateTime(1992, 02, 02, 20, 50, 2);
var compare = first.Date.CompareTo(second.Date);
switch (compare)
{
case 1:
Console.WriteLine("this instance is later than value.");
break;
case 0:
Console.WriteLine("this instance is the same as value.");
break;
default:
Console.WriteLine("this instance is earlier than value.");
break;
}
You can use file -i file_name
to check what exactly your original file format is.
Once you get that, you can do the following:
iconv -f old_format -t utf-8 input_file -o output_file
The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
I was struggling with the same problem and found one solution. I guess it can help you.
when you run python manage.py runserver
, it will take 127.0.0.1 as default ip address and 8000 as default port number which can be configured in your python environment.
In your python setting, go to <your python env>\Lib\site-packages\django\core\management\commands\runserver.py
and set
1. default_port = '<your_port>'
2. find this under def handle and set
if not options.get('addrport'):
self.addr = '0.0.0.0'
self.port = self.default_port
Now if you run "python manage.py runserver" it will run by default on "0.0.0.0:
Enjoy coding .....
For preventing the dots in the middle of a word or after a punctuation symbol.
let parseText = function(text, limit){_x000D_
if (text.length > limit){_x000D_
for (let i = limit; i > 0; i--){_x000D_
if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {_x000D_
return text.substring(0, i) + '...';_x000D_
}_x000D_
}_x000D_
return text.substring(0, limit) + '...';_x000D_
}_x000D_
else_x000D_
return text;_x000D_
};_x000D_
_x000D_
_x000D_
console.log(parseText("1234567 890",5)) // >> 12345..._x000D_
console.log(parseText("1234567 890",8)) // >> 1234567..._x000D_
console.log(parseText("1234567 890",15)) // >> 1234567 890
_x000D_
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
such as this kind of dataframe, there are two levels of thecolumn name:
shop_id item_id date_block_num item_cnt_day
target
0 0 30 1 31
we can use this code:
df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]
result is:
shop_id item_id date_block_num target
0 0 30 1 31
I think that's up to you to show that dialog for choosing. For Gallery you'll use that code, and for Camera try this.
It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.
Support for CSS filters has landed in Webkit. So we now have a cross-browser solution.
img {_x000D_
filter: gray; /* IE6-9 */_x000D_
-webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */_x000D_
filter: grayscale(1); /* Microsoft Edge and Firefox 35+ */_x000D_
}_x000D_
_x000D_
/* Disable grayscale on hover */_x000D_
img:hover {_x000D_
-webkit-filter: grayscale(0);_x000D_
filter: none;_x000D_
}
_x000D_
<img src="http://lorempixel.com/400/200/">
_x000D_
What about Internet Explorer 10?
You can use a polyfill like gray.
To print the content of Root store:
certutil -store Root
To output content to a file:
certutil -store Root > root_content.txt
To add certificate to Root store:
certutil -addstore -enterprise Root file.cer
bobince's answer will let you know in which cases "height: XX%;" will or won't work.
If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom
. Example for square:
<div class="square-container">
<div class="square-content">
<!-- put your content in here -->
</div>
</div>
.square-container { /* any display: block; element */
position: relative;
height: 0;
padding-bottom: 100%; /* of parent width */
}
.square-content {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
}
The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video
Right now, it appears as you are on the develop branch. Do you have a develop branch on your origin? If not, try git push origin develop
. git push
will work once it knows about a develop branch on your origin.
As further reading, I'd have a look at the git-push man pages, in particular, the examples section.
I have a solution which is not specified here
z = {}
z.update(x) or z.update(y)
This will not update x as well as y. Performance? I don't think it will be terribly slow.
You can compare two date by this method also
switch ([currenttimestr compare:endtimestr])
{
case NSOrderedAscending:
// dateOne is earlier in time than dateTwo
break;
case NSOrderedSame:
// The dates are the same
break;
case NSOrderedDescending:
// dateOne is later in time than dateTwo
break;
}
I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:
what is the type of the field EventDate
, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort
example :
df1.iloc[:5]
df1.loc['A','B']
As to what cdstamper suggested instead of the table view, adding below lines in the cell's layoutSubview method works for me.
- (void)layoutSubviews
{
[super layoutSubviews];
if ([self respondsToSelector:@selector(setSeparatorInset:)])
[self setSeparatorInset:UIEdgeInsetsZero];
if ([self respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
{
[self setPreservesSuperviewLayoutMargins:NO];;
}
if ([self respondsToSelector:@selector(setLayoutMargins:)])
{
[self setLayoutMargins:UIEdgeInsetsZero];
}
}
Ran into the same issue and researched this for a few minutes.
I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.
There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.
Most of the changes are mentioned above:
Program Files
vs Program Files (x86)
In the beginning the 16/86bit files were written on, '86' Intel processors.
System32
really means System64
(on 64-bit Windows)
When developers first started working with Windows7, there were several compatibility issues where other applications where stored.
SysWOW64
really means SysWOW32
Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.
Here are two links with all the basic info you need:
Hope this clears things up!
Yes, it is. And it is supported in all major browser:
var ts = Date.parse("date string");
The only difference is that this function returns milliseconds instead of seconds, so you need to divide the result by 1000.
I prefer to use BINARY(32) since it's the optimized way!
You can place in that 32 hex digits from (00 to FF).
Therefore BINARY(32)!
Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.
There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API
It includes an answer to your question here: Updates & creation should return a resource representation
It says:
To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.
Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.
Lets assume we have a graph which has n number of nodes and m number of edges,
Adjacency Matrix: We are creating a matrix that has n number of rows and columns so in memory it will take space that is proportional to n2. Checking if two nodes named as u and v has an edge between them will take T(1) time. For example checking for (1, 2) is an edge will look like as follows in the code:
if(matrix[1][2] == 1)
If you want to identify all edges, you have to iterate over matrix at this will require two nested loops and it will take T(n2). (You may just use the upper triangular part of the matrix to determine all edges but it will be again T(n2))
Adjacency List: We are creating a list that each node also points to another list. Your list will have n elements and each element will point to a list that has number of items that is equal to number of neighbors of this node (look image for better visualization). So it will take space in memory that is proportional to n+m. Checking if (u, v) is an edge will take O(deg(u)) time in which deg(u) equals number of neighbors of u. Because at most, you have to iterate over the list that is pointed by the u. Identifying all edges will take T(n+m).
Adjacency list of example graph
You should make your choice according to your needs.
Because of my reputation I couldn't put image of matrix, sorry for that
An alternative would be to set a variable, and check whether it is defined:
SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")
Unfortunately, using %1
directly with DEFINED
doesn't work.
target.Value
will give you a Variant
type
target.Value2
will give you a Variant
type as well but a Date
is coerced to a Double
target.Text
attempts to coerce to a String
and will fail if the underlying Variant
is not coercable to a String
type
The safest thing to do is something like
Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2
And check the type of the variant using VBA.VarType(v)
before you attempt an explicit coercion.
Same info, just in table form
| r r+ w w+ a a+
------------------|--------------------------
read | + + + +
write | + + + + +
write after seek | + + +
create | + + + +
truncate | + +
position at start | + + + +
position at end | + +
where meanings are: (just to avoid any misinterpretation)
write - writing to file is allowed
create - file is created if it does not exist yet
trunctate - during opening of the file it is made empty (all content of the file is erased)
position at start - after file is opened, initial position is set to the start of the file
Note: a
and a+
always append to the end of file - ignores any seek
movements.
BTW. interesting behavior at least on my win7 / python2.7, for new file opened in a+
mode:
write('aa'); seek(0, 0); read(1); write('b')
- second write
is ignored
write('aa'); seek(0, 0); read(2); write('b')
- second write
raises IOError
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
I know this has been a while, but want to add it if it helps. The way I went about with is to have two flags in the component and two ngIfs for the corresponding two flags.
It was simple and worked well with material as ng-template and material were not working well together.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.
I had the same issue recently and researched about the subject.
The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).
Here, to keep code short, I will use jQuery:
function pollTask() {
$.ajax({
url: '/api/Polling',
async: true, // by default, it's async, but...
dataType: 'json', // or the dataType you are working with
timeout: 10000, // IMPORTANT! this is a 10 seconds timeout
cache: false
}).done(function (eventList) {
// Handle your data here
var data;
for (var eventName in eventList) {
data = eventList[eventName];
dispatcher.handle(eventName, data); // handle the `eventName` with `data`
}
}).always(pollTask);
}
It is important to remember that (from jQuery docs):
In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
It is not in any specific language, but it would be something like this:
function handleRequest () {
while (!anythingHappened() || hasTimedOut()) { sleep(2); }
return events();
}
Here, hasTimedOut
will make sure your code does not wait forever, and anythingHappened
, will check if any event happend. The sleep
is for releasing your thread to do other stuff while nothing happens. The events
will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).
It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.
Use sockets!
On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.
On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.
If you don't like this solution, try APE (Ajax Push Engine).
Hope I helped.
In my case near any line a red circle appeared with a cross and red line with a message: "No executable code found at line ..." like in Android studio gradle breakpoint No executable code found at line.
A problem appeared after updating of build.gradle
. We included Kotlin support, so a number of methods exceeded 64K. Problem lines:
buildTypes {
debug {
minifyEnabled true
Change them to:
buildTypes {
debug {
minifyEnabled false
debuggable true
Then sync a gradle with a button "Sync Project with Gradle Files". If after restarting of your application you will get an error: "Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html", then, like in The number of method references in a .dex file cannot exceed 64k API 17 add the following lines to build.gradle
:
android {
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
implementation 'com.android.support:multidex:1.0.2'
}
UPDATE
According to https://developer.android.com/studio/build/multidex.html do the following to enable multidex support below Android 5.0. Else it won't start in these devices.
Open AndroidManifest
and find tag <application>
. Near android:name=
is a reference to an Application class. Open this class. Extend Application class with MultiDexApplication
so:
public class MyApplication extends MultiDexApplication { ... }
If no Application class set, write so:
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
WHERE NOT EXISTS (
SELECT * FROM target t2, batch b2
WHERE t2.userid = b2.userid
-- ... other keyfields ...
)
;
BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
;
will do exactly what you want: either it succeeds, or it fails.
If anyone wanted to download it as well.
Here is an awesome little function that will convert an array of JSON objects to csv, then download it.
downloadCSVFromJson = (filename, arrayOfJson) => {
// convert JSON to CSV
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(arrayOfJson[0])
let csv = arrayOfJson.map(row => header.map(fieldName =>
JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
// Create link and download
var link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv));
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
Then call it like this:
this.downloadCSVFromJson(`myCustomName.csv`, this.state.csvArrayOfJson)
more_itertools
is a third-party library that implements a numeric_range
tool:
import more_itertools as mit
for x in mit.numeric_range(0, 1, 0.1):
print("{:.1f}".format(x))
Output
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
You can create lib folder inside app you press right click and select directory you named as libs its will be worked
For calculating dates and times, there are several options but I will write the simple way:
from datetime import timedelta, datetime, date
import dateutil.relativedelta
# current time
date_and_time = datetime.now()
date_only = date.today()
time_only = datetime.now().time()
# calculate date and time
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)
# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)
# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)
# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)
# calculate time
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)
result.time()
Hope it helps
create a file called spark-env.sh in spark/conf directory and add this line
SPARK_EXECUTOR_MEMORY=2000m #memory size which you want to allocate for the executor
Adding this solution with grep
and basic sh
builtins for those interested in a more portable solution (independent of bash
version; also works with plain old sh
, on non-Linux platforms etc.)
# GLOB matching
gg=svm-grid-ch
case "$gg" in
*grid*) echo $gg ;;
esac
# REGEXP
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi
# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
echo $gg
fi
Some grep
incarnations also support the -q
(quiet) option as an alternative to redirecting to /dev/null
, but the redirect is again the most portable.
I was just wanted to run some PHPUnit tests on my Mac, using Terminal. Some of the classes I wanna test was having to connect MySQL DB which was created and managed by PHPMyAdmin, and the web app I was working was working fine in the localhost. So when I ran that testcases I got the following error on my terminal:
mysqli_connect(): (HY000/2002): No such file or directory
So with the itchiness I had to resolve it and run my test I searched in few SO Q&A threads and tried out. And a combination of changes worked for me.
config.inc.php
file which relates to PHPMyAdmin.$cfg['Servers'][$i]['host']
mostly this line might have been commented out by default, if so please uncomment it.$cfg['Servers'][$i]['host'] = '127.0.0.1';
$host
parameter value in the mysqli_connect()
method to following:$_connection = mysqli_connect(**"localhost: 3306"**, $_mysql_username, $_mysql_password, $_database);
Note: This 3306
is my MySQL port number which is its default. You should better check what's your actual MySQL Port number before going to follow these steps.
And that's all. For me only these set of steps worked and nothing else. I ran my Unit Tests and it's working fine and the DB data were also updated properly according to the tests.
The closest reason I could have found is that it works because sometimes the mysqli_connect
method requires a working socket(IP Address of the DB Host along with the Port number) of the database. So if you have commented out the $cfg['Servers'][$i]['host'] = '127.0.0.1';
line or have set 'localhost' as the value in it, it ignores the port number. But if you wanna use a socket, then you have to use '127.0.0.1' or the real hostname. (for me it appears to be regardless of the default port number we really have, we have to do the above steps.) Read the following link of PHPMyAdmin for further details.
Hope this might be helpful to somebody else out there.
Cheers!
After trial and error I came up with this function, works with iframe too.
function bringElIntoView(el) {
var elOffset = el.offset();
var $window = $(window);
var windowScrollBottom = $window.scrollTop() + $window.height();
var scrollToPos = -1;
if (elOffset.top < $window.scrollTop()) // element is hidden in the top
scrollToPos = elOffset.top;
else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
if (scrollToPos !== -1)
$('html, body').animate({ scrollTop: scrollToPos });
}
It can be confusing, I agree. Try utilizing table features. I use this simple CSS trick to position modals at the center of the webpage. It has large browser support:
<div class="table">
<div class="cell">
<img src="..." alt="..." />
<span>It works now</span>
</div>
</div>
and CSS part:
.table { display: table; }
.cell { display: table-cell; vertical-align: middle; }
Note that you have to style and adjust the size of image and table container to make it work as you desire. Enjoy.
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id
is unique among all rows. Otherwise there could be multiple rows with the maximum value for id
and you'll only get one.
CSS only (no icon sets) Codepen
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<!-- <a class="navbar-brand" href="#">_x000D_
<img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
Bootstrap_x000D_
</a> -->_x000D_
<!-- https://stackoverflow.com/questions/26317679 -->_x000D_
<a class="nav-link" href="#">_x000D_
<div id="navBars">_x000D_
<input type="checkbox" /><span></span>_x000D_
<span></span>_x000D_
<span></span>_x000D_
</div>_x000D_
</a>_x000D_
<!-- /26317679 -->_x000D_
<div class="collapse navbar-collapse" id="navbarNav">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
<li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
HTML
<div id="myparent">
<div id="mychild">Test Content here</div>
</div>
CSS
#myparent {
display: table;
}
#mychild {
display: table-cell;
vertical-align: middle;
}
We set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set its value to middle. Anything inside this child div will be vertically centered.
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
Call it like this:
foo(*ob);
Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.
In your function definition you're constraining sets a and b to the same type. You can also write
public <X,Y> void myFunction(Set<X> s1, Set<Y> s2){...}
Also make sure you do not wrap parentheses around your query string like so:
SELECT Name from [USER] WHERE [UserId] in (@ids)
I had this cause a SQL Syntax error using Dapper 1.50.2, fixed by removing parentheses
SELECT Name from [USER] WHERE [UserId] in @ids
You can simulate this problem with a syntax mistake, however, %matplotlib inline
won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the ()
off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
edit/addition:
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
The following works for me
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true,useUnifiedTopology: true })
.then(res => console.log('Connected to db'));
The mongoose
version is 5.8.10
.
I believe that dropping the size of the image down to an almost icon size, say 48x48, then converting to greyscale, then taking the difference between pixels, or Delta, should work well. Because we're comparing the change in pixel color, rather than the actual pixel color, it won't matter if the image is slightly lighter or darker. Large changes will matter since pixels getting too light/dark will be lost. You can apply this across one row, or as many as you like to increase the accuracy. At most you'd have 47x47=2,209 subtractions to make in order to form a comparable Key.
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.
The CSS:
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}
I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.
Very smooth.
Consider Apache Commons IO, it has a class called FileUtils that has a listFiles
method that might be very useful in your case.
You need $event.currentTarget
instead of $event.target
.
This is my method:
def is_square(n) -> bool:
return int(n**0.5)**2 == int(n)
Take square root of number. Convert to integer. Take the square. If the numbers are equal, then it is a perfect square otherwise not.
It is incorrect for a large square such as 152415789666209426002111556165263283035677489.
I had a similar issue but I was unable to use the UserAgent
class inside the fake_useragent
module. I was running the code inside a docker container
import requests
import ujson
import random
response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]
I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.
Pure bash
, no basename
, no variable juggling. Set a string and echo
:
p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"
Output:
foo
Note: the bash
extglob option must be "on", (Ubuntu sets extglob "on" by default), if it's not, do:
shopt -s extglob
Walking through the ${p//+(*\/|.*)}
:
${p
-- start with $p.//
substitute every instance of the pattern that follows.+(
match one or more of the pattern list in parenthesis, (i.e. until item #7 below).*\/
matches anything before a literal "/
" char. |
which in this instance acts like a logical OR..*
matches anything after a literal ".
" -- that is, in bash
the ".
" is just a period char, and not a regex dot.)
end pattern list.}
end parameter expansion. With a string substitution, there's usually another /
there, followed by a replacement string. But since there's no /
there, the matched patterns are substituted with nothing; this deletes the matches.Relevant man bash
background:
${parameter/pattern/string} Pattern substitution. The pattern is expanded to produce a pat tern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the begin- ning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / fol lowing pattern may be omitted. If parameter is @ or *, the sub stitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the fol lowing sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns
var postData = "text";
$.ajax({
type: "post",
url: "url",
data: postData,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
Here's a method that works by transforming the querystring into JSON...
var link = $('a').attr('href');
if (link.indexOf("?") != -1) {
var query = link.split("?")[1];
eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");
if (query.page)
alert(unescape(query.page));
else
alert('No page parameter');
} else {
alert('No querystring');
}
I'd go with a library like the others suggest though... =)
tr:not(:contains(.... work for me
function busca(busca){
$("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
$("#listagem tr:contains('"+busca+"')").css("display", "");
}
You are confusing a Mock
with a Spy
.
In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.
In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.
What you want is
MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);
A quick example:
static class TestClass {
public String getThing() {
return "Thing";
}
public String getOtherThing() {
return getThing();
}
}
public static void main(String[] args) {
final TestClass testClass = Mockito.spy(new TestClass());
Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
System.out.println(testClass.getOtherThing());
}
Output is:
Some Other thing
NB: You should really try to mock the dependencies for the class being tested not the class itself.