The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Here is an easy solution without coding a single line.
This change makes iPad app behavior as expected otherwise the new screen is displaying in the center of the screen as a popup.
In my case using Angular and Spring Boot I solved that issue in my SecurityConfig:
http.csrf().disable().cors().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/register")
.anonymous()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
Or replace that line to:
http.csrf().disable().cors().and()
And other test option is to delete dependency from pom.xml and other code depend on it. It's like turn off security from Spring:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
You have a CryptoListPresenter _presenter
but you are never initializing it. You should either be doing that when you declare it or in your initState()
(or another appropriate but called-before-you-need-it method).
One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.
EDIT:
I see diegoveloper beat me to answering this, and that the OP asked a follow up.
@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);
, or
CryptoListPresenter _presenter;
@override
void initState() {
_presenter = new CryptoListPresenter(...);
}
Add the lines in the gradle.properties file
android.useAndroidX=true
android.enableJetifier=true
in my case i am add in manifest file `
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
application tag of course, It will work
check your application.properties
changing
spring.datasource.driverClassName=com.mysql.jdbc.Driver
to
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
worked for me. Full config:
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
1.Added these codes to your app/build.gradle:
configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:26.1.0' // the lib is old dependencies version;
}
2.Modified sdk and tools version to 28:
compileSdkVersion 28
buildToolsVersion '28.0.3'
targetSdkVersion 28
2.In your AndroidManifest.xml file, you should add two line:
<application
android:name=".YourApplication"
android:appComponentFactory="anystrings be placeholder"
tools:replace="android:appComponentFactory"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
Thanks for the answer @Carlos Santiago : Android design support library for API 28 (P) not working
If you installed with pip, to upgrade you can just use:
pip install --upgrade docker-compose
or as Mariyo states with pip3 explicitly:
pip3 install --upgrade docker-compose
On Android Studio 3.1 and above, you can push photos to the emulator, by first starting the emulator. Then select “Device File Explorer” from the menu at the top of the screen: View/Tool Window/Device File Explorer Then look in the folder titled “sdcard” and you will see a folder titled “Pictures”, click on it. Then right click it and select “Upload” and navigate to the photo on your computer, to the photo you would like to push onto the emulator. The restart the emulator. See photo below: example of uploading a photo to emulator
Your build script should match with application build.gradle dependencies.
ext {
buildToolsVersion = "27.0.3"
minSdkVersion = 16
compileSdkVersion = 27
targetSdkVersion = 26
supportLibVersion = "27.1.1"
}
dependencies {
.................
...................
implementation 'com.android.support:support-v4:27.1.0'
implementation 'com.android.support:design:27.1.0'
................
...........
}
if you want to downgrade dependencies then also downgrade supportLibVersion and buildToolsVersion .
You can get headers using below code
let main_headers = {}
this.http.post(url,
{email: this.username, password: this.password},
{'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
.subscribe(response => {
const keys = response.headers.keys();
let headers = keys.map(key => {
`${key}: ${response.headers.get(key)}`
main_headers[key] = response.headers.get(key)
}
);
});
later we can get the required header form the json object.
header_list['X-Token']
If the requested resource of the server is using Flask. Install Flask-CORS.
In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.
i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
ii) In @NgModule import sections add below lines:
HttpModule,
HttpClientModule,
So, in my case @NgModule, looks like this:
@NgModule({
declarations: [AppComponent ],
entryComponents: [ ],
imports: [
BrowserModule,
HttpModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule,
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
That's it!
You could use moment.js with Postman to give you that timestamp format.
You can add this to the pre-request script:
const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));
Then reference {{today}}
where ever you need it.
If you add this to the Collection Level Pre-request Script
, it will be run for each request in the Collection
. Rather than needing to add it to all the requests individually.
For more information about using moment
in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/
please import requestoptions from angular cors
import {RequestOptions, Request, Headers } from '@angular/http';
and add request options in your code like given below
let requestOptions = new RequestOptions({ headers:null, withCredentials:
true });
send request option in your api request
code snippet below-
let requestOptions = new RequestOptions({ headers:null,
withCredentials: true });
return this.http.get(this.config.baseUrl +
this.config.getDropDownListForProject, requestOptions)
.map(res =>
{
if(res != null)
{
return res.json();
//return true;
}
})
.catch(this.handleError);
}
and add CORS in your backend PHP code where all api request will land first.
try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me
To turn on "Install via USB" and "USB Debugging(Security changes)" need to sign in to xiaomi account then these 2 can be turned on and work with redmi as developer
Note:When turning on USB Debugging(Security changes) few security alerts will be poped up all need to be accepted to work on developer mode
Clearing the contents of storage/framework/cache
did the trick for me. Nothing else worked...
Another way to do it is using the StructField if you have multiple fields that needs to be modified.
Ex:
from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
StructField('OPEN_FLG',IntegerType(),True),
StructField('I1_GNDR_CODE',StringType(),True),
StructField('TRW_INCOME_CD_V4',StringType(),True),
StructField('ASIAN_CD',IntegerType(),True),
StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)
Output:
Before
root
|-- CLICK_FLG: string (nullable = true)
|-- OPEN_FLG: string (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)
After:
root
|-- CLICK_FLG: integer (nullable = true)
|-- OPEN_FLG: integer (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)
This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.
It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
The approved answer to this question is not valid.
You need to set headers on your server-side code
app.use((req,res,next)=>{
res.setHeader('Acces-Control-Allow-Origin','*');
res.setHeader('Acces-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
res.setHeader('Acces-Contorl-Allow-Methods','Content-Type','Authorization');
next();
})
To allow receiving & sending cookies by a CORS request successfully, do the following.
Back-end (server):
Set the HTTP header Access-Control-Allow-Credentials
value to true
.
Also, make sure the HTTP headers Access-Control-Allow-Origin
and Access-Control-Allow-Headers
are set and not with a wildcard *
.
Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None
and Secure
. See MDN documentation
For more info on setting CORS in express js read the docs here
Front-end (client): Set the XMLHttpRequest.withCredentials
flag to true
, this can be achieved in different ways depending on the request-response library used:
jQuery 1.5.1 xhrFields: {withCredentials: true}
ES6 fetch() credentials: 'include'
axios: withCredentials: true
Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.
If you for whatever reason don't avoid it. The solution is above.
It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost
(without port) is not a problem. Many thanks to Erwin for this tip!
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'your/route'
];
I imagine everyone knows what cors is and what it is for. In a simple way and for example if you use nodejs and express for the management, enable it is like this
Dependency:
https://www.npmjs.com/package/cors
app.use (
cors ({
origin: "*",
... more
})
);
And for the problem of browser requests locally, it is only to install this extension of google chrome.
Name: Allow CORS: Access-Control-Allow-Origin
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=es
This allows you to enable and disable cros in local, and problem solved.
You need jackson dependency for this serialization and deserialization.
Add this dependency:
Gradle:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")
Maven:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.
import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@SpringBootApplication
public class MockEmployeeApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MockEmployeeApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.
I ran into the same error.
NAME READY STATUS RESTARTS AGE pod/webapp 0/1 CrashLoopBackOff 5 47h
My problem was that I was trying to run two different pods with the same metadata name.
kind: Pod metadata: name: webapp labels: ...
To find all the names of your pods run: kubectl get pods
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 15 47h
then I changed the conflicting pod name and everything worked just fine.
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 17 2d webapp-release-0-5 1/1 Running 0 13m
There is a much simpler solution that will take a minute.
Done!
Now you are able to upload your release that you generated earlier :) Good luck!
I didn't need the full JDK, I just needed to make JRE work and none of the other answers provided above worked for me. Maybe it used to work, but now (1st Jul 2018) it isn't working. I just kept getting the error and the pop-up.
I eventually solved this issue by placing the following JAVA_HOME export in ~/.bash_profile:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
Hope this helps someone. I'm running Mac OS High Sierra.
I just solved this problem within my project. Turned out my connection string had a typo and differed from the valid database auth. credentials. Dumb mistake on my part, hopefully somebody else saves time by reading this.
adding mode:no-cors
can avoid cors issue in the api.
fetch(sign_in, {
mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
Your dispatcher servlet does not where to dispatch the request. Issue is your controller bean is not created/working.
Even I faced the same problem. Then added the following under mvc-config.xml
<mvc:annotation-driven/>
<context:component-scan base-package="com.nsv.jsmbaba.teamapp.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/view/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
Hope this helps
None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.
You are using multiple versions of the Android Support Libraries:
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:design:25+'
Two are 26.0.0-alpha1
, and one is using 25+
.
Pick one concrete version and use it for all three of these. Since your compileSdkVersion
is not O
, use 25.3.1
for all three of these libraries, resulting in:
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
Very easy solution (2 min to config) is to use local-ssl-proxy package from npm
The usage is straight pretty forward:
1. Install the package:
npm install -g local-ssl-proxy
2. While running your local-server
mask it with the local-ssl-proxy --source 9001 --target 9000
P.S: Replace --target 9000
with the -- "number of your port"
and --source 9001
with --source "number of your port +1"
In general, the error ValueError: Wrong number of items passed 3, placement implies 1
suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation
results['predictedY'] = predictedY
is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.
Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess()
is coming from (I'm guessing, but correct me and revise the question if this is wrong).
Now, you generate predicted values for y here:
predictedY, MSE = gp.predict(testX, eval_MSE = True)
However, as we can see from the documentation for GaussianProcess, predict()
returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets)
which, depending on testX
, could be (1000, 3)
(just to pick numbers). Thus, your predictedY
might have 3 columns.
If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
I don't think the order can be guaranteed, otherwise it would be easy enough to slice the second half of Object.entries
result and map from there.
The only (very minor) issues with the answers above is that
type StandardEnum = { [id: string]: number | string; [nu: number]: string;}
function enumToList<T extends StandardEnum> (enm: T) : { id: number; description: string }[] {
return Object.entries(enm).reduce((accum, kv) => {
if (typeof kv[1] === 'number') {
accum.push({ id: kv[1], description: kv[0] })
}
return accum
}, []) // if enum is huge, perhaps pre-allocate with new Array(entries.length / 2), however then push won't work, so tracking an index would also be required
}
You can install any current version of Anaconda. You can then make a conda environment with your particular needs from the documentation
conda create -n tensorflowproject python=3.5 tensorflow ipython
This command has a specific version for python and when this tensorflowproject environment gets updated it will upgrade to Python 3.5999999999 but never go to 3.6 . Then you switch to your environment using either
source activate tensorflowproject
for linux/mac or
activate tensorflowproject
on windows
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Close your simulator and the terminal. Open new one and go to your project, then upgrade your react-native like this:
react-native upgrade
Issue in: Infinite recursion in RCTFatal when the bundle fails to execute.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
In my case , there was a single qutation '
in project directory and after removing it resolved
if your list looks like this: [1,2,3] you can do:
lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df
to get this:
col1 col2 col3
0 1 2 3
alternatively you can create a column as follows:
import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df
to get this:
col1
0 1
1 2
2 3
In short: No, your VOLUME
instruction is not correct.
Dockerfile's VOLUME
specify one or more volumes given container-side paths. But it does not allow the image author to specify a host path. On the host-side, the volumes are created with a very long ID-like name inside the Docker root. On my machine this is /var/lib/docker/volumes
.
Note: Because the autogenerated name is extremely long and makes no sense from a human's perspective, these volumes are often referred to as "unnamed" or "anonymous".
Your example that uses a '.' character will not even run on my machine, no matter if I make the dot the first or second argument. I get this error message:
docker: Error response from daemon: oci runtime error: container_linux.go:265: starting container process caused "process_linux.go:368: container init caused "open /dev/ptmx: no such file or directory"".
I know that what has been said to this point is probably not very valuable to someone trying to understand VOLUME
and -v
and it certainly does not provide a solution for what you try to accomplish. So, hopefully, the following examples will shed some more light on these issues.
Given this Dockerfile:
FROM openjdk:8u131-jdk-alpine
VOLUME vol1 vol2
(For the outcome of this minitutorial, it makes no difference if we specify vol1 vol2
or /vol1 /vol2
— this is because the default working directory within a Dockerfile is /
)
Build it:
docker build -t my-openjdk
Run:
docker run --rm -it my-openjdk
Inside the container, run ls
in the command line and you'll notice two directories exist; /vol1
and /vol2
.
Running the container also creates two directories, or "volumes", on the host-side.
While having the container running, execute docker volume ls
on the host machine and you'll see something like this (I have replaced the middle part of the name with three dots for brevity):
DRIVER VOLUME NAME
local c984...e4fc
local f670...49f0
Back in the container, execute touch /vol1/weird-ass-file
(creates a blank file at said location).
This file is now available on the host machine, in one of the unnamed volumes lol. It took me two tries because I first tried the first listed volume, but eventually I did find my file in the second listed volume, using this command on the host machine:
sudo ls /var/lib/docker/volumes/f670...49f0/_data
Similarly, you can try to delete this file on the host and it will be deleted in the container as well.
Note: The _data
folder is also referred to as a "mount point".
Exit out from the container and list the volumes on the host. They are gone. We used the --rm
flag when running the container and this option effectively wipes out not just the container on exit, but also the volumes.
Run a new container, but specify a volume using -v
:
docker run --rm -it -v /vol3 my-openjdk
This adds a third volume and the whole system ends up having three unnamed volumes. The command would have crashed had we specified only -v vol3
. The argument must be an absolute path inside the container. On the host-side, the new third volume is anonymous and resides together with the other two volumes in /var/lib/docker/volumes/
.
It was stated earlier that the Dockerfile
can not map to a host path which sort of pose a problem for us when trying to bring files in from the host to the container during runtime. A different -v
syntax solves this problem.
Imagine I have a subfolder in my project directory ./src
that I wish to sync to /src
inside the container. This command does the trick:
docker run -it -v $(pwd)/src:/src my-openjdk
Both sides of the :
character expects an absolute path. Left side being an absolute path on the host machine, right side being an absolute path inside the container. pwd
is a command that "print current/working directory". Putting the command in $()
takes the command within parenthesis, runs it in a subshell and yields back the absolute path to our project directory.
Putting it all together, assume we have ./src/Hello.java
in our project folder on the host machine with the following contents:
public class Hello {
public static void main(String... ignored) {
System.out.println("Hello, World!");
}
}
We build this Dockerfile:
FROM openjdk:8u131-jdk-alpine
WORKDIR /src
ENTRYPOINT javac Hello.java && java Hello
We run this command:
docker run -v $(pwd)/src:/src my-openjdk
This prints "Hello, World!".
The best part is that we're completely free to modify the .java file with a new message for another output on a second run - without having to rebuild the image =)
I am quite new to Docker, and the aforementioned "tutorial" reflects information I gathered from a 3-day command line hackathon. I am almost ashamed I haven't been able to provide links to clear English-like documentation backing up my statements, but I honestly think this is due to a lack of documentation and not personal effort. I do know the examples work as advertised using my current setup which is "Windows 10 -> Vagrant 2.0.0 -> Docker 17.09.0-ce".
The tutorial does not solve the problem "how do we specify the container's path in the Dockerfile and let the run command only specify the host path". There might be a way, I just haven't found it.
Finally, I have a gut feeling that specifying VOLUME
in the Dockerfile is not just uncommon, but it's probably a best practice to never use VOLUME
. For two reasons. The first reason we have already identified: We can not specify the host path - which is a good thing because Dockerfiles should be very agnostic to the specifics of a host machine. But the second reason is people might forget to use the --rm
option when running the container. One might remember to remove the container but forget to remove the volume. Plus, even with the best of human memory, it might be a daunting task to figure out which of all anonymous volumes are safe to remove.
On CentOS Linux, Python3.6, I edited this file (make a backup copy first)
/usr/lib/python3.6/site-packages/certifi/cacert.pem
to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.
You can use this code when using vs code on debugging mode.
"runtimeArgs": ["--disable-web-security","--user-data-dir=~/ChromeUserData/"]
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Chrome disable-web-security",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}",
"runtimeArgs": [
"--disable-web-security",
"--user-data-dir=~/ChromeUserData/"
]
}
]
}
Or directly run
Chrome --disable-web-security --user-data-dir=~/ChromeUserData/
I'd prefer mapping after making sure the value is available
private String getStringIfObjectIsPresent(Optional<Object> object) {
Object ob = object.orElseThrow(MyCustomException::new);
// do your mapping with ob
String result = your-map-function(ob);
return result;
}
or one liner
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
For those who use NSwag and need a custom header:
app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
settings.GeneratorSettings.IsAspNetCore = true;
settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));
settings.GeneratorSettings.DocumentProcessors.Add(
new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme
{
Type = SwaggerSecuritySchemeType.ApiKey,
Name = "header-name",
Description = "header description",
In = SwaggerSecurityApiKeyLocation.Header
}));
});
}
Swagger UI will then include an Authorize button.
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
book_shop[ch1] -= 1
Can't beat Eric Leschinski's awesomely detailed answer, but here's a quick workaround to the original question that I don't think has been mentioned yet - put the string in a list and use .isin
instead of ==
For example:
import pandas as pd
import numpy as np
df = pd.DataFrame({"Name": ["Peter", "Joe"], "Number": [1, 2]})
# Raises warning using == to compare different types:
df.loc[df["Number"] == "2", "Number"]
# No warning using .isin:
df.loc[df["Number"].isin(["2"]), "Number"]
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
package main
import "encoding/json"
func main() {
in := []byte(`{ "votes": { "option_A": "3" } }`)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
raw["count"] = 1
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
println(string(out))
}
With Spring Security in Spring Boot 2 to configure CORS globally (e.g. enabled all request for development) you can do:
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
To make it short you could use "companion object" to get into Kotlin static world like :
companion object {
const val TAG = "tHomeFragment"
fun newInstance() = HomeFragment()
}
and to make a constant field use "const val" as in the code. but try to avoid the static classes as it is making difficulties in unit testing using Mockito!.
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;"
to the <ul class="navbar-nav">
and then add the ml-auto
class to your navbar item.
If you are using new version of Kafka e.g. 5.3.3, you can use
kafka-broker-api-versions --bootstrap-server BROKER | grep 9092
You just need to pass one of the brokers
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
i faced the same issue few days earlier for my IONIC 4 Project. when i uploaded my IPA, i got this warnings from App Store Connect.
I fixed the "Missing Purpose String in info.plist" issue, by the following steps. hope it will also work for you.
Privacy - Photo Library Usage Description
. if it's not present there, add a new one and it's value, like below image.Thanks.
You should push the new viewcontroller by using current navigation controller, not present.
self.navigationController.pushViewController(nextViewController, animated: true)
I am using Laravel 8 and just installed the fruitcake/laravel-cors
and use it in app/Http/Kernel.php
like blow:
protected $middleware = [
....
\Fruitcake\Cors\HandleCors::class,
];
note : add it to end of array like me
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
The code below will produce this plot:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]
# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]
# A dataframe
df = pd.DataFrame(data)
def CorrMtx(df, dropDuplicates = True):
# Your dataset is already a correlation matrix.
# If you have a dateset where you need to include the calculation
# of a correlation matrix, just uncomment the line below:
# df = df.corr()
# Exclude duplicate correlations by masking uper right values
if dropDuplicates:
mask = np.zeros_like(df, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set background color / chart style
sns.set_style(style = 'white')
# Set up matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Add diverging colormap from red to blue
cmap = sns.diverging_palette(250, 10, as_cmap=True)
# Draw correlation plot with or without duplicates
if dropDuplicates:
sns.heatmap(df, mask=mask, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
else:
sns.heatmap(df, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
CorrMtx(df, dropDuplicates = False)
I put this together after it was announced that the outstanding seaborn corrplot
was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap
. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of
0.95173379, try changing to -0.95173379 and you'll get this:
NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
NEW_VAR=${ENV_VAR}
else
NEW_VAR="new value"
fi
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
There are multiple possible causes for this error:
1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input()
decorator
Your html file:
<body [x]="...">
Your class file:
export class YourComponentClass {
@Input()
x: string;
...
}
(make sure you also have the parentheses)
2) Make sure you registered your component/directive/pipe classes in NgModule:
@NgModule({
...
declarations: [
...,
YourComponentClass
],
...
})
See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.
3) Also happens if you have a typo in your angular directive. For example:
<div *ngif="...">
^^^^^
Instead of:
<div *ngIf="...">
This happens because under the hood angular converts the asterisk syntax to:
<div [ngIf]="...">
In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.
x & 1
produces a value that is either1
or0
, depending on the least significant bit ofx
: if the last bit is1
, the result ofx & 1
is1
; otherwise, it is0
. This is a bitwise AND operation.
This is because 1
will be represented in bits as 00000001
. Only the last bit is set to 1
. Let's assume x
is 185
which will be represented in bits as 10111001
. If you apply a bitwise AND operation on x
with 1
this will be the result:
00000001
10111001
--------
00000001
The first seven bits of the operation result will be 0
after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x
were before, after the operation they will be 0
. But the last bit of the operand 1
is 1
and it will reveal if the last bit of operand x
was 0
or 1
. So in this example the result of the bitwise AND operation will be 1
because our last bit of x
is 1
. If the last bit would have been 0
, then the result would have been also 0
, indicating that the last bit of operand x
is 0
:
00000001
10111000
--------
00000000
x >>= 1
means "setx
to itself shifted by one bit to the right". The expression evaluates to the new value ofx
after the shift
Let's pick the example from above. For x >>= 1
this would be:
10111001
--------
01011100
And for left shift x <<= 1
it would be:
10111001
--------
01110010
Please pay attention to the note of user "dasblinkenlight" in regard to shifts.
The correct way of use forms now in Angular2 is:
<form (ngSubmit)="onSubmit()">
<label>Username:</label>
<input type="text" class="form-control" [(ngModel)]="user.username" name="username" #username="ngModel" required />
<label>Contraseña:</label>
<input type="password" class="form-control" [(ngModel)]="user.password" name="password" #password="ngModel" required />
<input type="submit" value="Entrar" class="btn btn-primary"/>
</form>
The old way doesn't works anymore
Here is an example: https://jsfiddle.net/69z2wepo/9888/
$.ajax({
type: 'POST',
url: '/some/url',
data: data
})
.done(function(result) {
this.clearForm();
this.setState({result:result});
}.bind(this)
.fail(function(jqXhr) {
console.log('failed to register');
});
It used jquery.ajax
method but you can easily replace it with AJAX based libs like axios, superagent or fetch.
I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.
<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">
This will not render the form until it is initialized.
For example this is my html template:
<select class="custom-select d-block w-100" id="genre" name="genre"
[(ngModel)]="film.genre"
#genreInput="ngModel"
required>
<option value="">Choose...</option>
<option *ngFor="let genre of genres;" [value]="genre.value">{{genre.name}}</option>
</select>
This is the field that binded with template from my Component:
// Genres of films like action or drama that will populate dropdown list.
genres: Genre[];
I fetch genres of films from server dynamically. In order do communicate with server I have created FilmService
This is the method which communicate server:
fetchGenres(): Observable<Genre[]> {
return this.client.get(WebUtils.RESOURCE_HOST_API + 'film' + '/genre') as Observable<Genre[]>;
}
Why this method returns Observable<Genre[]>
not something like Genre[]
?
JavaScript is async
and it does not wait for a method to return value after an expensive process. With expensive I mean a process that take a time to return value. Like fetching data from server. So you have to return reference of Observable and subscribe it.
For example in my Component :
ngOnInit() {
this.filmService.fetchGenres().subscribe(
val => this.genres = val
);
}
Note: if you upgrade from spring boot 1 to spring boot 2 there is a ResponseStatusException
which has a Http error code and a description.
So, you can effectively use generics they way it is intended.
The only case which is a bit challenging for me, is the response type for a status 204 (ok with no body). I tend to mark those methods as ResponseEntity<?>
, because ResponseEntity<Void>
is less predictive.
For the SpringBoot2 just add
httpResponse.setHeader("Access-Control-Expose-Headers", "custom-header1, custom-header2");
to your CORS filter implementation code to have whitelisted custom-header1
and custom-header2
etc
Or you can use reject
method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull
method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
To create a user with sudo privileges is to put the user into /etc/sudoers
, or make the user a member of a group specified in /etc/sudoers
. And to make it password-less is to additionally specify NOPASSWD
in /etc/sudoers
.
Example of /etc/sudoers
:
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL
And instead of fiddling with /etc/sudoers
file, we can create a new file in /etc/sudoers.d/
directory since this directory is included by /etc/sudoers
by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers
.
To achieve above in Ansible, refer to the following:
- name: sudo without password for wheel group
copy:
content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
dest: /etc/sudoers.d/wheel_nopasswd
mode: 0440
You may replace %wheel
with other group names like %sudoers
or other user names like deployer
.
atm they are working on that issue https://github.com/firebase/quickstart-android/issues/4
when you send a notification from the Firebase console is uses your app icon by default, and the Android system will turn that icon solid white when in the notification bar.
If you are unhappy with that result you should implement FirebaseMessagingService and create the notifications manually when you receive a message. We are working on a way to improve this but for now that's the only way.
edit: with SDK 9.8.0 add to AndroidManifest.xml
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/my_favorite_pic"/>
Had the same problem. But only on my own methods.
Just fixed it by invalidating cache: (File-> Invalidate Caches/Restart)
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
See Spring 4.2.x CORS for more information.
Without Spring Security this will work:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):
fetch(request, {mode: 'cors'});
However this still requires the server to enable CORS as well, and allow your domain to request the resource.
Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.
You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>
):
fetch(request, {mode: 'no-cors'})
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
You can use Node.js for Mobile Apps.
It works on Android devices and simulators, with pre-built binaries for armeabi-v7a, x86, arm64-v8a, x86_64. It also works on iOS, though that's outside the scope of this question.
Like JXcore, it is used to host a Node.js engine in the same process as the app, in a dedicated thread. Unlike JXcore, it is basically pure Node.js, built as a library, with a few portability fixes to run on Android. This means that it's much easier to keep the project up to date with mainline Node.js.
Plugins for Cordova and React Native are also available. The plugins provide a communication layer between the JavaScript side of those frameworks and the Node.js side. They also simplify development by taking care of a few things automatically, like packaging modules and cross-compiling native modules at build time.
Full disclosure: I work for the company that develops Node.js for Mobile Apps.
If Image folder location is public/assets/img/default.jpg.
You can try in view
<img src="{{ URL::to('/assets/img/default.jpg') }}">
There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
I figured out the solution:
Anaconda/Scripts
pip install google
No more errors.
this is server configuration, set up config.addAllowedHeader("*"); in the CorsConfiguration.
The easiest and fastest way to convert a Pandas dataframe into a png image using Anaconda Spyder IDE- just double-click on the dataframe in variable explorer, and the IDE table will appear, nicely packaged with automatic formatting and color scheme. Just use a snipping tool to capture the table for use in your reports, saved as a png:
This saves me lots of time, and is still elegant and professional.
If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.
NotSupportedException: Specified method is not supported.
For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:
public async Task<IActionResult> Index(WebhookRequest request)
{
using var reader = new StreamReader(HttpContext.Request.Body);
// this won't fix your string empty problems
// because exception will be thrown
reader.BaseStream.Seek(0, SeekOrigin.Begin);
var body = await reader.ReadToEndAsync();
// Do stuff
}
You'll need to take your model binding out of the method parameters, and manually bind yourself:
public async Task<IActionResult> Index()
{
using var reader = new StreamReader(HttpContext.Request.Body);
// You shouldn't need this line anymore.
// reader.BaseStream.Seek(0, SeekOrigin.Begin);
// You now have the body string raw
var body = await reader.ReadToEndAsync();
// As well as a bound model
var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}
It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...
In my Apache VirtualHost config file, I have added following lines :
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:
The private key is actually being exported as part of the cert.
The application pool identity running the app has access to said private key.
In our case I had to:
The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.
This CORS issue wasn't further elaborated (for other causes).
I'm having this issue currently under different reason. My front end is returning 'Access-Control-Allow-Origin' header error as well.
Just that I've pointed the wrong URL so this header wasn't reflected properly (in which i kept presume it did). localhost (front end) -> call to non secured http (supposed to be https), make sure the API end point from front end is pointing to the correct protocol.
Deploying the code after enabling CORS for both POST
and OPTIONS
worked for me.
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
I tried all above but nothing helps, at last i just figured out that under setting >> apps, device still has an entry for uninstalled application as disabled, i just uninstalled from there and it starts working.
:) might be useful for someone
Your problem might actually be on this line:
<include layout="@layout/content_contact_list" />
Android Studio gets a little confused at time and takes the include layout
for the layout
tag. What's even more frustrating is that this could work the first time, fails to work with a modification on the Java/Kotlin code later, and then work again after a tweak that forces it to rebuild the binding. You may want to replace <include>
tags with something that populates it dynamically.
public class TrackingSystemApplication {
public static void main(String[] args) {
SpringApplication.run(TrackingSystemApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200").allowedMethods("PUT", "DELETE",
"GET", "POST");
}
};
}
}
<iframe width="560" height="315" src="https://www.youtube.com/embed/ULzr7JsFp0k?list=PLF8tTShmRC6vp9YTjkVdm1qKuTimC6K3e&rel=0&autoplay=1&controls=1&loop=1" rel=0& frameborder="0" allowfullscreen></iframe>
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
I did not need to add gestureRecognizer functions for it. It was enough for me to add following code blocks at viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:
<li *ngFor="let obj of myArray">{{obj | json}}</li>
Tested and valid using Angular 4.3.2.
To change all the fonts in your plot plot + theme(text=element_text(family="mono"))
Where mono
is your chosen font.
List of default font options:
R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.
This page goes through the default fonts in detail.
I just want to add something to these great answers. If your DOM
element ins't loading in time. You can still set the value.
let Ctrl = $('#mySelectElement');
...
Ctrl.attr('value', myValue);
after that most DOM
elements that accept a value attribute should populate correctly.
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
@PostMapping(path = "/my/endpoint", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Void> handleBrowserSubmissions(MyDTO dto) throws Exception {
...
}
That way works for me
val navigationView: NavigationView = findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"
This will fix your problem <3
Also instead of adding each file manually, we could do something like:
git add --all
OR
git add -A
This will also remove any files not present or deleted (Tracked files in the current working directory which are now absent).
If you only want to add files which are tracked and have changed, you would want to do
git add -u
Solution for me is: I clean both the solution and the project. And just rebuild the project. This error happens because I tried to delete the main file (only keep library files) in the previous build so at the current build the old stuff is still kept in the built directory. That's why unresolved things happened. "unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) "
I wanted to create a MarkdownPreviewer in react as part of a project in freecodecamp. So I was desperately searching for newline characters for markdown. After trying many suggestions. I finally used \n and it worked.
Take these two scenarios:
Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );
If opt
doesn't contain a value, the two are indeed equivalent. But if opt
does contain a value, how many Foo
objects will be created?
P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
you need to initialize MockitoAnnotations.initMocks(this) method has to called to initialize annotated fields.
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
for more details see Doc
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:
openapi: 3.0.0
...
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT # optional, for documentation purposes only
security:
- bearerAuth: []
This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).
UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx
header.
Authorization
header programmatically (Swagger UI 3.x)If you use Swagger UI and, for some reason, need to add the Authorization
header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor
. This solution is for Swagger UI 3.x; UI 2.x used a different technique.
// index.html
const ui = SwaggerUIBundle({
url: "http://your.server.com/swagger.json",
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer xxxxxxx"
return req
}
})
Recently I also find the same problem and there some reasons behind this but I am giving you 3
It must work.
Assuming self
is a UIViewController
:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer
parameter can be used with a RestTemplateBuilder
:
String accessToken= "<the oauth 2 token>";
RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer "+accessToken);
return execution.execute(request, body);
})).build();
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
The problem was that my array was in type u3 i changed it to float and it worked for me . I had a dataframe with Image column having the image/pic data.Reshaping part depends to person to person and image they deal with mine had 9126 size hence it was 96*96.
a = np.array(df_train.iloc[0].Image.split(),dtype='float')
a = a.reshape(96,96)
plt.imshow(a)
UIImage(data:imageData,scale:1.0)
presuming the image's scale is 1.
In swift 4.2, use below code for get Data().
image.pngData()
First of all, if you're using method 3, you can replace those last 14 lines of code with this:
int result = myObject.calculateSomething(p1.orElse(null), p2.orElse(null));
The four variations you wrote are convenience methods. You should only use them when they're more convenient. That's also the best approach. That way, the API is very clear which members are necessary and which aren't. If you don't want to write four methods, you can clarify things by how you name your parameters:
public int calculateSomething(String p1OrNull, BigDecimal p2OrNull)
This way, it's clear that null values are allowed.
Your use of p1.orElse(null)
illustrates how verbose our code gets when using Optional, which is part of why I avoid it. Optional was written for functional programming. Streams need it. Your methods should probably never return Optional unless it's necessary to use them in functional programming. There are methods, like Optional.flatMap()
method, that requires a reference to a function that returns Optional. Here's its signature:
public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)
So that's usually the only good reason for writing a method that returns Optional. But even there, it can be avoided. You can pass a getter that doesn't return Optional to a method like flatMap(), by wrapping it in a another method that converts the function to the right type. The wrapper method looks like this:
public static <T, U> Function<? super T, Optional<U>> optFun(Function<T, U> function) {
return t -> Optional.ofNullable(function.apply(t));
}
So suppose you have a getter like this: String getName()
You can't pass it to flatMap like this:
opt.flatMap(Widget::getName) // Won't work!
But you can pass it like this:
opt.flatMap(optFun(Widget::getName)) // Works great!
Outside of functional programming, Optionals should be avoided.
Brian Goetz said it best when he said this:
The reason Optional was added to Java is because this:
return Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
.stream()
.filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
.filter(m -> Arrays.equals(m.getParameterTypes(), parameterClasses))
.filter(m -> Objects.equals(m.getReturnType(), returnType))
.findFirst()
.getOrThrow(() -> new InternalError(...));
is cleaner than this:
Method matching =
Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
.stream()
.filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
.filter(m -> Arrays.equals(m.getParameterTypes(), parameterClasses))
.filter(m -> Objects.equals(m.getReturnType(), returnType))
.getFirst();
if (matching == null)
throw new InternalError("Enclosing method not found");
return matching;
I have a workaround for this that runs the AWS CLI in the same process.
Install awscli
as python lib:
pip install awscli
Then define this function:
from awscli.clidriver import create_clidriver
def aws_cli(*cmd):
old_env = dict(os.environ)
try:
# Environment
env = os.environ.copy()
env['LC_CTYPE'] = u'en_US.UTF'
os.environ.update(env)
# Run awscli in the same process
exit_code = create_clidriver().main(*cmd)
# Deal with problems
if exit_code > 0:
raise RuntimeError('AWS CLI exited with code {}'.format(exit_code))
finally:
os.environ.clear()
os.environ.update(old_env)
To execute:
aws_cli('s3', 'sync', '/path/to/source', 's3://bucket/destination', '--delete')
Complete tutorial here
Demo link
JavaScript
$('.owl-carousel').owlCarousel({
margin: 10,
nav: true,
navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
CSS Style for navigation
.owl-carousel .nav-btn{
height: 47px;
position: absolute;
width: 26px;
cursor: pointer;
top: 100px !important;
}
.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}
.owl-carousel .prev-slide{
background: url(nav-icon.png) no-repeat scroll 0 0;
left: -33px;
}
.owl-carousel .next-slide{
background: url(nav-icon.png) no-repeat scroll -24px 0px;
right: -33px;
}
.owl-carousel .prev-slide:hover{
background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}
In my opinion, the accepted answer is confusing, since it uses a DataFrame with only missing values. I also do not like the term position-based for .iloc
and instead, prefer integer location as it is much more descriptive and exactly what .iloc
stands for. The key word is INTEGER - .iloc
needs INTEGERS.
See my extremely detailed blog series on subset selection for more
Because .ix
is deprecated we will only focus on the differences between .loc
and .iloc
.
Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each index. Let's take a look at a sample DataFrame:
df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
'height':[165, 70, 120, 80, 180, 172, 150],
'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
},
index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])
All the words in bold are the labels. The labels, age
, color
, food
, height
, score
and state
are used for the columns. The other labels, Jane
, Nick
, Aaron
, Penelope
, Dean
, Christina
, Cornelia
are used for the index.
The primary ways to select particular rows in a DataFrame are with the .loc
and .iloc
indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.
We will first talk about the .loc
indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length of the DataFrame.
There are three different inputs you can use for .loc
Selecting a single row with .loc with a string
To select a single row of data, place the index label inside of the brackets following .loc
.
df.loc['Penelope']
This returns the row of data as a Series
age 4
color white
food Apple
height 80
score 3.3
state AL
Name: Penelope, dtype: object
Selecting multiple rows with .loc with a list of strings
df.loc[['Cornelia', 'Jane', 'Dean']]
This returns a DataFrame with the rows in the order specified in the list:
Selecting multiple rows with .loc with slice notation
Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.
df.loc['Aaron':'Dean']
Complex slices can be taken in the same manner as Python lists.
Let's now turn to .iloc
. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.
There are three different inputs you can use for .iloc
Selecting a single row with .iloc with an integer
df.iloc[4]
This returns the 5th row (integer location 4) as a Series
age 32
color gray
food Cheese
height 180
score 1.8
state AK
Name: Dean, dtype: object
Selecting multiple rows with .iloc with a list of integers
df.iloc[[2, -2]]
This returns a DataFrame of the third and second to last rows:
Selecting multiple rows with .iloc with slice notation
df.iloc[:5:3]
One excellent ability of both .loc/.iloc
is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.
For example, we can select rows Jane, and Dean with just the columns height, score and state like this:
df.loc[['Jane', 'Dean'], 'height':]
This uses a list of labels for the rows and slice notation for the columns
We can naturally do similar operations with .iloc
using only integers.
df.iloc[[1,4], 2]
Nick Lamb
Dean Cheese
Name: food, dtype: object
.ix
was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.
For instance, if we want to select rows Nick
and Cornelia
along with columns 2 and 4, we could use .loc
by converting the integers to labels with the following:
col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names]
Or alternatively, convert the index labels to integers with the get_loc
index method.
labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]
The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows wher age is above 30 and return just the food
and score
columns we can do the following:
df.loc[df['age'] > 30, ['food', 'score']]
You can replicate this with .iloc
but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:
df.iloc[(df['age'] > 30).values, [2, 4]]
It is possible to use .loc/.iloc
for just column selection. You can select all the rows by using a colon like this:
df.loc[:, 'color':'score':2]
[]
, can select rows and columns too but not simultaneously.Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.
df['food']
Jane Steak
Nick Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
Using a list selects multiple columns
df[['food', 'score']]
What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.
df['Penelope':'Christina'] # slice rows by label
df[2:6:2] # slice rows by integer location
The explicitness of .loc/.iloc
for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.
df[3:5, 'color']
TypeError: unhashable type: 'slice'
We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.
If you have pip installed you can install selenium like so.
pip install selenium
or depending on your permissions:
sudo pip install selenium
For python3:
sudo pip3 install selenium
As you can see from this question pip vs easy_install pip is a more reliable package installer as it was built to improve easy_install.
I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments here. In fact pip is included out of the box with virtualenv!
I think your problem is likely related to your spring.config.location not ending the path with "/".
Quote the docs
If spring.config.location contains directories (as opposed to files) they should end in / (and will be appended with the names generated from spring.config.name before being loaded).
This issue has been recently fixed (Nov 2010) by Google, see https://code.google.com/p/analytics-issues/issues/detail?id=671. But be aware that as a good fix it brings more bugs :)
You will also have to follow the initialisation method listed here: https://developers.google.com/analytics/devguides/collection/ios/v2.
The latest instructions are going to give you a headache because it references utilities not included in the pod. Below will fail with the cocoapod
// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
to sum it up
1) in AndroidStudio's settings > compile
enable checkbox named Compile independent modules in parallel
.
2) Under Help> Edit Custom VM Options
I have:
-Xms1024m
-Xmx4096m # <------ increase this to most of your RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=440m
-XX:+UseCompressedOops
-XX:-HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8
P.S. - Some people say Note, instead of VM options, it's better to combine can be overriden by combining those lines into one line single command in gradle.properties, like this :
org.gradle.jvmargs=-Xms1024m -Xmx4096m ......
3) I have an old dual core with 4GB ram, running ubuntu. Qs command line option I have only --offline
(which specifies that the build should operate without accessing network resources). I also enabled the remaining checkboxes and now it's running ok:
Make project automatically
Use in-process building Configure on demand
Check the AndroidStudio's settings, under compile that the checkbox Compile independent modules in parallel
is enabled.
Under Vmoptions I have
-Xmx2048m -XX:MaxPermSize=1024
I have an old dual core with 4GB ram, running ubuntu. Qs commandline option I have only --offline
, which specifies that the build should operate without accessing network resources. I enabled also the remaining checkboxes:
Configure on demand
and it is running ok
Edit
It is possible to provide additional options through studio.vmoptions
located at (just replace X.X with version):
Windows: go to %USERPROFILE%\.AndroidStudioX.X\studio.exe.vmoptions
(or studio64.exe.vmoptions
)
Mac: ~/Library/Preferences/.AndroidStudioX.X/studio.vmoptions
Linux: ~/.AndroidStudioX.X/studio.vmoptions
(and/or studio64.vmoptions
)
Increasing the value of -Xmx
should help a lot. E.g
-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=256m
-XX:+UseCompressedOops
will assign 4G as max heap, with initial value of 1G
Edit:
On windows the defaults are stored into C:\Program Files\Android\Android Studio\bin\*.vmoptions
. The IDE allows you to tweak those values through Help->Edit Custom VM options
(thanks to @Code-Read
for pointing it out).
EDIT 2:
Android studio 3.5 makes easier to change same of those values. Just go to:
Preferences > Appearance & Behavior > System Settings > Memory Settings
I have resolved the problem by adding below code to manifest,
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_name" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/black" />
where ic_stat_name
created on Android Studio Right Click on res >> New >>Image Assets >> IconType(Notification)
And one more step I have to do on server php side with notification payload
$message = [
"message" => [
"notification" => [
"body" => $title ,
"title" => $message
],
"token" => $token,
"android" => [
"notification" => [
"sound" => "default",
"icon" => "ic_stat_name"
]
],
"data" => [
"title" => $title,
"message" => $message
]
]
];
Note the section
"android" => [
"notification" => [
"sound" => "default",
"icon" => "ic_stat_name"
]
]
where icon name is "icon" => "ic_stat_name"
should be the same set on manifest.
All you need to do is to add filter
method in RecyclerView.Adapter
:
public void filter(String text) {
items.clear();
if(text.isEmpty()){
items.addAll(itemsCopy);
} else{
text = text.toLowerCase();
for(PhoneBookItem item: itemsCopy){
if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
items.add(item);
}
}
}
notifyDataSetChanged();
}
itemsCopy
is initialized in adapter's constructor like itemsCopy.addAll(items)
.
If you do so, just call filter
from OnQueryTextListener
:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
adapter.filter(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
});
It's an example from filtering my phonebook by name and phone number.
There is also some simple solution without mapping node_module
directory into another volume. It's about to move installing npm packages into final CMD command.
Disadvantage of this approach:
- run
npm install
each time you run container (switching fromnpm
toyarn
might also speed up this process a bit).
FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
COPY . /worker/
CMD /bin/bash -c 'npm install; npm start'
redis:
image: redis
worker:
build: ./worker
ports:
- "9730:9730"
volumes:
- worker/:/worker/
links:
- redis
You can use following code for open actionSheet in Swift
let alert = UIAlertController(title: enter your title, message: "Enter your messgage. ", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:{ (UIAlertAction)in
print("User click Cancel button")
}))
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})
You need to edit your my.cnf
file and make sure you have the port set as in the following line:
port = 3360
Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port
is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).
Mine got solved by enabling multiDex for debug builds.
defaultConfig {
multiDexEnabled true
}
well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
First two answers here: How to enable CORS in AngularJs
if you have class with id and you want to filter by id
line1 : you mape all the id
line2: filter what is not exist in the map
Set<String> mapId = entityResponse.getEntities().stream().map(Entity::getId).collect(Collectors.toSet());
List<String> entityNotExist = entityValues.stream().filter(n -> !mapId.contains(n.getId())).map(DTOEntity::getId).collect(Collectors.toList());
I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.
CSS:
a.disabled{
pointer-events: none;
cursor: default;
}
HTML:
<a class="btn btn-info disabled">Link Text</a>
JS:
$(function(){
$('a.disabled').on('click',function(event){
event.preventDefault();
}).removeClass('disabled');
});
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
With Java 9 or higher, ifPresentOrElse
is most likely what you want:
Optional<> opt = dao.find();
opt.ifPresentOrElse(obj -> obj.setAvailable(true),
() -> logger.error("…"));
Currying using vavr or alike might get even neater code, but I haven't tried yet.
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
Stop it by-: stop-all.sh
format the namenode-: hadoop namenode -format
again start-: start-all.sh
Further to this, the return type is determined by
What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.
What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.
If there is a choice it picks one - in this example, it happens to be JSON.
This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.
My silly mistake was this: change != to ==
if(convertView != null) { // <---- HERE
LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);
TextView textView = convertView.findViewById(R.id.board_name_tv);
ImageView imageView = convertView.findViewById(R.id.board_imageview);
textView.setText(text_list.get(position));
imageView.setImageDrawable(imageAddressList.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("MESSAGE", text_list.get(pos));
setResult(98, intent);
finish();
}
});
}
return convertView;
Please use @CrossOrigin
on the backendside
in Spring boot controller (either class level or method level) as the solution for Chrome error 'No 'Access-Control-Allow-Origin'
header is present on the requested resource.'
This solution is working for me 100% ...
Example : Class level
@CrossOrigin
@Controller
public class UploadController {
----- OR -------
Example : Method level
@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RequestMapping(value = "/loadAllCars")
@ResponseBody
public List<Car> loadAllCars() {
Ref: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.
The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html
Got a reply from @Vjeux over at the React team:
Normal HTML/CSS:
<div class="something"><span>Something</span></div>
<style>
.something::after {
content: '';
position: absolute;
-webkit-filter: blur(10px) saturate(2);
}
</style>
React with inline style:
render: function() {
return (
<div>
<span>Something</span>
<div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
</div>
);
},
The trick is that instead of using ::after
in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.
For special attributes like -webkit-filter
, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter
. Note that doing {'-webkit-filter': ...}
should also work.
Try giving your Button in your main.xml a more descriptive name such as:
<Button
android:id="@+id/buttonXYZ"
(use lowercase in your xml files, at least, the first letter)
And then in your MainActivity class, declare it as:
Button buttonXYZ;
In your onCreate(Bundle savedInstanceState) method, define it as:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);
Here's a little less opinionated version of the RawHTML function posted before. It lets you:
<br />
'sRawHTML></RawHTML>
)Here's the component:
const RawHTML = ({ children, tag = 'div', nl2br = true, ...rest }) =>
React.createElement(tag, {
dangerouslySetInnerHTML: {
__html: nl2br
? children && children.replace(/\n/g, '<br />')
: children,
},
...rest,
});
RawHTML.propTypes = {
children: PropTypes.string,
nl2br: PropTypes.bool,
tag: PropTypes.string,
};
Usage:
<RawHTML>{'First · Second'}</RawHTML>
<RawHTML tag="h2">{'First · Second'}</RawHTML>
<RawHTML tag="h2" className="test">{'First · Second'}</RawHTML>
<RawHTML>{'first line\nsecond line'}</RawHTML>
<RawHTML nl2br={false}>{'first line\nsecond line'}</RawHTML>
<RawHTML></RawHTML>
Output:
<div>First · Second</div>
<h2>First · Second</h2>
<h2 class="test">First · Second</h2>
<div>first line<br>second line</div>
<div>first line
second line</div>
<div></div>
It will break on:
<RawHTML><h1>First · Second</h1></RawHTML>
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
It may be because of the installation of Cors nuget packages.
If you facing the problem after installing and enabaling cors from nuget , then you may try reinstalling web Api.
From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall
Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.
This causes every flex container to move to a new line on the screen.
Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.
This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.
Note: The placement of cross_origin should be right and dependencies are installed. On the client side, ensure to specify kind of data server is consuming. For example application/json or text/html
For me the code written below did magic
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app=Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/api/test', methods=['POST', 'GET','OPTIONS'])
@cross_origin(supports_credentials=True)
def index():
if(request.method=='POST'):
some_json=request.get_json()
return jsonify({"key":some_json})
else:
return jsonify({"GET":"GET"})
if __name__=="__main__":
app.run(host='0.0.0.0', port=5000)
A correct file upload would like this:
HTTP header:
Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ
Http body:
--ABCDEFGHIJKLMNOPQ
Content-Disposition: form-data; name="file"; filename="my.txt"
Content-Type: application/octet-stream
Content-Length: ...
<...file data in base 64...>
--ABCDEFGHIJKLMNOPQ--
and code is like this:
public void uploadFile(File file) {
try {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/file/user/upload";
HttpMethod requestMethod = HttpMethod.POST;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename(file.getName())
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);
System.out.println("file upload status code: " + response.getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}
}
A convenient option is to use javax.xml.bind.JAXB:
StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();
The [reverse] process (unmarshal) would be:
Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);
No need to deal with checked exceptions in this approach.
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
No import is necessary as long as you declare both a.go
and b.go
to be in the same package. Then, you can use go run
to recognize multiple files with:
$ go run a.go b.go
For an Ant project:
Make sure, you have servlet-api.jar in the lib folder.
For a Maven project:
Make sure, you have the dependency added in POM.xml.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Another way to do it is: Update the project facets to pick up the right server.
Check this box in this location:
Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)
Using BS 3.3.7
$("#yourModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null); // will clear all element inside modal
});
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
For swift 4 / 5 + to get topmost viewController
// MARK: UIApplication extensions
extension UIApplication {
class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return getTopViewController(base: nav.visibleViewController)
} else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
return getTopViewController(base: selected)
} else if let presented = base?.presentedViewController {
return getTopViewController(base: presented)
}
return base
}
}
How to use
if let topVC = UIApplication.getTopViewController() {
topVC.view.addSubview(forgotPwdView)
}
Sorry if I answer myself, but, at the finally, the solution of my problem was update Android Studio to the new version 0.8.14 by Canary Channel: http://tools.android.com/recent/
After the update, the problem is gone:
I leave this question here for those who have this problem in the future.
Yes there is, you can simply put <hr>
in your code where you want it, I already use it in one of my admin panel side bar.
This works in Swift for normal view controllers and even if there is a navigation controller on the screen:
let alert = UIAlertController(...)
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.presentViewController(alert, animated: true, completion: nil)
There is no impact of setting server time as UTC (for instance with jdbc:mysql://localhost:3306/myschema?serverTimezone=UTC
, even if your application/database servers are not in this timezone. The important is for the application connection string + database to be synchronized with the same time zone.
In other words, simply setting serverTimezone=UTC
with a different time zone on the database server will shift any dates extracted from the database
Please find this category. I am able to change FONT and Color of UIAlertAction and UIAlertController.
Use:
UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil];
[appearanceLabel setAppearanceFont:yourDesireFont]];
I'm new to Xcode, so it took me a few hours to figure out the issue in order to load xls file. I followed through most of the sample codes up there and none of them solves the error Xcode shown.
The solution I found was that we need to specify the 'Add to targets:' tick the project to add, when we import the xls file into Xcode by drag and drop into Project -> Supporting Files.
list.append
returns None
, since it is an in-place operation and you are assigning it back to dates_dict[key]
. So, the next time when you do dates_dict.get(key, []).append
you are actually doing None.append
. That is why it is failing. Instead, you can simply do
dates_dict.setdefault(key, []).append(date)
But, we have collections.defaultdict
for this purpose only. You can do something like this
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
This will create a new list object, if the key
is not found in the dictionary.
Note: Since the defaultdict
will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.
The top solution above:
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
didnt'work for me when I called it in viewDidAppear of the presented view controller. However it did work when I called it in preparForSegue in the presenting view controller.
(Sorry, not enough reputation points to comment on that solution, so I had to add it like this)
just remember there is a pycache folder hidden inside the migrations folder so if you change your models and delete all your migration files you MUST delete the pycache folder also.
The only one you should not delete is your init file.
Hope this helps
CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');
From official documentation
Warning: Do not filter files with binary content like images! This will most likely result in corrupt output.
If you have both text files and binary files as resources it is recommended to have two separated folders. One folder src/main/resources (default) for the resources which are not filtered and another folder src/main/resources-filtered for the resources which are filtered.
<project>
...
<build>
...
<resources>
<resource>
<directory>src/main/resources-filtered</directory>
<filtering>true</filtering>
</resource>
...
</resources>
...
</build>
...
</project>
Now you can put those files into src/main/resources which should not filtered and the other files into src/main/resources-filtered.
As already mentioned filtering binary files like images,pdf`s etc. could result in corrupted output. To prevent such problems you can configure file extensions which will not being filtered.
Most certainly, You have in your directory files that cannot be filtered. So you have to specify the extensions that has not be filtered.
In the general case, the answer is No.
However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.
In Visual Studio, this option is located here:
Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic
There, you can check the Thrown box.
For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue>
and not tied directly to Dictionary<TKey, TValue>
, you can implement your own dictionary class which provides this behavior.
In my case, I tried to start the listener via console:
> lsnrctl star
This command printed the following error:
TNS-12560: TNS:protocol adapter error
TNS-00583: Valid node checking: unable to parse configuration parameters
So, I performed the following actions:
listener.ora
or sqlnet.ora
file contains special characterslistener.ora
or sqlnet.ora` file are in wrong format or syntaxlistener.ora
or sqlnet.ora
file have some left justified parenthesis which are not accepted by oracle parser.Have a look at these files and check the proper syntax. If possible remove/rename sqlnet.ora and try to restart the listener. Or remove/rename both listener.ora or sqlnet.ora file and recreate it properly. These will defenitely resolve the issue.
Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)
All implementation for topViewController here are not fully supporting cases when you have UINavigationController
or UITabBarController
, for those two you need a bit different handling:
For UITabBarController
and UINavigationController
you need a different implementation.
Here is code I'm using to get topMostViewController:
protocol TopUIViewController {
func topUIViewController() -> UIViewController?
}
extension UIWindow : TopUIViewController {
func topUIViewController() -> UIViewController? {
if let rootViewController = self.rootViewController {
return self.recursiveTopUIViewController(from: rootViewController)
}
return nil
}
private func recursiveTopUIViewController(from: UIViewController?) -> UIViewController? {
if let topVC = from?.topUIViewController() { return recursiveTopUIViewController(from: topVC) ?? from }
return from
}
}
extension UIViewController : TopUIViewController {
@objc open func topUIViewController() -> UIViewController? {
return self.presentedViewController
}
}
extension UINavigationController {
override open func topUIViewController() -> UIViewController? {
return self.visibleViewController
}
}
extension UITabBarController {
override open func topUIViewController() -> UIViewController? {
return self.selectedViewController ?? presentedViewController
}
}
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
Final Working Solution for me (Highlighted the tages in the sample code):
xmlns:tools
line in the manifest tagtools:replace
in the application tagExample:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pagination.yoga.com.tamiltv"
**xmlns:tools="http://schemas.android.com/tools"**
>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
**tools:replace="android:icon,android:theme"**
>
Here is a quick summary of the segues and an example for each type.
Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail
Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout
Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings
Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar
Custom - You may implement your own custom segue and have control over its behavior
The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.
For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.
I had this with an UIAlertControllerStyleActionSheet giving the user the option to take a photo with the camera or use one from library.
I tried a symbolic breakpoint on the error message
That showed me the error is produced by the intern use of a UICollectionView during presentation
[self presentViewController:alert animated:YES completion:nil];
I fixed this by explixitly setting the frame before presenting
[alert setPreferredContentSize: alert.view.frame.size];
Here is the complete methode that is working without the error
-(void)showImageSourceAlertFromSender:(id)sender{
UIButton *senderButton = (UIButton*)sender;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[self takePhoto];
}];
UIAlertAction *libraryAction = [UIAlertAction actionWithTitle:@"Library" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[self selectPhotoFromLibraryFromSender:sender];
}];
[alert addAction:cameraAction];
[alert addAction:libraryAction];
alert.popoverPresentationController.delegate = self;
alert.popoverPresentationController.sourceRect = senderButton.frame;
alert.popoverPresentationController.sourceView = self.view;
[alert setPreferredContentSize: alert.view.frame.size];
[self presentViewController:alert animated:YES completion:^(){
}];}
Use make_response
of Flask something like
@app.route("/")
def home():
resp = make_response("hello") #here you could use make_response(render_template(...)) too
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
From flask docs,
flask.make_response(*args)
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.
Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator()
instead of join()
:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
joinWithSeparator
is defined as an extension on SequenceType
extension SequenceType where Generator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
@warn_unused_result
public func joinWithSeparator(separator: String) -> String
}
This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:
./gradlew wrapper --gradle-version <version> --distribution-type all
Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.
Pros:
Cons:
Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.
@RequestBody MultipartFile[] submissions
should be
@RequestParam("file") MultipartFile[] submissions
The files are not the request body, they are part of it and there is no built-in HttpMessageConverter
that can convert the request to an array of MultiPartFile
.
You can also replace HttpServletRequest
with MultipartHttpServletRequest
, which gives you access to the headers of the individual parts.
If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.days
accessor you need either df.astype
or pd.to_numeric
Either of these options should help:
df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')
or
df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')
OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world
function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin
header is what we should concern. So, thing is very simple, just like bellow:
@blueprint.after_request # blueprint can also be app~~
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
return response
That is all~~
If you want to allow all the fonts from a folder for a specific domain then you can use this:
<location path="assets/font">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:3000" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
where assets/font is the location where all fonts are and http://localhost:3000 is the location which you want to allow.
There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:
static long values = Long.parseUnsignedLong("123456789012345678");
but this is not declaration of the variable.
Optional parameters are kind of like a macro substitution from what I understand. They are not really optional from the method's point of view. An artifact of that is the behavior you see where you get different results if you cast to an interface.
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:
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
I assume you don't want to rebind the event, but call the handler.
You can use trigger()
to trigger events:
$('#billing_state_id').trigger('change');
If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:
function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
Also note that live()
is deprecated, on()
is the new hotness.
I've implemented an async version of the accepted answer like so - and it seems to work nicely - any comments?
public static async Task DoAsync(
Action action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
DoAsync<object>(() =>
{
action();
return null;
}, retryInterval, maxAttemptCount);
}
public static async Task<T> DoAsync<T>(
Func<Task<T>> action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
var exceptions = new List<Exception>();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
Thread.Sleep(retryInterval);
}
return await action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
And, call it simply like this:
var result = await Retry.DoAsync(() => MyAsyncMethod(), TimeSpan.FromSeconds(5), 4);
array[index] == 'undefined'
compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined'
, which compares the type.
I was getting same error with python-2. I wanted to run python-2 jupyter notebook session but by default I was getting python-3. So easiest work around is open Anaconda terminal for python-2 and type 'jupyter notebook' , it will launch jupyter-notebook session without any problem. Similary it could be tried with python-3
I had same problem to find a way to check whether ASP.NET 4.5 is on the Server. Because v4.5 is in place replace to v4.0, if you look at c:\windows\Microsoft.NET\Framework, you will not see v4.5 folder. Actually there is a simple way to see the version installed in the machine. Under Windows Server 2008 or Windows 7, just go to control panel -> Programs and Features, you will find "Microsoft .NET Framework 4.5" if it is installed.
Let's begin with D of SOLID and look at DI and IoC from Scott Millett's book "Professional ASP.NET Design Patterns":
Dependency Inversion Principle (DIP)
The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation.
Dependency Injection (DI) and Inversion of Control (IoC)
Closely linked to the DIP are the DI principle and the IoC principle. DI is the act of supplying a low level or dependent class via a constructor, method, or property. Used in conjunction with DI, these dependent classes can be inverted to interfaces or abstract classes that will lead to loosely coupled systems that are highly testable and easy to change.
In IoC, a system’s flow of control is inverted compared to procedural programming. An example of this is an IoC container, whose purpose is to inject services into client code without having the client code specifying the concrete implementation. The control in this instance that is being inverted is the act of the client obtaining the service.
Millett,C (2010). Professional ASP.NET Design Patterns. Wiley Publishing. 7-8.
I found this on web.
http://www.opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c
int strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.
You can also copy packages installed on global python to virtualenv.
cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/
<View style={{flexDirection:'row'}}> <Text style={{ flex: number }}> You miss fdddddd dddddddd You miss fdd </Text> </View>
{ flex: aNumber } is all you need!
Just set 'flex' to a number that suit for you. And then the text will wrap.
The jQuery UI sortable
feature includes a serialize
method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id
. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize
option, it will create a POST query string like this: item[]=1&item[]=2
etc. So if you make use - for example - your database IDs in the id
attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)
time() + 24*60*60;
Just ad this in the select :
DATE_FORMAT($yourDate, \'%X %V\') as week
And
group_by(week);
If you want connect to user@'%'
from localhost use mysql -h192.168.0.1 -uuser -p
.
As this error comes when you are trying to insert non-numeric value into a numeric column in db it seems that your last field might be numeric and you are trying to send it as a string in database. check your last value.
when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.
if you set Visibility=Gone then you have to initialize the component..like
eg Button _mButton = new Button(this);
_mButton = (Button)findViewByid(R.id.mButton);
so it will take more time as compared to Visibility = invisible.
This solved my problem, from preventign that an event gets fired by a children:
doSmth(){_x000D_
// what ever_x000D_
}
_x000D_
<div (click)="doSmth()">_x000D_
<div (click)="$event.stopPropagation()">_x000D_
<my-component></my-component>_x000D_
</div>_x000D_
</div>
_x000D_
Latest version of Geany supports it (only on Linux, though)
Brief and Useful:
/**
* @param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
* a <code>Boolean</code>, a <code>Number</code>,
* a <code>null</code> or a <code>JSONObject.NULL</code>.
* @return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
* a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
*/
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
if (jsonThing instanceof JSONArray) {
final ArrayList<Object> list = new ArrayList<>();
final JSONArray jsonArray = (JSONArray) jsonThing;
final int l = jsonArray.length();
for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
return list;
}
if (jsonThing instanceof JSONObject) {
final HashMap<String, Object> map = new HashMap<>();
final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
while (keysItr.hasNext()) {
final String key = keysItr.next();
map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
}
return map;
}
if (JSONObject.NULL.equals(jsonThing)) return null;
return jsonThing;
}
Thank @Vikas Gupta.
unique_ptr
's like that.I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.
unique_ptr
constructor parameters if you have publicly-exposed unique_ptr
members.unique_ptr
s wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*>
as suggested in the Core Guidelines.
Only if the purpose of your class is to hold unique_ptr
's, and have others use those unique_ptr
's as such - only then is it reasonable for your constructor or methods to take them.
unique_ptr
s internallyUsing unique_ptr
for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.
[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this
That ability was actually just added, and you need the Subversion version for it. You can see the example code here.
I am just updating to say that there's a better example online now. Still need the Subversion version though, there hasn't been a release with this yet.
[edit] Matplotlib 0.99.0 RC1 was just released, and includes this capability.
From Bootstrap's docs about the remote
option;
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's
load
method and injected into the.modal-content
div. If you're using the data-api, you may alternatively use thehref
attribute to specify the remote source. An example of this is shown below:<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
That's the .modal-content
div, not .modal-body
. If you want to put content inside .modal-body
then you need to do that with custom javascript.
So I would call jQuery.load
programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.
To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal
event to load content into the .modal-body
div.
HTML Link/Button
<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>
jQuery
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
I developed an R package that will do this, borrowing from the suggestions above. The package is called called mise
, as in "mise en place." You can install and run it using
install.packages("mise")
library(mise)
mise()
Note that mise()
also deletes all variables and functions and closes all figures by default. To just clear the console, use mise(vars = FALSE, figs = FALSE)
.
After calling GroupBy
, you get a series of groups IEnumerable<Grouping>
, where each Grouping itself exposes the Key
used to create the group and also is an IEnumerable<T>
of whatever items are in your original data set. You just have to call Count()
on that Grouping to get the subtotal.
foreach(var line in data.GroupBy(info => info.metric)
.Select(group => new {
Metric = group.Key,
Count = group.Count()
})
.OrderBy(x => x.Metric))
{
Console.WriteLine("{0} {1}", line.Metric, line.Count);
}
I'm assuming you already have a list/array of some class
that looks like
class UserInfo {
string name;
int metric;
..etc..
}
...
List<UserInfo> data = ..... ;
When you do data.GroupBy(x => x.metric)
, it means "for each element x
in the IEnumerable defined by data
, calculate it's .metric
, then group all the elements with the same metric into a Grouping
and return an IEnumerable
of all the resulting groups. Given your example data set of
<DATA> | Grouping Key (x=>x.metric) |
joe 1 01/01/2011 5 | 1
jane 0 01/02/2011 9 | 0
john 2 01/03/2011 0 | 2
jim 3 01/04/2011 1 | 3
jean 1 01/05/2011 3 | 1
jill 2 01/06/2011 5 | 2
jeb 0 01/07/2011 3 | 0
jenn 0 01/08/2011 7 | 0
it would result in the following result after the groupby:
(Group 1): [joe 1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb 0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim 3 01/04/2011 1]
i think best approach is to make a common method and call in hover and click events.
Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.
Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.
I'm not about to repeat all the other answers, but there's one aspect that I haven't yet seen mentioned - it's the story of disappearing data. I don't know where to find it, but...
Basically it's about a web application that mysteriously every few night did loose all its data and nobody knew why. Inspecting the Logs later revealed that the site was found by google or another arbitrary spider, that happily GET (read: GOT) all the links it found on the site - including the "delete this entry" and "are you sure?" links.
Actually - part of this has been mentioned. This is the story behind "don't change data on GET but only on POST". Crawlers will happily follow GET, never POST. Even robots.txt doesn't help against misbehaving crawlers.
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
I would say you have two options:
to get all parent divs styled with 100%
height (including body and html)
to use absolute positioning for one of the parent divs (for example #content
) and then all child divs set to height 100%
You should always use $array[]
if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.
Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.
This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.
If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.
You can use like this(Though the random number generator logic is not upto the mark)
public class WorkSheet {
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
public static void main(String args[]) {
WorkSheet test = new WorkSheet();
test.inputData("mango", 5);
test.inputData("apple", 2);
test.inputData("grapes", 2);
test.inputData("peach", 3);
test.displayData();
}
public void displayData(){
for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(int fruitNo : entry.getValue()){
System.out.print(fruitNo+" ");
}
System.out.println();
}
}
public void inputData(String name ,int number) {
Random rndData = new Random();
ArrayList<Integer> fruit = new ArrayList<Integer>();
for(int i=0 ; i<number ; i++){
fruit.add(rndData.nextInt(10));
}
map.put(name, fruit);
}
}
grapes | 7 5
apple | 9 5
peach | 5 5 8
mango | 4 7 1 5 5
SQL Loader helps load csv files into tables: SQL*Loader
If you want sqlplus only, then it gets a bit complicated. You need to locate your sqlloader script and csv file, then run the sqlldr command.
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
g _ goes to the last non-whitespace character.
g $ goes to the end of the screen line (when a buffer line is wrapped across multiple screen lines)
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
a = "MandY"
alow = a.lower()
if "mandy" in alow:
print "true"
work around
Overloading methods is tricky in Python. However, there could be usage of passing the dict, list or primitive variables.
I have tried something for my use cases, and this could help here to understand people to overload the methods.
Let's take your example:
A class overload method with call the methods from different class.
def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):
Pass the arguments from the remote class:
add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}
Or
add_bullet(sprite = 'test', start=Yes, headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}
So, handling is being achieved for list, Dictionary or primitive variables from method overloading.
Try it out for your code.
Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:
Create a named region,
Setup the dropdown in a cell.
There is a detailed explanation of the process HERE.
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
private static string GuidToRaw(Guid guid)
{
byte[] bytes = guid.ToByteArray();
int ?harCount = bytes.Length * 2;
char[] chars = new char[?harCount];
int index = 0;
for (int i = 0; i < ?harCount; i += 2)
{
byte b = bytes[index++];
chars[i] = GetHexValue((int)(b / 16));
chars[i + 1] = GetHexValue((int)(b % 16));
}
return new string(chars, 0, chars.Length);
}
private static char GetHexValue(int i)
{
return (char)(i < 10 ? i + 48 : i + 55);
}
As the @Ayush answer:
As you can see
sizeWithFont
at Apple Developer site it is deprecated so we need to usesizeWithAttributes
.
Well, supposing that in 2019+ you are probably using Swift and String
instead of Objective-c and NSString
, here's the correct way do get the size of a String
with predefined font:
let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])
So actually, my comment that you should do a console.log(el.nativeElement)
should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element
.
What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el)
in your example, then you'll have access to the nativeElement
object and will see a property called innerHTML
.
Which will lead to the answer to your original question:
let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element
Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.
The best way to manipulate DOM Elements
programmatically is using the Renderer:
constructor(private _elemRef: ElementRef, private _renderer: Renderer) {
this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}
Since Renderer
is deprecated now, use Renderer2 instead with setProperty
This question with its answer explained the console.log
behavior.
Which means that console.dir(el.nativeElement)
would be the more direct way of accessing the DOM Element
as an "inspectable" Object in your console for this situation.
Hope this helped.
Map.keys()
returns a MapIterator
object which can be converted to Array
using Array.from
:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
type ModifiedType = Modify<OriginalType, { a: number; b: number; }> interface ModifiedInterface extends Modify<OriginalType, { a: number; b: number; }> {}
Inspired by ZSkycat's extends Omit
solution, I came up with this:
type Modify<T, R> = Omit<T, keyof R> & R; // before [email protected] type Modify<T, R> = Pick<T, Exclude<keyof T, keyof R>> & R
Example:
interface OriginalInterface {
a: string;
b: boolean;
c: number;
}
type ModifiedType = Modify<OriginalInterface , {
a: number;
b: number;
}>
// ModifiedType = { a: number; b: number; c: number; }
Going step by step:
type R0 = Omit<OriginalType, 'a' | 'b'> // { c: number; }
type R1 = R0 & {a: number, b: number } // { a: number; b: number; c: number; }
type T0 = Exclude<'a' | 'b' | 'c' , 'a' | 'b'> // 'c'
type T1 = Pick<OriginalType, T0> // { c: number; }
type T2 = T1 & {a: number, b: number } // { a: number; b: number; c: number; }
Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:
$contents = (string) $response->getBody();
You can also do it with
$contents = $response->getBody()->getContents();
The difference between the two approaches is that getContents
returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind
or seek
.
$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.
$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses
If the backend of the REST API is a SQL relational database, then
If you don't care about lost updates, or if you want to force your clients to do a GET immediately after a PUT, then don't return anything from PUT.
With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject
You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.
I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6
but essentially you add following dependencies -
"devDependencies": {
"@angular-builders/custom-webpack": "^7.0.0",
"@angular-builders/dev-server": "^7.0.0",
"@angular-devkit/build-angular": "~0.11.0",
In angular.json make following changes -
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {"path": "./custom-webpack.config.js"},
Notice change in builder and new option customWebpackConfig. Also change
"serve": {
"builder": "@angular-builders/dev-server:generic",
Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.
However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.
If you want to use column names to select the columns, simply use .()
, which is an alias for list()
:
library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
# b c
# 1: 2 3
# 2: 3 4
This isn't exactly what you are asking for, but just looking at the example, it appears that you are looking for the numeric section of the string.
If this is always the case, then a good way to do it would be using a regular expression.
var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
The reason is your result
assigned to the returning Task
which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:
var task = Task.Run(() =>
{
for (int i = 10; i < 432543543; i++)
{
// just for a long job
double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
}
return "Foo Completed.";
});
while (task.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);
}
Console.WriteLine("Result: {0}", task.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
The output
:
Consider this for better explanation: You have a Foo
method,let's say it Task A, and you have a Task
in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task
which is Task A, because Task B doesn't return a Task, it returns a string
. Consider this:
If you define your result like this:
Task result = Foo(5);
You won't get any error.But if you define it like this:
string result = Foo(5);
You will get:
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'
But if you add an await
keyword:
string result = await Foo(5);
Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:
private static async Task<string> Foo(int seconds)
{
await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
// in here don't return anything
});
return await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
In PHP5, you should use the Document Object Model class instead. Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:
SET SERVEROUTPUT ON
declare
v_testnum number;
v_teststring varchar2(1000);
begin
v_testnum := 2;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
SELECT 36,'hello world'
INTO v_testnum, v_teststring
from dual;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;
SET SERVEROUTPUT ON
makes it so text can be printed to the script output console.
I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT
above? In PL/SQL you always have to SELECT ... INTO
either variable or a refcursor. You can't just SELECT
and return a result set in PL/SQL.
Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.
The error message leads to the conclusion that you do not have a master
branch in your local repository. Either push your main development branch (git push origin my-local-master:master
which will rename it to master
on github) or make a commit first. You can not push a completely empty repository.
I just wanted to say that after trying a bunch of things, what fixed my CORS problem was simply using an older version of socket.io (version 2.2.0). My package.json file now looks like this:
{
"name": "current-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"devStart": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"socket.io": "^2.2.0"
},
"devDependencies": {
"nodemon": "^1.19.0"
}
}
If you execute npm install
with this, you may find that the CORS problem goes away when trying to use socket.io. At least it worked for me.
I found this solution very helpful in a clean way to remove xml configuration entirely.
Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/
By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.
I managed to solve the problem by the following steps :
1. Disable windows updates(but check the option "let users install updates manually")
2. Reboot the PC
3. Manually install kb2999226 update from VS install folder (packages/Patch/x64/Windows6.1-KB299926-x64.msu)
4. Start the VS install
5. After install is finished turn back automatic updates
// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
**pagename/methodname** *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
function(result)
{
}
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
{
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function(result)
{
if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
{
CallBackFunction(result);
}
},
error: function(result)
{
alert('error occured');
alert(result.responseText);
window.location.href="FrmError.aspx?Exception="+result.responseText;
},
async: true
});
}
//page name is Default.aspx & FunPubGetTasks method
///your code behind function
[System.Web.Services.WebMethod()]
public static object FunPubGetTasks(string a, string b)
{
//return Ienumerable or array
}
Just to give some ideas to oracle Java source developer :-)
The solution already exists in .Net and is more very more readable !
In Visual Basic .Net
Drawable drawable
= If(Common.getDrawableFromUrl(this, product.getMapPath())
,getRandomDrawable()
)
In C#
Drawable drawable
= Common.getDrawableFromUrl(this, product.getMapPath()
?? getRandomDrawable();
These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.
Just to see quickly the difference with Java solution, I have added the 2 Java solutions
Using Optional in Java
Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
Using { } in Java
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable != null)
{
drawable = getRandomDrawable();
}
Personally, I like VB.Net but I prefer ?? C#
or if {}
solution in Java ... and you ?
Adding a suffix like this:
$('#img_gif').attr('src','file.gif?' + Math.random());
the browser is compelled to download a new image every time the user accesses the page. Moreover the client cache may be quickly filled.
Here follows the alternative solution I tested on Chrome 49 and Firefox 45.
In the css stylesheet set the display property as 'none', like this:
#img_gif{
display:'none';
}
Outside the '$(document).ready' statement insert:
$(window).load(function(){ $('#img_gif').show(); });
Every time the user accesses the page, the animation will be started after the complete load of all the elements. This is the only way I found to sincronize gif and html5 animations.
Please note that:
The gif animation will not restart after refreshing the page (like pressing "F5").
The "$(document).ready" statement doesn't produce the same effect of "$(window).load".
The property "visibility" doesn't produce the same effect of "display".
i was able to achieve sorting using below lines:
array.sort(function(a, b)
{
if (a.DueDate > b.DueDate) return 1;
if (a.DueDate < b.DueDate) return -1;
})
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
You can also write this:
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);
You need to do
./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl
Instead of this
./configure --with-ssl=openssl
Get first element:
array_values($arr)[0]
Get last element
array_reverse($arr)[0]
I know this is old, but I do not see where anyone stated it this way. From what I can tell, this is ANSI standard.
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
It would be good if Microsoft could also support the ANSI standard CURRENT_DATE variable.
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
This may be overkill for a simple breadcrumb, but it's worth a shot. I remember having this issue a long time ago when I first started, but I never really solved it. That is, until I just decided to write this up now. :)
I have documented as best I can inline, at the bottom are 3 possible use cases. Enjoy! (feel free to ask any questions you may have)
<?php
// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ', $home = 'Home') {
// This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// This will build our "base URL" ... Also accounts for HTTPS :)
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
// Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
// Find out the index for the last value in our path array
$last = end(array_keys($path));
// Build the rest of the breadcrumbs
foreach ($path AS $x => $crumb) {
// Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
$title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));
// If we are not on the last index, then display an <a> tag
if ($x != $last)
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
// Otherwise, just display the title (minus)
else
$breadcrumbs[] = $title;
}
// Build our temporary array (pieces of bread) into one big string :)
return implode($separator, $breadcrumbs);
}
?>
<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>
First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:
ID Selector:
$('#mytable td').each(function() {
var cellText = $(this).html();
});
Class Selector:
$('.myTableClass td').each(function() {
var cellText = $(this).html();
});
Additional Information:
Take a look at jQuery's selector docs.
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
in my case
my platform
is x64
the Dll library(sdk)
and the redistributable package
is x64
so
in the solution explorer navigate to your project
open Properties
change the Platform target from AnyCPU to x64
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
I'd create a cte and do an inner join. It's not efficient but it's convenient
with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER()
OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM TABLE)
select *
from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table
group by date, status, title) t2
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title
My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.
// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");
Here is a script I used for recursive trimming. Replace $1 with the directory you want, of course.
BASEDIR="$1"
IFS=$'\n'
cd $BASEDIR
for f in $(find . -type f -name ' *')
do
DIR=$(dirname "$f")
DIR=${DIR:1}
cd $BASEDIR$DIR
rename 's/^ *//' *
done
I use Log.d method also please import import android.util.Log;
Log.d("TAG", "Message");
But please keep in mind that, when you want to see the debug messages then don't use Run As rather use "Debug As" then select Android Application. Otherwise you'll not see the debug messages.
No need to get too complicated. If all you need is ² then use the unicode representation.
http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
(which is how I assume you got the ² to appear in your question. )
It worked on my programs, i'am using date_diff
, you can check date_diff
manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
Can you believe that the treeview on the image below does not use any JavaScript, but relies only on CSS3? Check out this CSS3 TreeView, which is good with Twitter BootStrap:
You can get more info about this here http://acidmartin.wordpress.com/2011/09/26/css3-treevew-no-javascript/.
If you are using select as inline to other component, then you can also use like given below.
<select onChange={(val) => this.handlePeriodChange(val.target.value)} className="btn btn-sm btn-outline-secondary dropdown-toggle">
<option value="TODAY">Today</option>
<option value="THIS_WEEK" >This Week</option>
<option value="THIS_MONTH">This Month</option>
<option value="THIS_YEAR">This Year</option>
<option selected value="LAST_AVAILABLE_DAY">Last Availabe NAV Day</option>
</select>
And on the component where select is used, define the function to handle onChange like below:
handlePeriodChange(selVal) {
this.props.handlePeriodChange(selVal);
}
Or:
SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;
More efficient (I think.) Because you don't have to cast mydate twice per row.
One advantage is that you are compiling access into the application, so it cannot accidentally be changed by someone modifying the Web.config.
This may not be an advantage to you, and might be a disadvantage. But for some kinds of access, it may be preferrable.
Plus, I find that authorization information in the Web.config pollutes it, and makes it harder to find things. So in some ways its preference, in others there is no other way to do it.
Just give any name to the DataTable Like:
DataTable dt = new DataTable();
dt = SecondDataTable.Copy();
dt .TableName = "New Name";
DataSet.Tables.Add(dt );
Here is an inlineStyle selector filter I wrote that plugs into jQuery.
$("div:inlineStyle(display:block)") // will select all divs with an inline style of display: block set
In your case you could use this like:
$("div:inlineStyle(display:block)").hide();
In Addition to Ben's Answer, You can try Below Queries as per your need
USE {database-name};
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE ({database-file-name}, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE {database-name}
SET RECOVERY FULL;
GO
Update Credit @cema-sp
To find database file names use below query
select * from sys.database_files;
Can be done using numpy where() function:
import pandas as pd
import numpy as np
In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
index=list("abcde"))
In [717]: df
Out[717]:
BoolCol gene_name
a False SLC45A1
b True NECAP2
c False CLIC4
d True ADC
e True AGBL4
In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)
In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])
In [720]: df.iloc[select_indices]
Out[720]:
BoolCol gene_name
b True NECAP2
d True ADC
e True AGBL4
Though you don't always need index for a match, but incase if you need:
In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')
In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']
I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/
Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.
Here's the usage
TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"
AllData = loadStockInfo(TICKERS_SP500, allParameters())
SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")
loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."
Finally, the actual code to run that...
require 'net/http'
# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/
$parametersData = Hash[[
["symbol", ["s", "Symbol"]],
["ask", ["a", "Ask"]],
["divYield", ["y", "Dividend Yield"]],
["bid", ["b", "Bid"]],
["dps", ["d", "Dividend per Share"]],
#["noname", ["b2", "Ask (Realtime)"]],
#["noname", ["r1", "Dividend Pay Date"]],
#["noname", ["b3", "Bid (Realtime)"]],
#["noname", ["q", "Ex-Dividend Date"]],
#["noname", ["p", "Previous Close"]],
#["noname", ["o", "Open"]],
#["noname", ["c1", "Change"]],
#["noname", ["d1", "Last Trade Date"]],
#["noname", ["c", "Change & Percent Change"]],
#["noname", ["d2", "Trade Date"]],
#["noname", ["c6", "Change (Realtime)"]],
#["noname", ["t1", "Last Trade Time"]],
#["noname", ["k2", "Change Percent (Realtime)"]],
#["noname", ["p2", "Change in Percent"]],
#["noname", ["c8", "After Hours Change (Realtime)"]],
#["noname", ["m5", "Change From 200 Day Moving Average"]],
#["noname", ["c3", "Commission"]],
#["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
#["noname", ["g", "Day’s Low"]],
#["noname", ["m7", "Change From 50 Day Moving Average"]],
#["noname", ["h", "Day’s High"]],
#["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
#["noname", ["k1", "Last Trade (Realtime) With Time"]],
#["noname", ["m3", "50 Day Moving Average"]],
#["noname", ["l", "Last Trade (With Time)"]],
#["noname", ["m4", "200 Day Moving Average"]],
#["noname", ["l1", "Last Trade (Price Only)"]],
#["noname", ["t8", "1 yr Target Price"]],
#["noname", ["w1", "Day’s Value Change"]],
#["noname", ["g1", "Holdings Gain Percent"]],
#["noname", ["w4", "Day’s Value Change (Realtime)"]],
#["noname", ["g3", "Annualized Gain"]],
#["noname", ["p1", "Price Paid"]],
#["noname", ["g4", "Holdings Gain"]],
#["noname", ["m", "Day’s Range"]],
#["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
#["noname", ["m2", "Day’s Range (Realtime)"]],
#["noname", ["g6", "Holdings Gain (Realtime)"]],
#["noname", ["k", "52 Week High"]],
#["noname", ["v", "More Info"]],
#["noname", ["j", "52 week Low"]],
#["noname", ["j1", "Market Capitalization"]],
#["noname", ["j5", "Change From 52 Week Low"]],
#["noname", ["j3", "Market Cap (Realtime)"]],
#["noname", ["k4", "Change From 52 week High"]],
#["noname", ["f6", "Float Shares"]],
#["noname", ["j6", "Percent Change From 52 week Low"]],
["name", ["n", "Company Name"]],
#["noname", ["k5", "Percent Change From 52 week High"]],
#["noname", ["n4", "Notes"]],
#["noname", ["w", "52 week Range"]],
#["noname", ["s1", "Shares Owned"]],
#["noname", ["x", "Stock Exchange"]],
#["noname", ["j2", "Shares Outstanding"]],
#["noname", ["v", "Volume"]],
#["noname", ["a5", "Ask Size"]],
#["noname", ["b6", "Bid Size"]],
#["noname", ["k3", "Last Trade Size"]],
#["noname", ["t7", "Ticker Trend"]],
#["noname", ["a2", "Average Daily Volume"]],
#["noname", ["t6", "Trade Links"]],
#["noname", ["i5", "Order Book (Realtime)"]],
#["noname", ["l2", "High Limit"]],
#["noname", ["e", "Earnings per Share"]],
#["noname", ["l3", "Low Limit"]],
#["noname", ["e7", "EPS Estimate Current Year"]],
#["noname", ["v1", "Holdings Value"]],
#["noname", ["e8", "EPS Estimate Next Year"]],
#["noname", ["v7", "Holdings Value (Realtime)"]],
#["noname", ["e9", "EPS Estimate Next Quarter"]],
#["noname", ["s6", "evenue"]],
#["noname", ["b4", "Book Value"]],
#["noname", ["j4", "EBITDA"]],
#["noname", ["p5", "Price / Sales"]],
#["noname", ["p6", "Price / Book"]],
#["noname", ["r", "P/E Ratio"]],
#["noname", ["r2", "P/E Ratio (Realtime)"]],
#["noname", ["r5", "PEG Ratio"]],
#["noname", ["r6", "Price / EPS Estimate Current Year"]],
#["noname", ["r7", "Price / EPS Estimate Next Year"]],
#["noname", ["s7", "Short Ratio"]
]]
def replaceCommas(data)
s = ""
inQuote = false
data.split("").each do |a|
if a=='"'
inQuote = !inQuote
s += '"'
elsif !inQuote && a == ","
s += "#"
else
s += a
end
end
return s
end
def allParameters()
s = ""
$parametersData.keys.each do |i|
s = s + i + ","
end
return s
end
def prepareParameters(parametersText)
pt = parametersText.split(",")
if !pt.include? 'symbol'; pt.push("symbol"); end;
if !pt.include? 'name'; pt.push("name"); end;
p = []
pt.each do |i|
p.push([i, $parametersData[i][0]])
end
return p
end
def prepareURL(tickers, parameters)
urlParameters = ""
parameters.each do |i|
urlParameters += i[1]
end
s = "http://download.finance.yahoo.com/d/quotes.csv?"
s = s + "s=" + tickers + "&"
s = s + "f=" + urlParameters
return URI(s)
end
def loadStockInfo(tickers, parametersRaw)
parameters = prepareParameters(parametersRaw)
url = prepareURL(tickers, parameters)
data = Net::HTTP.get(url)
data = replaceCommas(data)
h = CSVtoObject(data, parameters)
logStockObjects(h, true)
end
#parse csv
def printCodes(substring, length)
a = data.index(substring)
b = data.byteslice(a, 10)
puts "printing codes of string: "
puts b
puts b.split('').map(&:ord).to_s
end
def CSVtoObject(data, parameters)
rawData = []
lineBreaks = data.split(10.chr)
lineBreaks.each_index do |i|
rawData.push(lineBreaks[i].split("#"))
end
#puts "Found " + rawData.length.to_s + " Stocks"
#puts " w/ " + rawData[0].length.to_s + " Fields"
h = Hash.new("MainHash")
rawData.each_index do |i|
o = Hash.new("StockObject"+i.to_s)
#puts "parsing object" + rawData[i][0]
rawData[i].each_index do |n|
#puts "parsing parameter" + n.to_s + " " +parameters[n][0]
o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
end
h[o["symbol"]] = o;
end
return h
end
def logStockObjects(h, concise)
h.keys.each do |i|
if concise
puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
else
puts ""
puts h[i]["name"]
h[i].keys.each do |p|
puts " " + $parametersData[p][1] + " : " + h[i][p].to_s
end
end
end
end
Actually my problem was that the command line mvn utility wouldn't see the changes for some reason. I turned on the Auto-deploy in the Deployment Scanner and there was still no difference. HOWEVER... I was twiddling around with the Eclipse environment and because I had added a JBoss server for it's Servers window I discovered I had the ability to "Add or Remove..." modules in my workspace. Once the project was added whenever I made a change to code the code change was detected by the Deployment Scanner and JBoss went thru the cycle of updating code!!! Works like a charm.
Here are the steps necessary to set this up;
First if you haven't done so add your JBoss Server to your Eclipse using File->New->Other->Server then go thru the motions of adding your JBoss AS 7 server. Being sure to locate the directory that you are using.
Once added, look down near the bottom of Eclipse to the "Servers" tab. You should see your JBoss server. Highlight it and look for "Add or Remove...". From there you should see your project.
Once added, make a small change to your code and watch JBoss go to town hot deploying for you.
I found a tool called ttyplot
in homebrew. It's good. https://github.com/tenox7/ttyplot
when you declare activity in the manifest you need android:configChanges="orientation"
example:
<activity android:theme="@android:style/Theme.Light.NoTitleBar" android:configChanges="orientation" android:label="traducción" android:name=".PantallaTraductorAppActivity"></activity>
if you are getting id from url try
$id = (isset($_GET['id']) ? $_GET['id'] : '');
if getting from form you need to use POST
method cause your form has method="post"
$id = (isset($_POST['id']) ? $_POST['id'] : '');
For php notices use isset()
or empty()
to check values exist or not or initialize variable first with blank or a value
$id= '';
There are three method to avoid such a problem.
Method 1 : by setting ignore missing font property.
JRProperties.setProperty("net.sf.jasperreports.awt.ignore.missing.font", "true");
or you can set this property by entering following line into .jrxml file.
<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>
Method 2 : by setting default font property.
JRProperties.setProperty("net.sf.jasperreports.default.font.name", "Sans Serif");
or you can set this property by entering following line into .jrxml file.
<property name="net.sf.jasperreports.default.font.name" value="Sans Serif"/>
Method 3 : by adding missing font property.
Firstly install missing fonts in IReport by selecting " Tools >> Options >> Fonts >> Install Font " then select the all font and Export this By clicking on "Export as Extension" with .jar Extension.
You can use this jar for Jasperreports-font.X.X.X.jar which will be present in your project library or classpath.
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
You can later access this member, on any instance:
int main()
{
int Car::*pSpeed = &Car::speed;
Car myCar;
Car yourCar;
int mySpeed = myCar.*pSpeed;
int yourSpeed = yourCar.*pSpeed;
assert(mySpeed > yourSpeed); // ;-)
return 0;
}
Note that you do need an instance to call it on, so it does not work like a delegate.
It is used rarely, I've needed it maybe once or twice in all my years.
Normally using an interface (i.e. a pure base class in C++) is the better design choice.
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
I'm using this variant for force print K decimal places:
# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)
http://www.math.sjsu.edu/~foster/dictionary.txt
350,000 words
Very late, but might be useful for others.
Yes, definitely don't write your own algorithm. Java has lots of cryptography APIs.
If the OS you are installing upon has a keystore, then you could use that to store your crypto keys that you will need to encrypt and decrypt the sensitive data in your configuration or other files.
As an addition to npm version
you can use the --no-git-tag-version
flag if you want a version bump but no tag or a new commit:
npm --no-git-tag-version version patch
For Xcode 9 and latest devices
Portrait
iPhone 4/4S 640 x 960
iPhone 5/5C/5S iPod touch 5th generation 640 x 1136
iPhone 6/7/8 750 x 1334
iPhone 6/7/8 Plus 1242 x 2208
iPhone X 1125 x 2436
iPad non-retina 768 x 1024
iPad retina 1536 x 2048
Landscape
iPhone 6, 7 and 8 plus 2208 x 1242
iPhone X 2436 x 1125
iPad non-retina 1024 x 768
iPad retina 2048 x 1536
To force git stash pop
run this command
git stash show -p | git apply && git stash drop
In swift 4 and autoLayout, you can use sectionInset like this:
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: (view.frame.width-40)/2, height: (view.frame.width40)/2) // item size
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) // here you can add space to 4 side of item
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) // set layout to item
collectionView?.register(ProductCategoryCell.self, forCellWithReuseIdentifier: cellIdentifier) // registerCell
collectionView?.backgroundColor = .white // background color of UICollectionView
view.addSubview(collectionView!) // add UICollectionView to view
One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.
I'm using Eclipse with Cygwin and this worked for me:
Go to Project > Properties > C/C++ General > Preprocessor Includes... > Providers and select "CDT GCC Built-in Compiler Settings Cygwin [Shared]".
Following is the way to do it;
.control select {
border-radius: 0px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("<your image>");
background-repeat: no-repeat;
background-position: 100%;
background-size: 20px;
}
Assume we are creating a subsite whose files are in the folder http://site.ru/shop.
Link to home page
href="http://sites.ru/shop/"
Link to the product page
href="http://sites.ru/shop/t-shirts/t-shirt-life-is-good/"
Link from home page to product page
href="t-shirts/t-shirt-life-is-good/"
Link from product page to home page
href="../../"
Although relative URL look shorter than absolute one, but the absolute URLs are more preferable, since a link can be used unchanged on any page of site.
We have considered two extreme cases: "absolutely" absolute and "absolutely" relative URLs. But everything is relative in this world. This also applies to URLs. Every time you say about absolute URL, you should always specify relative to what.
Link to home page
href="//sites.ru/shop/"
Link to product page
href="//sites.ru/shop/t-shirts/t-shirt-life-is-good/"
Google recommends such URL. Now, however, it is generally considered that http:// and https:// are different sites.
I.e. relative to the root folder of the domain.
Link to home page
href="/shop/"
Link to product page
href="/shop/t-shirts/t-shirt-life-is-good/"
It is a good choice if all pages are within the same domain. When you move your site to another domain, you don't have to do a mass replacements of the domain name in the URLs.
The tag <base> specifies the base URL, which is automatically added to all relative links and anchors. The base tag does not affect absolute links. As a base URL we'll specify the home page: <base href="http://sites.ru/shop/">.
Link to home page
href=""
Link to product page
href="t-shirts/t-shirt-life-is-good/"
Now you can move your site not only to any domain, but in any subfolder. Just keep in mind that, although URLs look like relative, in fact they are absolute. Especially pay attention to anchors. To navigate within the current page we have to write href="t-shirts/t-shirt-life-is-good/#comments" not href="#comments". The latter will throw on home page.
For internal links I use base-relative URLs (5). For external links and newsletters I use absolute URLs (1).
I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.
I think that some pretty common limitations for subject lines in general (not just e-mail) are:
Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.
Hope this helps!
Creator of the change-case extension here. I've updated the extension to support spanning lines.
To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:
{
"key": "ctrl+t ctrl+u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
}
EDIT:
With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase
and editor.action.transformToLowercase
. These don't have default keybindings. They also work with multi-line blocks.
The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.
Try this -->
new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko).ToList()
This seems to work:
/descendant::input[@id="search_query"][2]
I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.
There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.
You can't access form inputs via their name. Use document.getElements
methods instead.
From the documentation:
The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.
This means that the order is probably OS/filesystem dependent, has no particularly meaningful order, and is therefore not guaranteed to be anything in particular. As many answers mentioned: if preferred, the retrieved list can be sorted.
Cheers :)
It should be:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName
: the name of the table in the database.TableEntityInstance
: an instance of the table entity class.If your table is Orders
, then:
Order order = new Order();
context.Orders.AddObject(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is a live example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.AddObject(screenshot);
this.ObjectContext.SaveChanges();
}
}
Try this one:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxcombobox/index.htm
Very nice with many features including localization.
There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.
The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip
that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.
Unzipping is easier - just treat it as a directory.
In case the web pages are lost again, here are a few of the relevant code snippets:
Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
Split97 = Evaluate("{""" & _
Application.Substitute(sStr, sdelim, """,""") & """}")
End Function
Sub Zip_File_Or_Files()
Dim strDate As String, DefPath As String, sFName As String
Dim oApp As Object, iCtr As Long, I As Integer
Dim FName, vArr, FileNameZip
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
'Browse to the file(s), use the Ctrl key to select more files
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, Title:="Select the files you want to zip")
If IsArray(FName) = False Then
'do nothing
Else
'Create empty Zip File
NewZip (FileNameZip)
Set oApp = CreateObject("Shell.Application")
I = 0
For iCtr = LBound(FName) To UBound(FName)
vArr = Split97(FName(iCtr), "\")
sFName = vArr(UBound(vArr))
If bIsBookOpen(sFName) Then
MsgBox "You can't zip a file that is open!" & vbLf & _
"Please close it and try again: " & FName(iCtr)
Else
'Copy the file to the compressed folder
I = I + 1
oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = I
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
End If
Next iCtr
MsgBox "You find the zipfile here: " & FileNameZip
End If
End Sub
Sub Unzip1()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create the folder name
strDate = Format(Now, " dd-mm-yy h-mm-ss")
FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
'If you want to extract only one file you can use this:
'oApp.Namespace(FileNameFolder).CopyHere _
'oApp.Namespace(Fname).items.Item("test.txt")
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.
Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.
In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.
The code that tries to stop the thread should do the following:
running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
threadInstance_.Abort();
}
Had the same issue, the reason for it was BCrypt.Net library, compiled using .NET 2.0 framework, while the whole project, which used it, was compiling with .NET 4.0. If symptoms are the same, try download BCrypt source code and rebuild it in release configuration within .NET 4.0. After I'd done it "pre-login handshake" worked fine. Hope it helps anyone.
var fd = new FormData();
//Get Form Values
var other_data = $('#form1').serializeArray();
$.each(other_data, function (key, input) {
fd.append(input.name, input.value);
});
//Get File Value
var $file = jq("#photoUpload").get(0);
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
fd.append('Photograph' + i, $file.files[i]);
}
}
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
Another reason why many prefer hyphens in CSS id and class names is functionality.
Using keyboard shortcuts like option + left/right (or ctrl+left/right on Windows) to traverse code word by word stops the cursor at each dash, allowing you to precisely traverse the id or class name using keyboard shortcuts. Underscores and camelCase do not get detected and the cursor will drift right over them as if it were all one single word.
You can use the monitoring program glances with its GPU monitoring plug-in:
sudo apt-get install -y python-pip; sudo pip install glances[gpu]
sudo glances
It also monitors the CPU, disk IO, disk space, network, and a few other things:
Edit:
@t1m0thy's answer is more elegant than mine, better follow his advices.
Also, nice link proposed by @aldemarcalazans in the comments: https://davidwalsh.name/html5-buttons.
Original answer:
Use <a />
when you need a link (the a of anchor). Use <button />
when you need a button.
That said, if you really need to expand an <a />
, add the CSS attribute display: block;
on it. You'll then be able to specify a width and/or a height (i.e. as if it were a <div />
).
If you are not using fig and ax plot objects you can do it like so:
import matplotlib.pyplot as plt
# do plot specifics
plt.legend('')
plt.show()
$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));
Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.
Problem
In Laravel you have config/database.php
where all the setup for the connection is located. You also have a .env
file in the root directory in your project (which everyone uses for timesaving). This contains variables that you can use for the entire project.
On a standard L5 project the MySql section of config/database.php
looks like this:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
Notice there is no port set!
Although in my .env
file I had set DB_PORT=33060
. But that value (3306)
was never read into the config/database.php
.
So don't be a dumbass like myself and forget to check the database.php
file.
'port' => env('DB_PORT', 3306),
to your config/database.php and set that value in .env like this DB_PORT=3306
There is CUnit
And Embedded Unit is unit testing framework for Embedded C System. Its design was copied from JUnit and CUnit and more, and then adapted somewhat for Embedded C System. Embedded Unit does not require std C libs. All objects are allocated to const area.
And Tessy automates the unit testing of embedded software.
First you should change the mode of .pem
file from read and write mode to read only mode. This can be done just by a single command in terminal sudo chmod 400 your_public_key.pem
Edit / Paste from the title bar's context menu (until they fix the control key shortcuts)
It's Unicode.
Just put the variable between str()
, and it will work fine.
But in case you have two lists like the following:
a = ['co32','co36']
b = [u'co32',u'co36']
If you check set(a)==set(b)
, it will come as False, but if you do as follows:
b = str(b)
set(a)==set(b)
Now, the result will be True.
This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.
After successfully running autogen.sh/configure, compile with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make
The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
I know this is an old post but as MisterZimbu stated, the color
property is defining the values of other properties, as the border-color
and, with CSS3, of currentColor
.
currentColor
is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).
Example:
.element {_x000D_
color: green;_x000D_
background: red;_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
border: solid 10px;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
background: currentColor;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
<div class="innerElement1"></div>_x000D_
<div class="innerElement2"></div>_x000D_
</div>
_x000D_
You've just done a restart of the service and the code should run without errors
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).
For this example, let's draw a RED pixel at position 100x50.
Mat foo;
int x=100, y=50;
Solution 1:
Create a macro function that obtains the pixel from the array.
#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Solution 2:
Get's the pixel using the method ptr.
unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
To avoid closing the parentheses for each line you can simply use double quotes with a backslash to escape the newline:
"select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
from table1, table2, table3, etc, etc, etc, etc, etc, \
where etc etc etc etc etc etc etc etc etc etc etc etc etc"
just do it: in component tree right click on ConstraintLayout and select relativelayout on convert view...
Just run below command:
SELECT setval('my_table_seq', (SELECT max(id) FROM my_table));
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16
, or 64k.
You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.
Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.
body {
background: url('../images/cat.ong');
background-size: cover;
background-position: center;
background-attachment: fixed;
}
Vue.js uses vue-loader
, a loader for WebPack which is set up to rewrite/convert paths at compile time, in order to allow you to not worry about static paths that would differ between deployments (local, dev, one hosting platform or the other), by allowing you to use relative local filesystem paths. It also adds other benefits like asset caching and versioning (you can probably see this by checking the actual src
URL being generated).
So having a src that would normally be handled by vue-loader
/WebPack set to a dynamic expression, evaluated at runtime, will circumvent this mechanism and the dynamic URL generated will be invalid in the context of the actual deployment (unless it's fully qualified, that's an exception).
If instead, you would use a require
function call in the dynamic expression, vue-loader
/WebPack will see it and apply the usual magic.
For example, this wouldn't work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? './assets/logo-dark.png'
: './assets/logo-white.png';
}
}
While this would work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? require('./assets/logo-dark.png')
: require('./assets/logo-white.png');
}
}
I just found out about this myself. Took me an hour but... you live, you learn, right?
Even though this solution is done with jQuery I though it may be useful for anyone doing columns to fit the screen size.
For columns starting at the top of the page, this solution is the simplest.
body,html{
height:100%;
}
div#right{
height:100%
}
For columns that are not starting at the top of the page (for example: if they are starting below the header).
<script>
$(document).ready(function () {
var column_height = $("body").height();
column_height = column_height - 100; // 100 is the header height
column_height = column_height + "px";
$("#column").css("height",column_height);
});
</script>
First method applies the body height to it and the columns as well, which means that is starting_pixels + height100%
.
The second method gets the height of page shown to the user by getting the height of the body and then subtracts the header size to know how much height is left to display the column.
Copied answer from the attached question.
You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.
Install PM2
$ npm install pm2 -g
Start an application
$ pm2 start app.js
If you using express then you can start your app like
pm2 start ./bin/www --name="app"
Listing all running processes:
$ pm2 list
It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.
$ pm2 stop all
$ pm2 stop 0
$ pm2 restart all
To display logs
$ pm2 logs ['all'|app_name|app_id]
For my use case, I needed to access just the system properties, but provide default values in case they are undefined.
This is how you do it:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="myBean" class="path.to.my.BeanClass">
<!-- can be overridden with -Dtest.target.host=http://whatever.com -->
<constructor-arg value="${test.target.host:http://localhost:18888}"/>
</bean>
You forgot to add std::
namespace prefix to vector
class name.
Starting in Python 3.9
, you can use removeprefix
and removesuffix
:
'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
And if you want to specify select's ID:
$("#nextPageLink").click(function(){
$('#myselect option:selected').next('option').attr('selected', 'selected');
$("#myselect").change();
});
If you click on item with id "nextPageLink", next option will be selected and onChange() event will be called. It may look like this:
$("#myselect").change(function(){
$('#myDivId').load(window.location.pathname,{myvalue:$("select#myselect").val()});
});
OnChange() event uses Ajax to load something into specified div.
window.location.pathname = actual address
OnChange() event is defined because it allowes you to change value not only using netx/prev button, but directly using standard selection. If value is changed, page does somethig automatically.
Well, to give some perspective, let me compare node.js with apache.
Apache is a multi-threaded HTTP server, for each and every request that the server receives, it creates a separate thread which handles that request.
Node.js on the other hand is event driven, handling all requests asynchronously from single thread.
When A and B are received on apache, two threads are created which handle requests. Each handling the query separately, each waiting for the query results before serving the page. The page is only served until the query is finished. The query fetch is blocking because the server cannot execute the rest of thread until it receives the result.
In node, c.query is handled asynchronously, which means while c.query fetches the results for A, it jumps to handle c.query for B, and when the results arrive for A arrive it sends back the results to callback which sends the response. Node.js knows to execute callback when fetch finishes.
In my opinion, because it's a single thread model, there is no way to switch from one request to another.
Actually the node server does exactly that for you all the time. To make switches, (the asynchronous behavior) most functions that you would use will have callbacks.
The SQL query is taken from mysql library. It implements callback style as well as event emitter to queue SQL requests. It does not execute them asynchronously, that is done by the internal libuv threads that provide the abstraction of non-blocking I/O. The following steps happen for making a query :
The incoming requests to http server are handled in the similar fashion. The internal thread architecture is something like this:
The C++ threads are the libuv ones which do the asynchronous I/O (disk or network). The main event loop continues to execute after the dispatching the request to thread pool. It can accept more requests as it does not wait or sleep. SQL queries/HTTP requests/file system reads all happen this way.
If you use the html approach:
don't add blank lines
Like this:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
the markup will break.
Remove blank lines:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
My team encountered the same issue in machines with Windows.. then managed to resolve it in two ways:
a) Set enviroment variable (even in Windows system preferences)
JAVA_TOOL_OPTIONS
-Dfile.encoding=UTF8
b) Introduce following snippet to your pom.xml:
-Dfile.encoding=UTF-8
WITHIN
<jvmArguments>
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001
-Dfile.encoding=UTF-8
</jvmArguments>
If you like to manually manage your profiles (mostly to clean up):
No longer supported ... you can also download Apple's iPhone Configuration Utility 3.5 for Mac OS X, it still has "Provisioning Profiles" and works with Xcode 5 -- it's now gone from Apples site but you can find an alternative download link in @suda's comment.
I'm just speculating:
I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:
int *doubleDigits;
And then allocate the space for it in the init-method:
@synthesize doubleDigits;
- (id)init {
if (self = [super init]) {
doubleDigits = malloc(sizeof(int) * 10);
/*
* This works, but is dangerous (forbidden) because bufferDoubleDigits
* gets deleted at the end of -(id)init because it's on the stack:
* int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
* [self setDoubleDigits:bufferDoubleDigits];
*
* If you want to be on the safe side use memcpy() (needs #include <string.h>)
* doubleDigits = malloc(sizeof(int) * 10);
* int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
* memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
*/
}
return self;
}
- (void)dealloc {
free(doubleDigits);
[super dealloc];
}
In this case the interface looks like this:
@interface MyClass : NSObject {
int *doubleDigits;
}
@property int *doubleDigits;
Edit:
I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)
int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];
Thanks Ravi and other users .... Nevertheless I have got the solution
SELECT @phoneNumber=
CASE
WHEN ISNULL(rdg2.nPhoneNumber ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0')
WHEN ISNULL(rdg2.nMobileNumber, '0') in ('0','-',NULL)
THEN '0'
ELSE ISNULL(rdg2.nPhoneNumber ,'0')
END
FROM tblReservation_Details_Guest rdg2
WHERE nReservationID=@nReservationID
Just need to put '0' instead of 0
I like this if you want to get just some parts of the query:
new CriteriaQueryTranslator(
factory,
executableCriteria,
executableCriteria.getEntityOrClassName(),
CriteriaQueryTranslator.ROOT_SQL_ALIAS)
.getWhereCondition();
For instance something like this:
String where = new CriteriaQueryTranslator(
factory,
executableCriteria,
executableCriteria.getEntityOrClassName(),
CriteriaQueryTranslator.ROOT_SQL_ALIAS)
.getWhereCondition();
String sql = "update my_table this_ set this_.status = 0 where " + where;
in template
<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
system_update_alt
</md-icon></md-button>
in controller
$scope.export = function(){ $window.location.href = $scope.export; };
This was my workaround:
$('#vcGoButton').click(function () {
var buttonStatus = $('#vcChangeLocation').prop('checked');
console.log("Status is " + buttonStatus);
if (buttonStatus) {
var address = $('#vcNewLocation').val();
var cabNumber = $('#vcVehicleNumber').val();
$.get('postCabLocation.php',
{address: address, cabNumber: cabNumber},
function(data) {
console.log("Changed vehicle " + cabNumber + " location to " + address );
});
}
else {
console.log("VC go button clicked, but no location action");
}
});
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
To install nodejs on ubuntu, you can type the following command in the terminal:
sudo apt-get install nodejs
To install nodejs on systems using yum, type the following in the terminal:
yum -y install nodejs
i think the problem lies within the space in the folder-name where your project is placed. /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json
there is space between Java Programs.Renaming the folder name should make it work
I had this issue too because I was filtering /src/main/resources and forgot I had added a keystore (*.jks) binary to this directory.
Add a "resource" block with exclusions for binary files and your problem may be resolved.
<build>
<finalName>somename</finalName>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
</testResource>
</testResources>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>*.jks</exclude>
<exclude>*.png</exclude>
</excludes>
</resource>
</resources>
...
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
string a = @"a\\b";
a = a.Replace(@"\\",@"\");
should work. Remember that in the watch Visual STudio show the "\" escaped so you see "\" in place of a single one.
Typographically, the correct glyph to use in sentence punctuation is the quote mark, both single (including for apostrophes) and double quotes. The straight-looking mark that we often see on the web is called a prime, which also comes in single and double varieties and has limited uses, mostly for measurements.
This article explains how to use them correctly.
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.
The alternative is to add the dependency to the classpath at the time you invoke the application:
win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix: java -cp app.jar:dependency.jar foo.MyMainClass
SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
Using the jquery data store you can define a 'loaded' state.
<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />
Then elsewhere you can do:
if ($('#myimage').data('loaded')) {
// loaded, so do stuff
}
The best javascript solution I've found is this
elm.options[0].selected="selected";
I don't believe this is possible. Consider the following example:
>>> a = []
>>> b = a
>>> id(a)
140031712435664
>>> id(b)
140031712435664
The a
and b
point to the same object, but the object can't know what variables point to it.
Actually, you have to use the anchor # to play with this. If you reverse engineer the Gmail url system, you'll find
https://mail.google.com/mail/u/0/#inbox
https://mail.google.com/mail/u/0/#inbox?compose=new
Everything after # is the part your want to load in your page, then you just have to chose where to load it.
By the way, using document.location by adding a #something won't refresh your page.
Android Studio 1.2.2 has moved the setting into the General
subfolder of Editor settings.
In addition to Eduard Void answer here's the addValidators
method:
declare module '@angular/forms' {
interface FormControl {
addValidators(validators: ValidatorFn[]): void;
}
}
FormControl.prototype.addValidators = function(this: FormControl, validators: ValidatorFn[]) {
if (!validators || !validators.length) {
return;
}
this.clearValidators();
this.setValidators( this.validator ? [ this.validator, ...validators ] : validators );
};
Using it you can set validators dynamically:
some_form_control.addValidators([ first_validator, second_validator ]);
some_form_control.addValidators([ third_validator ]);
import java.io.Serializable;
public class Course implements Serializable {
protected int courseId;
protected String courseName;
protected String courseType;
public Course() {
courseName = new String();
courseType = new String();
}
public Course(String courseName, String courseType) {
this.courseName = courseName;
this.courseType = courseType;
}
public Course(int courseId, String courseName, String courseType) {
this.courseId = courseId;
this.courseName = courseName;
this.courseType = courseType;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseType() {
return courseType;
}
public void setCourseType(String courseType) {
this.courseType = courseType;
}
@Override
public int hashCode() {
return courseId;
}
@Override
public boolean equals(Object obj) {
if (obj != null || obj instanceof Course) {
Course c = (Course) obj;
if (courseId == c.courseId && courseName.equals(c.courseName)
&& courseType.equals(c.courseType))
return true;
}
return false;
}
@Override
public String toString() {
return "Course[" + courseId + "," + courseName + "," + courseType + "]";
}
}
In my case, a problem was in calling inflater.inflate(R.layout.some_layout, null). Null as ViewGroup parameter was the problem.
Set a system variable named http_proxy
with the value of ProxyServer:Port
.
That is the simplest solution. Respectively, use https_proxy
as daefu pointed out in the comments.
Setting gitproxy (as sleske mentions) is another option, but that requires a "command", which is not as straightforward as the above solution.
References: http://bardofschool.blogspot.com/2008/11/use-git-behind-proxy.html
One idiom is:
cd some_dir && ./configure --some-flags && make && make install
I realize that can get long, but for larger scripts you could break it into logical functions.
Assuming this is what the HTML looks like
<div class="form-group required">
<label class="col-md-2 control-label">E-mail</label>
<div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>
To display an asterisk on the right of the label:
.form-group.required .control-label:after {
color: #d00;
content: "*";
position: absolute;
margin-left: 8px;
top:7px;
}
Or to the left of the label:
.form-group.required .control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -15px;
}
To make a nice big red asterisks you can add these lines:
font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;
Or if you are using Font Awesome add these lines (and change the content line):
font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";
Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is SIGKILL
. This also explains the killed
message. The question is, why did you receive that signal?
The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.
As I commented earlier, one reason you might hit a memory limit after printing finished counting
is that your call to counter.items()
in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use counter.iteritems()
which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.
So, I'd suggest trying this, as your final loop:
for key, value in counter.iteritems():
writer.writerow([key, value])
Note that in Python 3, items
returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces iteritems
, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.
unsorted_list.sort(key=lambda x: x[3])
add this to README
<div align="center">
<img src="/screenshots/screen1.jpg" width="400px"</img>
</div>
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Why do we have to write that 5 line code ?
public class EnumTest {
public enum MyEnum {
A, B, C, D;
}
@Test
public void test() throws Exception {
MyEnum.valueOf("A"); //gives you A
//this throws ILlegalargument without having to do any lookup
MyEnum.valueOf("RADD");
}
}
You should use $_FILES[$form_name]['error']
. It returns UPLOAD_ERR_NO_FILE
if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
If you have the char array null terminated, you can assign the char array to the string:
char[] chArray = "some characters";
String String(chArray);
As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.
The below 'd help you to add the cert to the Root Store-
certutil -enterprise -f -v -AddStore "Root" <Cert File path>
This worked for me perfectly.
This is what I came up with:
private static String format(final double dbl) {
return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
}
It is a simple one-liner and only casts to int if it really needs to.