You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
According to the official doc (https://nodejs.org/api/esm.html#esm_code_import_code_statements):
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to (https://nodejs.org/api/esm.html#esm_enabling):
just go to this url in chrome browser
chrome://settings/help
and chrome will automatically look for updates(update Chrome to the latest version)
finish :)
When hosting in Amazon Web Services (AWS) using an Elastic Beanstalk (EBS) deployment AND using this stackoverflow answer on how to access configuration values in EBS containers (https://stackoverflow.com/a/47648283/78804)
If NO configuration values have been set within the Elastic Beanstalk -> Environments -> [APP NAME] -> Configuration -> Software
menu, you will probably see this error.
Setting ANY SINGLE VALUE in the EBS config, makes it go away.
This is probably caused by the configuration-loading block failing to do a null check and the entire website failing un-gracefully because the error is happening during the application Startup
phase.
You can multiply numpy arrays by scalars and it just works.
>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2, 4, 6],
[ 8, 10, 12]])
This is also a very fast and efficient operation. With your example:
>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
[6., 8.]])
That's mostly due to libraries which are obsolete. To check for new updates manually, you should navigate to
Analyze > "Run Inspection By Name"
That should be enough. Another option is to run a gradle dependency update using
./gradlew dependencyUpdates
that will produce a report like this:
:dependencyUpdates
------------------------------------------------------------
: Project Dependency Updates (report to plain text file)
------------------------------------------------------------
The following dependencies are using the latest milestone version:
- com.github.ben-manes:gradle-versions-plugin:0.15.0
The following dependencies have later milestone versions:
- com.google.auto.value:auto-value [1.4 -> 1.4.1]
- com.google.errorprone:error_prone_core [2.0.19 -> 2.0.21]
- com.google.guava:guava [21.0 -> 23.0-rc1]
- net.ltgt.gradle:gradle-apt-plugin [0.9 -> 0.10]
- net.ltgt.gradle:gradle-errorprone-plugin [0.0.10 -> 0.0.11]
...
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(...);
}
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
In addition to @Cinn's answer, you can define a class like this
class MyAppBar extends AppBar with PreferredSizeWidget {
@override
get preferredSize => Size.fromHeight(50);
MyAppBar({Key key, Widget title}) : super(
key: key,
title: title,
// maybe other AppBar properties
);
}
or this way
class MyAppBar extends PreferredSize {
MyAppBar({Key key, Widget title}) : super(
key: key,
preferredSize: Size.fromHeight(50),
child: AppBar(
title: title,
// maybe other AppBar properties
),
);
}
and then use it instead of standard one
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
useHistory()
from react-router-dom
can fix your problem
import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
const history = useHistory();
const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');
return (
<div>
<button onClick={navigateTo} type="button" />
</div>
);
}
export default NavigationDemo;
As @Peter Haddad mentioned above,
To fix this issue I followed Google firebase integration guidelines and did the following changes in my app/build.gradle and project/build.gradle
Follow below mentioned link if you have any doubts
https://firebase.google.com/docs/android/setup
changes in app/build.gradle
implementation 'com.google.android.gms:play-services-base:15.0.2'_x000D_
implementation "com.google.firebase:firebase-core:16.0.1"_x000D_
implementation "com.google.firebase:firebase-messaging:17.4.0"
_x000D_
Changes in Project/build.gradle
repositories {_x000D_
_x000D_
google()_x000D_
jcenter()_x000D_
mavenCentral()_x000D_
maven {_x000D_
url 'https://maven.fabric.io/public'_x000D_
}_x000D_
}_x000D_
dependencies {_x000D_
classpath 'com.android.tools.build:gradle:3.1.4'_x000D_
classpath 'com.google.gms:google-services:4.2.0'// // google-services plugin it should be latest if you are using firebase version 16.0 +_x000D_
_x000D_
}_x000D_
allprojects {_x000D_
repositories {_x000D_
google()// add it to top instead of bottom or somewhere in middle_x000D_
mavenLocal()_x000D_
mavenCentral()_x000D_
maven {_x000D_
url 'https://maven.google.com'_x000D_
}_x000D_
_x000D_
jcenter()_x000D_
maven {_x000D_
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm_x000D_
url "$rootDir/../node_modules/react-native/android"_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
I was having the same problem using my class SharedModule.
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [MyService]
}
}
}
Then I changed it putting directly in the app.modules this way
@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })
Obs: I'm using "@angular/core": "^6.0.2".
I hope its help you.
[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"
I suggest doing it in two steps:
# set fixed value to 'c2' where the condition is met
df.loc[df['c1'] == 'Value', 'c2'] = 10
# copy value from 'c3' to 'c2' where the condition is NOT met
df.loc[df['c1'] != 'Value', 'c2'] = df[df['c1'] != 'Value', 'c3']
Changed all dependencies to compile rather than implementation, then I rebuild the project without errors. Then I switched back to implementation rather than leaving it as compile.
What are dex files: Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app.
Reason for this exception: The DEX specification limits the total number of methods that can be referenced within a single DEX file to 65,536 (64K reference limit) —including Android framework methods, library methods, and methods in your own code.
Step 01. Add the following dependency as follows
For Non-Androidx Users,
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
For Androidx Users,
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
Step 02:
After adding those Sync projects and before you run the project make sure to Build a project before the run. otherwise, you will get an exception.
I faced this challenge with select2. It go resolved after I downloaded the latest version of the library and replaced the one (the css and js files) in my project.
If you're using Vuex
you can use https://github.com/vuejs/vuex-router-sync
Just initialize it in your main file with:
import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);
Each route change will update route
state object in Vuex
.
You can next create getter
to use the from
Object in route state or just use the state
(better is to use getters, but it's other story
https://vuex.vuejs.org/en/getters.html),
so in short it would be (inside components methods/values):
this.$store.state.route.from.fullPath
You can also just place it in <router-link>
component:
<router-link :to="{ path: $store.state.route.from.fullPath }">
Back
</router-link>
So when you use code above, link to previous path would be dynamically generated.
My solution is simple, don't look at the error notification in Build - Run tasks (which should be Execution failed for task ':app:compileDebugJavaWithJavac')
Just fix all errors in the Java Compiler section below it.
OK It's A Wrong Approach But If You Use it Like This :
compile "com.android.support:appcompat-v7:+"
Android Studio Will Use The Last Version It Has.
In My Case Was 26.0.0alpha-1.
You Can See The Used Version In External Libraries (In The Project View).
I Tried Everything But Couldn't Use Anything Above 26.0.0alpha-1, It Seems My IP Is Blocked By Google. Any Idea? Comment
Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.
To append 'api'
to my baseURL, I have my default baseURL set as,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
kubectl create can work with one object configuration file at a time. This is also known as imperative management
kubectl create -f filename|url
kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/
Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/
In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient
. When installing the npm package, a duplicate node_modules
directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client
is the module containing the service):
Obviously, the dependency to HttpClient
is not resolved correctly, as the locations of HttpClientModule
injected into the service (lives in the duplicate node_modules
directory) and the one injected in app.module
(the correct node_modules
) don't match.
I've also had this error in other setups containing a duplicate node_modules
directory due to a wrong npm install
call.
This defective setup also leads to the described runtime exception No provider for HttpClient!
.
TL;DR; Check for duplicate
node_modules
directories, if none of the other solutions work!
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
Try to add this in gradle
android {
defaultConfig {
multiDexEnabled true
}
}
Can you provide the code where you use this.props.history.push('/Page2');
?
Have you tried the goBack() method?
this.props.history.goBack();
It's listed here https://reacttraining.com/react-router/web/api/history
With a live example here https://reacttraining.com/react-router/web/example/modal-gallery
A self-explanatory simple one-liner to extract token for kubernetes dashboard login.
kubectl describe secret -n kube-system | grep deployment -A 12
Copy the token and paste it on the kubernetes dashboard under token sign in option and you are good to use kubernetes dashboard
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
This hasn't been shared here yet so hopefully it can help someone.
Following this link solved the same issue for me.
To begin, I'll note that I did not have to set multiDexEnabled to true.
First I set dependencies in my pubspec.yaml to
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^0.8.2
and ran flutter packages get
in my IDE's terminal.
Also I had to change the minimum target SDK version:
This alone may fix your problem; however I had to also do the following because some of my dependency versions were mismatched.
I had to open android/app/build.gradle
, then add the following line as the last line in the file:
apply plugin: 'com.google.gms.google-services'
Next, I had to open android/build.gradle
, then inside the buildscript tag, add a new dependency:
buildscript {
repositories {
// ...
}
dependencies {
// ...
classpath 'com.google.gms:google-services:3.2.1' // new
}
}
After this my app finally ran on the android emulator.
The link has a more complete walkthrough if you get stuck.
Also, to note, I did not have to set multiDexEnabled to true.
just Disable the Firewall and start again. it worked for me
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Update 2019
Why not use an input-group?
<div class="input-group col-md-4">
<input class="form-control py-2" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
And, you can make it appear inside the input using the border utils...
<div class="input-group col-md-4">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
Or, using a input-group-text
w/o the gray background so the icon appears inside the input...
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
</span>
</div>
Alternately, you can use the grid (row
>col-
) with no gutter spacing:
<div class="row no-gutters">
<div class="col">
<input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
</div>
<div class="col-auto">
<button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
Or, prepend the icon like this...
<div class="input-group">
<span class="input-group-prepend">
<div class="input-group-text bg-transparent border-right-0">
<i class="fa fa-search"></i>
</div>
</span>
<input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
Search
</button>
</span>
</div>
Demo of all Bootstrap 4 icon input options
I have found following solution to replace following code
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
It's work fine for me
All google services should be of same version, try matching every versions.
Correct one is :
implementation 'com.google.firebase:firebase-auth:11.6.0'
implementation 'com.google.firebase:firebase-database:11.6.0'
Incorrect Config is :
implementation 'com.google.firebase:firebase-auth:11.6.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
you forgot to add add alpha1 in module area
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
use maven repository in project area that's it
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
The problem seems to be that you are not returning something in the event that your first if
-case is false.
The error you are getting states that your arrow function (comment) => {
doesn't have a return statement. While it does for when your if
-case is true, it does not return anything for when it's false.
return this.props.comments.map((comment) => {
if (comment.hasComments === true) {
return (
<div key={comment.id}>
<CommentItem className="MainComment" />
{this.props.comments.map(commentReply => {
if (commentReply.replyTo === comment.id) {
return (
<CommentItem className="SubComment"/>
)
}
})
}
</div>
)
} else {
//return something here.
}
});
edit you should take a look at Kris' answer for how to better implement what you are trying to do.
While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).
I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.
I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.
If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.
Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.
Update 2: Same solution seems to be needed on iOS 13 beta builds as well.
Replace a hard coded version to + example:
implementation 'com.google.android.gms:play-services-base:+'
implementation 'com.google.android.gms:play-services-maps:+'
The title and subsequent question in the OP seem to boil down to:
Short answer:
A workspace is a virtual collection of folders opened simultaneously in VSCode and defined in a .code-workspace
file. Opening this file will open the collection of folders automatically. This is called a "multi-root" workspace.
The .code-workspace
file also defines workspace settings that are used by the instance of VSCode where the workspace is opened.
When a workspace is not defined, i.e. you open a folder on its own, you can create "workspace settings" that are saved in a .vscode\settings.json
file in the root of that folder structure.
In more detail:
VSCode uses the word "workspace" a little ambiguously in places. The first use to consider is in what is calls a multi-root workspace.
A multi-root workspace is a set of folders (the "roots") that are opened collectively in an instance of VSCode. There is no need for these folders to share parent folders; indeed that is the point since VSCode normally uses a single folder in the Explorer side-bar.
A multi-root workspace is defined by a .code-workspace
(JSON) file which contains both the list of folders to be included in the workspace and VSCode settings.
Regarding those workspace settings...
When you open File > Preferences > Settings the settings editor is shown. At the very least you should see a USER SETTINGS tab. These are the VSCode settings that are universal for your user account on your local machine. In Windows these are saved in %APPDATA%\Code\User\settings.json
.
Individual folders (often each of the "root" folders in a workspace) might have a .vscode
folder with their own settings.json
file. When opened individually, i.e. not as part of a workspace, the content of these settings.json
files is presented under the WORKSPACE SETTINGS tab, and ALL the settings in that file are used by the running VSCode instance.
When opening a multi-root workspace things behave differently. Firstly, the WORKSPACE SETTINGS tab shows the options set in the .code-workspace
file. Secondly, any folder with a settings.json
file will appear under a new FOLDER SETTINGS tab. Be aware that, when in a multi-root workspace, only a limited number of settings from each folder's settings.json
are used. I suggest you open the link above to read further.
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.android.support:cardview-v7:26.0.1'
UIKit
uses the topLayoutGuide & bottomLayoutGuide which is UIView
propertyiOS11+ uses safeAreaLayoutGuide which is also UIView
property
Enable Safe Area Layout Guide check box from file inspector.
Safe areas help you place your views within the visible portion of the overall interface.
In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
Use safe areas as an aid to laying out your content like UIButton
etc.
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.
The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active
print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones
Height of home indicator container is 34 points.
Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.
You can set constraints with respective of self.view.safeAreaLayoutGuide
as-
ObjC:
self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
Swift:
demoView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
} else {
NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
}
This error is caused by adding a support library instead of AndroidX. Make sure you use which one:
for AndroidX:
dependencies {
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'
}
If you aren't using AndroidX:
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
Also in manifest use the application class name instead of "android.support.multidex.MultiDexApplication" in the application tag(my application class name is G):
the mistake:
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
right:
<application
android:name=".G" >
...
</application>
After working through a couple of issues in dependent projects, like the accepted answer says, I was still getting this error. I could see the file did indeed exist at the location it was looking in, but for some reason Visual Studio would not recognize it. Rebuilding the solution would clear all dependent projects and then would not rebuild them, but building individually would generate the .dll's. I used msbuild <project-name>.csproj
in the developer PowerShell terminal in Visual Studio, meaning to get some more detailed debugging information--but it built for me instead! Try using msbuild
against persistant build errors; you can use the --verbosity:
option to get more output, as outlined in the docs.
For me I had to specifically stop the gradlew
and clear caches and this fixed my issues:
./gradlew --stop
// Delete all cache files in your project. With git: `git -xfd clean`
// Delete global cache dir. On Mac it is located in `~/.gradle/caches
Found here: https://github.com/realm/realm-java/issues/5650#issuecomment-355011135
This seems to be a little buggy in Pandas 0.23.4?
If there are np.nan values then this will throw an error as expected:
df['col'] = df['col'].astype(np.int64)
But doesn't change any values from float to int as I would expect if "ignore" is used:
df['col'] = df['col'].astype(np.int64,errors='ignore')
It worked if I first converted np.nan:
df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)
Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:
df['col'] = df['col'].replace(0,np.nan)
Below changes worked for me
I change distribution URL, located in gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
And
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
kotlin version 1.2.71
I have the same problem. I ran docker system prune -a --volumes
, docker network prune
, but neither helped me.
I use a VPN, I turned off the VPN and, after it docker started normal and was able to create a network. After that, you can enable VPN again.
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
Referring to the article https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
So the mechanics behind change detection actually works in a way that both change detection and verification digests are performed synchronously. That means, if we update properties asynchronously the values will not be updated when the verification loop is running and we will not get ExpressionChanged...
error. The reason we get this error is, during the verification process, Angular sees different values then what it recorded during change detection phase. So to avoid that....
1) Use changeDetectorRef
2) use setTimeOut. This will execute your code in another VM as a macro-task. Angular will not see these changes during verification process and you will not get that error.
setTimeout(() => {
this.isLoading = true;
});
3) If you really want to execute your code on same VM use like
Promise.resolve(null).then(() => this.isLoading = true);
This will create a micro-task. The micro-task queue is processed after the current synchronous code has finished executing hence the update to the property will happen after the verification step.
mode: 'no-cors'
won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.
What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin
is in a response, then browsers will relax that blocking and allow your code to access the response.
But if a site sends no Access-Control-Allow-Origin
in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors'
(in fact that’ll ensure your frontend code can’t access the response contents).
However, one thing that will work: if you send your request through a CORS proxy.
You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/
.
Prefix your request URL with your proxy URL; for example:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:
https://example.com
.https://example.com
.Access-Control-Allow-Origin
header to the response.The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends back the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight successful.
I can hit this endpoint,
http://catfacts-api.appspot.com/api/facts?number=99
via Postman
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin
response header.
http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin
response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin
response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin
response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin
header added is what the browser sees, so the browser lets your frontend code actually access the response.
So I am trying to pass in an object, to my Fetch which will disable CORS
You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.
But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.
No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.
You most likely never want to use mode: 'no-cors'
in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors'
actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.
As far as the cases when you would want to consider using mode: 'no-cors'
, see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:
In the limited case when you’re using JavaScript to put content from another origin into a <script>
, <link rel=stylesheet>
, <img>
, <video>
, <audio>
, <object>
, <embed>
, or <iframe>
element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href
or src
attribute for the element.
When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.
But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.
I have also tried to pass in the object
{ mode: 'opaque'}
There is no mode: 'opaque'
request mode — opaque
is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors
mode.
But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.
class _YourClassState extends State<YourClass> {
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.text = 'Your message';
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send message...'),
),
);
}
}
Another sneaky issue related to this is naming your columns with -
instead of _
.
Something like this will trigger an error at the moment your tables are getting created.
@Column(name="verification-token")
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
Update Android Studio and Gradle. Changing the respective updated gradle version in build.gradle file worked for me.
If you've recently updated, a reboot might solve this problem.
For anyone where none of these solutions are working, make sure that your request origin equals your request target, see this github issue.
I short, if you visit your website on 127.0.0.1:8000, then make sure that the requests you send are targeting your server on 127.0.0.1:8001 and not localhost:8001, although it might be the same target theoretically.
There are a few different points here:
.npmrc
file created.Running npm config ls -l
will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc
. But if you have never logged in (using npm login
) it will be empty. Simply log in to create it.
Another thing is #2. You can actually do that by putting a .npmrc
file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:
; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
Pointers
My solution would be after converting data to numerical type:
Top15[['Citable docs per Capita','Energy Supply per Capita']].corr()
Switching to the smartphone network & disabling the web security tool installed on my computer solved the problem.
I presume you meant false
instead of 'false'
Also, [disabled]
is expecting a Boolean
. You should avoid returning a null
.
This problem was created by a regression in a recent release. You can find the pull request that fixes this problem at https://github.com/facebook/react-native-fbsdk/pull/339
I had the same issue and I solved it by installing latest npm version:
npm install -g npm@latest
and then change the webpack.config.js
file to solve
- configuration.resolve.extensions[0] should not be empty.
now resolve extension should look like:
resolve: {
extensions: [ '.js', '.jsx']
},
then run npm start
.
As of Angular 8+ you can use clear()
to remove all controls in the FormArray:
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
console.log(arr.length); // 2
arr.clear();
console.log(arr.length); // 0
For previous versions the recommended way is:
while (arr.length) {
arr.removeAt(0);
}
It's caused by the table-responsive
class giving the table a property of display:block
, which is strange because this overwrites the table
classes original display:table
and is why the table shrinks when you add table-responsive
.
Most likely its down to bootstrap 4 still being in dev. You are safe to overwrite this property with your own class that sets display:table
and it won't effect the responsiveness of the table.
e.g.
.table-responsive-fix{
display:table;
}
The above answers work fine too, but I've found you can usually just use message.author.send("blah blah")
instead of message.author.sendMessage("blah blah")
.
-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js
.send tends to work better for me in general than .sendMessage, which sometimes runs into problems. Hope that helps a teeny bit!
With the use of the bootstrap 4 utilities you could horizontally center an element itself by setting the horizontal margins to 'auto'.
To set the horizontal margins to auto you can use mx-auto
. The m
refers to margin and the x
will refer to the x-axis (left+right) and auto
will refer to the setting. So this will set the left margin and the right margin to the 'auto' setting. Browsers will calculate the margin equally and center the element. The setting will only work on block elements so the display:block needs to be added and with the bootstrap utilities this is done by d-block
.
<button type="submit" class="btn btn-primary mx-auto d-block">Submit</button>
You can consider all browsers to fully support auto margin settings according to this answer Browser support for margin: auto so it's safe to use.
The bootstrap 4 class text-center
is also a very good solution, however it needs a parent wrapper element. The benefit of using auto margin is that it can be done directly on the button element itself.
You could use regex:
<input type="text" (keypress)="numericOnly($event)">
numericOnly(event): boolean {
let patt = /^([0-9])$/;
let result = patt.test(event.key);
return result;
}
If you are using lodash it can be done concisely with fromPairs
import {fromPairs} from 'lodash';
const object = fromPairs(Array.from(formData.entries()));
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
This works and I need to set the token only once in my app.js
:
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
Then I can make requests in my components without setting the header again.
"axios": "^0.19.0",
It's significantly easier to do this in Angular 6 than it was in previous versions, even when the checkbox information is populated asynchronously from an API.
The first thing to realise is that thanks to Angular 6's keyvalue
pipe we don't need to have to use FormArray
anymore, and can instead nest a FormGroup
.
First, pass FormBuilder into the constructor
constructor(
private _formBuilder: FormBuilder,
) { }
Then initialise our form.
ngOnInit() {
this.form = this._formBuilder.group({
'checkboxes': this._formBuilder.group({}),
});
}
When our checkbox options data is available, iterate it and we can push it directly into the nested FormGroup
as a named FormControl
, without having to rely on number indexed lookup arrays.
const checkboxes = <FormGroup>this.form.get('checkboxes');
options.forEach((option: any) => {
checkboxes.addControl(option.title, new FormControl(true));
});
Finally, in the template we just need to iterate the keyvalue
of the checkboxes: no additional let index = i
, and the checkboxes will automatically be in alphabetical order: much cleaner.
<form [formGroup]="form">
<h3>Options</h3>
<div formGroupName="checkboxes">
<ul>
<li *ngFor="let item of form.get('checkboxes').value | keyvalue">
<label>
<input type="checkbox" [formControlName]="item.key" [value]="item.value" /> {{ item.key }}
</label>
</li>
</ul>
</div>
</form>
It is not something obvious, but the caret
package has a function postResample()
that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are
and have to be accessed from the vector like this
library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]
However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.
caret
also has an R2()
method, although it's hard to find in the documentation.
The way to implement the normal coefficient of determination equation is:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss
Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.
Just Adding Instance Properties
For example, all components can access a global appName
, you just write one line code:
Vue.prototype.$appName = 'My App'
$
isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties.
Use document.write().
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var number = 123;_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>_x000D_
the value for number is:_x000D_
<script type="text/javascript">_x000D_
document.write(number)_x000D_
</script>_x000D_
</h1>_x000D_
</body>_x000D_
</html>
_x000D_
This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]): any[] {
const searchText = args[0];
const jsonKey = args[1];
let jsonKeyArray = [];
if (searchText == null || searchText === 'undefined') { return json; }
if (jsonKey.indexOf(',') > 0) {
jsonKey.split(',').forEach( function(key) {
jsonKeyArray.push(key.trim());
});
} else {
jsonKeyArray.push(jsonKey.trim());
}
if (jsonKeyArray.length === 0) { return json; }
// Start with new Array and push found objects onto it.
let returnObjects = [];
json.forEach( function ( filterObjectEntry ) {
jsonKeyArray.forEach( function (jsonKeyValue) {
if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
returnObjects.push(filterObjectEntry);
}
});
});
return returnObjects;
}
}
Now, instead of
jsonFilterBy:[ searchText, 'name']
you can do
jsonFilterBy:[ searchText, 'name, other, other2...']
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
The origin of this error lies in the fact that each and every promise is expected to handle promise rejection i.e. have a .catch(...) . you can avoid the same by adding .catch(...) to a promise in the code as given below.
for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
}).catch(function () {
console.log("Promise Rejected");
});
In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises. It's all about how you write your code. The following code will generate "unhandled promise rejection" even though we are handling catch
.
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
console.log("Promise Rejected");
});
The difference is that you don't handle .catch(...)
as chain but as separate. For some reason JavaScript engine treats it as promise without un-handled promise rejection.
Class WebMvcConfigurerAdapter
is deprecated as of 5.0 WebMvcConfigurer
has default methods and can be implemented directly without the need for this adapter. For this case:
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
}
See also: Same-Site flag for session cookie
I dislike the chaining thens. The second then does not have access to status. As stated before 'response.json()' returns a promise. Returning the then result of 'response.json()' in a acts similar to a second then. It has the added bonus of being in scope of the response.
return fetch(url, params).then(response => {
return response.json().then(body => {
if (response.status === 200) {
return body
} else {
throw body
}
})
})
Open gradle.properties
and use following code:
android.useAndroidX=false
android.enableJetifier=false
or U can use these dependencies too:
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.annotation:annotation:1.0.2'
Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.
It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.
Copy-paste ready code:
// SEE https://stackoverflow.com/a/46295049/286685
const loop = (arr, fn, busy, err, i=0) => {
const body = (ok,er) => {
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
catch(e) {er(e)}
}
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
return busy ? run(busy,err) : new Promise(run)
}
To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const items = ['one', 'two', 'three']_x000D_
_x000D_
loop(items, item => {_x000D_
console.info(item)_x000D_
})_x000D_
.then(() => console.info('Done!'))
_x000D_
Let's look at the handler function, nested loops and error handling.
The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
[],_x000D_
['one', 'two'],_x000D_
['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
console.info('Performing test ' + idx)_x000D_
return loop(test, (testCase) => {_x000D_
console.info(testCase)_x000D_
})_x000D_
.then(testNext)_x000D_
.catch(testFailed)_x000D_
}))_x000D_
.then(() => console.info('All tests done'))
_x000D_
Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
[],_x000D_
['one', 'two'],_x000D_
['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
console.info('Performing test ' + idx)_x000D_
loop(test, (testCase) => {_x000D_
if (idx == 2) throw new Error()_x000D_
console.info(testCase)_x000D_
})_x000D_
.then(testNext)_x000D_
.catch(testFailed) // <--- DON'T FORGET!!_x000D_
}))_x000D_
.then(() => console.error('Oops, test should have failed'))_x000D_
.catch(e => console.info('Succesfully caught error: ', e))_x000D_
.then(() => console.info('All tests done'))
_x000D_
Since writing this answer, I turned the above code in an NPM package.
npm install --save for-async
var forAsync = require('for-async'); // Common JS, or
import forAsync from 'for-async';
var arr = ['some', 'cool', 'array'];
forAsync(arr, function(item, idx){
return new Promise(function(resolve){
setTimeout(function(){
console.info(item, idx);
// Logs 3 lines: `some 0`, `cool 1`, `array 2`
resolve(); // <-- signals that this iteration is complete
}, 25); // delay 25 ms to make async
})
})
See the package readme for more details.
You can find the correct dependencies here apply changes to app.gradle and project.gradle and tell me about this, greetings!
Your apply plugin: 'com.google.gms.google-services' in app.gradle looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.example.personal.numbermania"
minSdkVersion 10
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
incremental true
javaMaxHeapSize "4g" //Here stablished how many cores you want to use your android studi 4g = 4 cores
}
buildTypes {
debug
{
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.google.firebase:firebase-ads:9.6.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.android.gms:play-services:9.6.1'
}
apply plugin: 'com.google.gms.google-services'
Add classpath to the project's gradle:
classpath 'com.google.gms:google-services:3.0.0'
Google play services library on SDK Manager:
I was facing the same problem and i solved this issue by changing the fireabseStorage version the same as the Firebase database version
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:17.0.0'
to
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
There is always this of course:
(async () => {
await ...
// all of the script....
})();
// nothing else
This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611
when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
This is an other way to solve your problem. So please check out below solution. Hope it will help you.
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
if let names = json["names"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
Open your php.ini and uncomment this line:
;extension=php_gd2.dll
Best explanation for X = aY + b
(in fact it f(x) = ax + b
)) is provided at https://math.stackexchange.com/a/906280/357701
A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
If you have a list of columns you want to concatenate and maybe you'd like to use some separator, here's what you can do
def concat_columns(df, cols_to_concat, new_col_name, sep=" "):
df[new_col_name] = df[cols_to_concat[0]]
for col in cols_to_concat[1:]:
df[new_col_name] = df[new_col_name].astype(str) + sep + df[col].astype(str)
This should be faster than apply
and takes an arbitrary number of columns to concatenate.
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
Cannot comment so posting this as an answer, which is somewhat in between @piRSquared/@cyril's solution and @cs95's:
As noted by @cs95, if your data contains NaNs or Nones, converting to string type will throw an error when trying to convert to int afterwards.
However, if your data consists of (numerical) strings, using convert_dtypes
will convert it to string type unless you use pd.to_numeric
as suggested by @cs95 (potentially combined with df.apply()
).
In the case that your data consists only of numerical strings (including NaNs or Nones but without any non-numeric "junk"), a possibly simpler alternative would be to convert first to float and then to one of the nullable-integer extension dtypes provided by pandas (already present in version 0.24) (see also this answer):
df['purchase'].astype(float).astype('Int64')
Note that there has been recent discussion on this on github (currently an -unresolved- closed issue though) and that in the case of very long 64-bit integers you may have to convert explicitly to float128
to avoid approximations during the conversions.
With the new angular class Renderer2
constructor(private renderer:Renderer2) {}
@ViewChild('one', { static: false }) d1: ElementRef;
ngAfterViewInit() {
const d2 = this.renderer.createElement('div');
const text = this.renderer.createText('two');
this.renderer.appendChild(d2, text);
this.renderer.appendChild(this.d1.nativeElement, d2);
}
I am not sure if this is still bothering you but take a look at this page for slack text formatting:
https://api.slack.com/docs/message-formatting#linking_to_urls
For example using Python and the slack API:
from slackclient import SlackClient
slack_client = SlackClient(your_slack_token)
link_as_text_example = '<http://www.hyperlinkcode.com/|Hyperlink Code>'
slack_client.api_call("chat.postMessage", channel=channel_to_post, text=link_as_text_example , as_user=True)
You can also send a more advance JSON following the link: https://api.slack.com/docs/message-attachments
Update (using renderer):
Note that the original Renderer service has now been deprecated in favor of Renderer2
as on Renderer2 official doc.
Furthermore, as pointed out by @GünterZöchbauer:
Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.
You can achieve this by using elementRef
as well as by ViewChild
. however it's not recommendable to use elementRef
due to:
as pointed out by official ng2 documentation.
elementRef
(Direct Access):export class MyComponent {
constructor (private _elementRef : ElementRef) {
this._elementRef.nativeElement.querySelector('textarea').focus();
}
}
ViewChild
(better approach):<textarea #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}"
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var
export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
renderer
:export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
constructor(private renderer: Renderer2){
}
ngAfterViewInit() {
//using selectRootElement instead of depreaced invokeElementMethod
this.renderer.selectRootElement(this.input["nativeElement"]).focus();
}
}
You can use ancestor
. I find that this is easier to read because the element you are actually selecting is at the end of the path.
//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]
You can also simply set your pandas column as list of id values with length same as of dataframe.
df['New_ID'] = range(880, 880+len(df))
Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
You can try installing one of the following localhost softwares:
There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com
)
It's Works
.ts -> pi = 3.1415
.html -> {{ pi | number : '1.0-2' }}
Ouput -> 3.14
https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html
this works for me!!! thanks!!
You want to do more than just getState
. You want to react to changes in the store.
If you aren't using react-redux, you can do this:
function rerender() {
const state = store.getState();
render(
<div>
{ state.items.map((item) => <p> {item.title} </p> )}
</div>,
document.getElementById('app')
);
}
// subscribe to store
store.subscribe(rerender);
// do initial render
rerender();
// dispatch more actions and view will update
But better is to use react-redux. In this case you use the Provider like you mentioned, but then use connect to connect your component to the store.
I was able to setup a SSL certificated for a domain AND multiple subdomains by using using --cert-name
combined with --expand
options.
See official certbot-auto documentation at https://certbot.eff.org/docs/using.html
Example:
certbot-auto certonly --cert-name mydomain.com.br \
--renew-by-default -a webroot -n --expand \
--webroot-path=/usr/share/nginx/html \
-d mydomain.com.br \
-d www.mydomain.com.br \
-d aaa1.com.br \
-d aaa2.com.br \
-d aaa3.com.br
Your can send notification to all devices using "/topics/all"
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/all",
"notification":{ "title":"Notification title", "body":"Notification body", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" },
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
Merlin's answer is better and super easy, but we don't need a lambda function. The evaluation of dictionary can be safely ignored by either of the following two ways as illustrated below:
Way 1: Two steps
# step 1: convert the `Pollutants` column to Pandas dataframe series
df_pol_ps = data_df['Pollutants'].apply(pd.Series)
df_pol_ps:
a b c
0 46 3 12
1 36 5 8
2 NaN 2 7
3 NaN NaN 11
4 82 NaN 15
# step 2: concat columns `a, b, c` and drop/remove the `Pollutants`
df_final = pd.concat([df, df_pol_ps], axis = 1).drop('Pollutants', axis = 1)
df_final:
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
Way 2: The above two steps can be combined in one go:
df_final = pd.concat([df, df['Pollutants'].apply(pd.Series)], axis = 1).drop('Pollutants', axis = 1)
df_final:
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
Note: It might be troublesome later on, I used it as a last resort since non of the solutions provided above and others did not work in my case:
Add-Migration "migration-name"
Up(){ //paste here }
Update-Database
if you have Firebase included also, make them of same version as the error says.
In my case I am using a variation of the solution proposed by @seanwright:
https://github.com/NetanelBasal/ngx-take-until-destroy
It's a file used in the ngx-rocket / starter-kit project. You can access it here until-destroyed.ts
The component would look like so
/**
* RxJS operator that unsubscribe from observables on destory.
* Code forked from https://github.com/NetanelBasal/ngx-take-until-destroy
*
* IMPORTANT: Add the `untilDestroyed` operator as the last one to
* prevent leaks with intermediate observables in the
* operator chain.
*
* @param instance The parent Angular component or object instance.
* @param destroyMethodName The method to hook on (default: 'ngOnDestroy').
*/
import { untilDestroyed } from '../../core/until-destroyed';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
interval(1000)
.pipe(untilDestroyed(this))
.subscribe(val => console.log(val));
// ...
}
// This method must be present, even if empty.
ngOnDestroy() {
// To protect you, an error will be thrown if it doesn't exist.
}
}
We are missing the setMaster("local[*]") to set. Once we added then problem get resolved.
Problem:
val spark = SparkSession
.builder()
.appName("Spark Hive Example")
.config("spark.sql.warehouse.dir", warehouseLocation)
.enableHiveSupport()
.getOrCreate()
solution:
val spark = SparkSession
.builder()
.appName("Spark Hive Example")
.config("spark.sql.warehouse.dir", warehouseLocation)
.enableHiveSupport()
.master("local[*]")
.getOrCreate()
I can resolve this problem using the following code using Bootstrap 4:
<table class="table">
<tbody>
<tr class="d-flex">
<th class="col-3" scope="row">Indicador:</th>
<td class="col-9">this is my indicator</td>
</tr>
<tr class="d-flex">
<th class="col-3" scope="row">Definición:</th>
<td class="col-9">This is my definition</td>
</tr>
</tbody>
</table>
<pre>
<input type="text" #titleInput>
<button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
</pre>
{
addTodo(title:string) {
console.log(title);
}
}
You can divide column of dtype
timedelta
by np.timedelta64(1, 'D')
, but output is not int
, but float
, because NaN
values:
df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
First_Date Second Date Difference
0 2016-02-09 2015-11-19 82.0
1 2016-01-06 2015-11-30 37.0
2 NaT 2015-12-04 NaN
3 2016-01-06 2015-12-08 29.0
4 NaT 2015-12-09 NaN
5 2016-01-07 2015-12-11 27.0
6 NaT 2015-12-12 NaN
7 NaT 2015-12-14 NaN
8 2016-01-06 2015-12-14 23.0
9 NaT 2015-12-15 NaN
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
I'm assuming that you want to be able to view data present in your container everytime you connect to it from outside. To do this, you will have to persist data on the postgres image.
If you dont have persistant data, you will have to repeat everything you did the first time.
Steps 3, 5, 6, 7, and 8 answer your question directly.
Here is the detailed overview of the entire process I followed on Windows 10 powershell (commands are the same in Linux and macOS as well):
Step 1: Start powershell in non-admin mode
Step 2: Download postgres docker image:
docker pull postgres:latest
Step 3: Start docker container in detached mode and persist data on postgres image by creating a volume and binding it to a destination
(Note: by default 5432 is the default port that is used; but state it explicitly to prevent connection errors from clients like pgadmin, dbeaver, etc.)
docker run --name postgres-test -e POSTGRES_PASSWORD=password -p 5432:5432 -v postgres-data:/var/lib/postgresql/data -d postgres:latest
Step 4: Check status of running containers
docker ps -a
Step 5: Go inside container_name in interactive mode
(Note: commands like ls, pwd, etc. can be executed here if you've checked linux containers during installation)
docker exec -it postgres-test psql -U postgres
Step 6: Create sample data. At this point, you can play with psql
commands in the following manner:
# CREATE DATABASE test;
# \c test
# CREATE TABLE test_table(something int);
# INSERT INTO test_table VALUES (123);
# SELECT * FROM test_table;
# \q
Step 7: Open a database client application like pgadmin
or dbeaver
and enter the below in the connection fields:
Host: localhost
Database: test
User: postgres
Password: password
Step 8: Enter the query select * from test_table
in the query editor and you should be able to see the output 123
Using Value2
gives a performance benefit. As per Charles Williams blog
Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.
So
DirArray = [a1:a5].Value2
To get the latest images use docker-compose build --pull
I use below command which is really 3 in 1
docker-compose down && docker-compose build --pull && docker-compose up -d
This command will stop the services, pulls the latest image and then starts the services.
For me the only thing that works is to add to repositories
maven {
url "https://maven.google.com"
}
It should look like this:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
Duplicate name Classes
like
class BackGroundTask extends AsyncTask<String, Void, Void> {
and
class BackgroundTask extends AsyncTask<String, Void, Void> {
You need to add else
in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.
sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x)
You need to create custom background like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<shape>
<gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear"/>
<stroke android:width="1dp" android:color="#504a4b"/>
<corners android:radius="5dp"/>
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
</shape>
</item>
<item>
<bitmap android:gravity="bottom|right" android:src="@drawable/drop_down"/> // you can place your dropdown image
</item>
</layer-list>
</item>
</selector>
Then create style for spinner like this:
<style name="spinner_style">
<item name="android:background">@drawable/YOURCUSTOMBACKGROUND</item>
<item name="android:layout_marginLeft">5dp</item>
<item name="android:layout_marginRight">5dp</item>
<item name="android:layout_marginBottom">5dp</item>
</style>
after that apply this style to your spinner
In your app's build.gradle
add the following:
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
Enforces Gradle to only compile the version number you state for all dependencies, no matter which version number the dependencies have stated.
There are 2 methods technically same
First put your cursor on the word and press F2. Replace your word and press Enter.
First put your cursor on the word and left click it. Click "Rename Symbol" option. Replace your word and press Enter.
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
? Copy .aar package in app/libs.
? Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
In my case, if your version of build tools in the build.gradle file in the root folder like :
classpath 'com.android.tools.build:gradle:3.x.x' <--- version of tools
is not supported by the Gradle installed in your project, you can check the build tools/plugin supported versions here, and make sure that the version installed in your project is supported by that version of Gradle.
You don't need to upgrade Gradle, you just check if it supports the plugin installed in your project or not.
You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.
var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)
You can change default options by using Chart.defaults.global
in your javascript file. So you want to change legend and tooltip options.
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips.enabled = false;
Here is a working fiddler.
Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/
.tinted-image {
width: 300px;
height: 200px;
background:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* bottom, image */
url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}
Additionnally to hotkey
's good answer, here is how I choose among the two in practice:
lateinit
is for external initialisation: when you need external stuff to initialise your value by calling a method.
e.g. by calling:
private lateinit var value: MyClass
fun init(externalProperties: Any) {
value = somethingThatDependsOn(externalProperties)
}
While lazy
is when it only uses dependencies internal to your object.
Official npm page suggest a structured method to update angular version for both global and local scenarios.
1.First of all, you need to uninstall the current angular from your system.
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm uninstall -g @angular/cli
2.Clean up the cache
npm cache clean
EDIT
As pointed out by @candidj
npm cache clean
is renamed as npm cache verify
from npm 5 onwards
3.Install angular globally
npm install -g @angular/cli@latest
4.Local project setup if you have one
rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install
Please check the same down on the link below:
https://www.npmjs.com/package/@angular/cli#updating-angular-cli
This will solve the problem.
<div class="w-100 d-lg-none mt-4"></div>
I created 4 cards and place this code between second and third card, try this.
For mysql 8.0 the command to disable password validation component is:
UNINSTALL COMPONENT 'file://component_validate_password';
To install it back again, the command is:
INSTALL COMPONENT 'file://component_validate_password';
If you just want to change the policy of password validation plugin:
SET GLOBAL validate_password.policy = 0; // For LOW
SET GLOBAL validate_password.policy = 1; // For MEDIUM
SET GLOBAL validate_password.policy = 2; // For HIGH
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
justify-content: space-between
and the order
property.justify-content: space-between
and reverse the order of the divs..parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
open key.properties and check your path is correct. (replace from \ to /)
example:-
replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"
So do the following ,
Lets say your branch name is my_branch and this has the extra commits.
git checkout -b my_branch_with_extra_commits
(Keeping this branch saved under a different name)gitk
(Opens git console)git checkout my_branch
gitk
(This will open the git console )reset branch to here
" git pull --rebase origin branch_name_to _merge_to
git cherry-pick <SHA you copied in step 3. >
Now look at the local branch commit history and make sure everything looks good.
The error message:
merge: remote/master - not something we can merge
is saying that Git doesn't recognize remote/master
. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".
Think of "remotes" as an alias for the url to your Git server. master
is your locally checked-out version of the branch. origin/master
is the latest version of master
from your Git server that you have fetched (downloaded). A fetch
is always safe because it will only update the "origin/x" version of your branches.
So, to get your master
branch back in sync, first download the latest content from the git server:
git fetch
Then, perform the merge:
git merge origin/master
...But, perhaps the better approach would be:
git pull origin master
The pull
command will do the fetch
and merge
for you in one step.
I want to give my resolution, it work when i replace the line [session = tf.Session()]
with [sess = tf.InteractiveSession()]
. Hope this will be useful to others.
On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line
import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')
Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64
, and then isnan
check should work
You can simply use this:
'07311954' in df.date.values
which returns True
or False
Here is the further explanation:
In pandas, using in
check directly with DataFrame and Series (e.g. val in df
or val in series
) will check whether the val
is contained in the Index.
BUT you can still use in
check for their values too (instead of Index)! Just using val in df.col_name.values
or val in series.values
. In this way, you are actually checking the val
with a Numpy array.
And .isin(vals)
is the other way around, it checks whether the DataFrame/Series values are in the vals
. Here vals
must be set or list-like. So this is not the natural way to go for the question.
Add multiDexEnabled
true in your defaultConfig in the app level gradle
.
defaultConfig {
applicationId "your application id"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
This error occurs because you don't have proper statements at the Manifest root such:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.test">
So you should remove additional texts in it.
From your react native folder run:
cd android && gradlew clean
THEN
cd .. && react-native run-android
Notes:
For mac you may need to change
gradlew
to./gradlew
For the command prompt you may need to change the
&&
to&
For powershell you may need to change the
&&
to;
andgradlew
to.\gradlew.bat
Each command can also be run individually like so
cd android
thengradlew clean
thencd ..
thenreact-native run-android
On top of mentioning your environment variable for HADOOP_HOME
in windows as C:\winutils
, you also need to make sure you are the administrator of the machine. If not and adding environment variables prompts you for admin credentials (even under USER
variables) then these variables will be applicable once you start your command prompt as administrator.
The solution of @bunji works for me, but default options don't always give a good result. I added some useful parameter to tweak the appearance of the table.
import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import numpy as np
dates = pd.date_range('20130101',periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
df.index = [item.strftime('%Y-%m-%d') for item in df.index] # Format date
fig, ax = plt.subplots(figsize=(12, 2)) # set size frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
ax.set_frame_on(False) # no visible frame, uncomment if size is ok
tabla = table(ax, df, loc='upper right', colWidths=[0.17]*len(df.columns)) # where df is your data frame
tabla.auto_set_font_size(False) # Activate set fontsize manually
tabla.set_fontsize(12) # if ++fontsize is necessary ++colWidths
tabla.scale(1.2, 1.2) # change size table
plt.savefig('table.png', transparent=True)
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
-We can create ParentComponent and with handleInputChange method to update the ParentComponent state. Import the ChildComponent and we pass two props from parent to child component ie.handleInputChange function and count.
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
count: '',
};
}
handleInputChange(e) {
const { value, name } = e.target;
this.setState({ [name]: value });
}
render() {
const { count } = this.state;
return (
<ChildComponent count={count} handleInputChange={this.handleInputChange} />
);
}
}
Now we create the ChildComponent file and save as ChildComponent.jsx. This component is stateless because the child component doesn't have a state. We use the prop-types library for props type checking.
import React from 'react';
import { func, number } from 'prop-types';
const ChildComponent = ({ handleInputChange, count }) => (
<input onChange={handleInputChange} value={count} name="count" />
);
ChildComponent.propTypes = {
count: number,
handleInputChange: func.isRequired,
};
ChildComponent.defaultProps = {
count: 0,
};
export default ChildComponent;
For me the issue was I had an invalid request code. I choose 0xDEADBEEF as a request code and it was silently failing (maybe it's cast to something smaller than 32-bit somewhere internally?) If I choose 255 everything worked fine as NightSkyDev described above.
I've had success with
<span class="someclass"></span>
Caveat : the class must already exist on the site.
Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:
First verify this is a PATH issue:
Check if the path returned by which jupyter
is covered by the sudo user:
sudo env | grep ^PATH
(As opposed to the current user: env | grep ^PATH
)
If its not covered - add a soft link from it to one of the covered paths. For ex:
sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin
Now you sould be able to run:
sudo jupyter notebook
There is no magic method that will do what you want. The answer is simply name it appropriately. asdict
is a reasonable choice for a plain conversion to dict
, inspired primarily by namedtuple
. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.
Other answers suggest using __iter__
, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.
I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.
The steps are :
You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers
Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.
Edit : you have to repeat the steps every time you will go on the production site.
I had to stopPropigation
and preventDefault
in order to prevent a button expanding an accordion item that it sat above.
So...
@Component({
template: `
<button (click)="doSomething($event); false">Test</button>
`
})
export class MyComponent {
doSomething(e) {
e.stopPropagation();
// do other stuff...
}
}
Add
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
in package.json
then run react-native link
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long
value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.
using for loop
lst = [5, 20 ,15]
product = []
for i in lst:
product.append(i*5)
print product
using list comprehension, this is also same as using for-loop but more 'pythonic'
lst = [5, 20 ,15]
prod = [i * 5 for i in lst]
print prod
As mentioned by Alejandro Corredor it is a simple scope error. The subscribe
is run asynchronously and the open
must be placed in that context, so that the data finished loading when we trigger the download.
That said, there are two ways of doing it. As the docs recommend the service takes care of getting and mapping the data:
//On the service:
downloadfile(runname: string, type: string){
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
.catch(this.logAndPassOn);
}
Then, on the component we just subscribe and deal with the mapped data. There are two possibilities. The first, as suggested in the original post, but needs a small correction as noted by Alejandro:
//On the component
downloadfile(type: string){
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => window.open(window.URL.createObjectURL(data)),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
}
The second way would be to use FileReader. The logic is the same but we can explicitly wait for FileReader to load the data, avoiding the nesting, and solving the async problem.
//On the component using FileReader
downloadfile(type: string){
var reader = new FileReader();
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(res => reader.readAsDataURL(res),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no');
}
}
Note: I am trying to download an Excel file, and even though the download is triggered (so this answers the question), the file is corrupt. See the answer to this post for avoiding the corrupt file.
For Android Studio 3.2.1 Update your
Gradle Version 4.6
Android plugin version 3.2.1
I have got the same issue and I found that variable name and method were missing. Double check the layout file or look for build error that says DATABINDINGISSUE, or invalidate and restart android studio. It should work.
As Tyler has suggested in one of the comments here, using
max-width: 100%;
on the child may work (worked for me). Using align-self: stretch
only works if you aren't using align-items: center
(which I did). width: 100%
only works if you haven't multiple childs inside your flexbox which you want to show side by side.
There is one other reason that can cause Test Explorer not showing any tests, and it has to do with the new portable .pdb
file format introduced with Visual Studio 2017 / for .NET Core which can break some VS tooling. (Background: See the bug report "Mono.Cecil causes OutOfMemoryException with new .csproj PDBs".)
.pdb
(debug symbols) format?If you see output like to the following (possibly repeated once for each of your tests), then you've got the problem described in this answer:
Exception System.OutOfMemoryException, Exception converting <SignatureOfYourTestMethod>
Array dimensions exceeded supported range.
none
, pdb-only
, or full
, but NOT portable
. It is this last setting that causes the tests to not be found..pdb
files before rebuilding. Now your tests should be back.I stumbled on this while looking for a better way than what I had arrived at. Having read the answers and trying them out I thought it was worth posting what I was doing as the other answers didn't feel as succinct for me. It was important for me to only have to write a short amount of code each time I set up a new interface. I settled on...
Using a custom generic deepCopy function:
deepCopy = <T extends {}>(input: any): T => {
return JSON.parse(JSON.stringify(input));
};
Define your interface
interface IX {
a: string;
b: any;
c: AnotherType;
}
... and define the defaults in a separate const.
const XDef : IX = {
a: '',
b: null,
c: null,
};
Then init like this:
let x : IX = deepCopy(XDef);
That's all that's needed..
.. however ..
If you want to custom initialise any root element you can modify the deepCopy function to accept custom default values. The function becomes:
deepCopyAssign = <T extends {}>(input: any, rootOverwrites?: any): T => {
return JSON.parse(JSON.stringify({ ...input, ...rootOverwrites }));
};
Which can then be called like this instead:
let x : IX = deepCopyAssign(XDef, { a:'customInitValue' } );
Any other preferred way of deep copy would work. If only a shallow copy is needed then Object.assign would suffice, forgoing the need for the utility deepCopy
or deepCopyAssign
function.
let x : IX = object.assign({}, XDef, { a:'customInitValue' });
Known Issues
deepCopyAssign
to iterate and check types before assigning.I was curious to see the performance difference between these
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x) / np.sum(np.exp(x), axis=0)
def softmaxv2(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
def softmaxv3(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / np.sum(e_x, axis=0)
def softmaxv4(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x - np.max(x)) / np.sum(np.exp(x - np.max(x)), axis=0)
x=[10,10,18,9,15,3,1,2,1,10,10,10,8,15]
Using
print("----- softmax")
%timeit a=softmax(x)
print("----- softmaxv2")
%timeit a=softmaxv2(x)
print("----- softmaxv3")
%timeit a=softmaxv2(x)
print("----- softmaxv4")
%timeit a=softmaxv2(x)
Increasing the values inside x (+100 +200 +500...) I get consistently better results with the original numpy version (here is just one test)
----- softmax
The slowest run took 8.07 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 17.8 µs per loop
----- softmaxv2
The slowest run took 4.30 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv3
The slowest run took 4.06 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv4
10000 loops, best of 3: 23 µs per loop
Until.... the values inside x reach ~800, then I get
----- softmax
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: overflow encountered in exp
after removing the cwd from sys.path.
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
after removing the cwd from sys.path.
The slowest run took 18.41 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv2
The slowest run took 4.18 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.8 µs per loop
----- softmaxv3
The slowest run took 19.44 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv4
The slowest run took 16.82 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.7 µs per loop
As some said, your version is more numerically stable 'for large numbers'. For small numbers could be the other way around.
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply
method as well as lambda
and converting datetime format. Line if x != '' else x
will take care of all empty spaces or nulls accordingly.
df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
Although it has been a while since this question was asked, I will post my answer hoping it helps somebody.
Disclaimer: I know this solution is not standard, but I think it works well.
import pandas as pd
import numpy as np
data = np.array([[10, 2, 10, 10],
[10, 3, 60, 100],
[np.nan] * 4,
[10, 22, 280, 250]]).T
idx = pd.date_range('20150131', end='20150203')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df
A B C D
=================================
2015-01-31 10 10 NaN 10
2015-02-01 2 3 NaN 22
2015-02-02 10 60 NaN 280
2015-02-03 10 100 NaN 250
def calculate(mul, add):
global value
value = value * mul + add
return value
value = df.loc['2015-01-31', 'D']
df.loc['2015-01-31', 'C'] = value
df.loc['2015-02-01':, 'C'] = df.loc['2015-02-01':].apply(lambda row: calculate(*row[['A', 'B']]), axis=1)
df
A B C D
=================================
2015-01-31 10 10 10 10
2015-02-01 2 3 23 22
2015-02-02 10 60 290 280
2015-02-03 10 100 3000 250
So basically we use a apply
from pandas and the help of a global variable that keeps track of the previous calculated value.
Time comparison with a for
loop:
data = np.random.random(size=(1000, 4))
idx = pd.date_range('20150131', end='20171026')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df.C = np.nan
df.loc['2015-01-31', 'C'] = df.loc['2015-01-31', 'D']
%%timeit
for i in df.loc['2015-02-01':].index.date:
df.loc[i, 'C'] = df.loc[(i - pd.DateOffset(days=1)).date(), 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']
3.2 s ± 114 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
data = np.random.random(size=(1000, 4))
idx = pd.date_range('20150131', end='20171026')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df.C = np.nan
def calculate(mul, add):
global value
value = value * mul + add
return value
value = df.loc['2015-01-31', 'D']
df.loc['2015-01-31', 'C'] = value
%%timeit
df.loc['2015-02-01':, 'C'] = df.loc['2015-02-01':].apply(lambda row: calculate(*row[['A', 'B']]), axis=1)
1.82 s ± 64.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So 0.57 times faster on average.
Just Change in build.gradle file
classpath 'com.android.tools.build:gradle:1.3.0'
To
classpath 'com.android.tools.build:gradle:2.0.0'
Now GoTo
-> menu choose File
-> Invalidate Caches/Restart
...
Choose first option: Invalidate and Restart
Android Studio would restart.
After this, it should work normally.
Try {{model?.person.name}}
this should wait for model to not be undefined
and then render.
Angular 2 refers to this ?.
syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:
The Elvis Operator ( ?. ) and null property paths
The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
The current hero's name is {{currentHero?.firstName}}
Let’s elaborate on the problem and this particular solution.
What happens when the following data bound title property is null?
The title is {{ title }}
The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.
Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.
The null hero's name is {{nullHero.firstName}}
JavaScript throws a null reference error and so does Angular:
TypeError: Cannot read property 'firstName' of null in [null]
Worse, the entire view disappears.
We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.
On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.
While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.
Unfortunately, our app crashes when the currentHero is null.
We could code around that problem with NgIf
<!--No hero, div not displayed, no error -->
<div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>
Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.
The null hero's name is {{nullHero && nullHero.firstName}}
These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.
The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.
<!-- No hero, no problem! -->
The null hero's name is {{nullHero?.firstName}}
It works perfectly with long property paths too:
a?.b?.c?.d
Just as most have said, but dont forget to set LifeCycleOwner
Sample in Java
i.e
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
BindingClass binding = DataBindingUtil.inflate(inflater, R.layout.fragment_layout, container, false);
ModelClass model = ViewModelProviders.of(getActivity()).get(ViewModelClass.class);
binding.setLifecycleOwner(getActivity());
binding.setViewmodelclass(model);
//Your codes here
return binding.getRoot();
}
If this happened to you after renaming your application package name, then you need to update the following:
1)google-services.json file in your application by looking up in the file for "package_name" attribute and update it with the new package name.
2)Update your application client Credentials in Google Developers Console by going to the Credentials
and selecting your android client key then update the package name as well with the new one.
Hope this will help.
I got the same error in the same tutorial because I had forgot the export keyword for the interface.
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
You cannot load NPM modules without uploading a .zip
file, but you can actually get this process down to two quick command lines.
Here's how:
Put your Lambda function file(s) in a separate directory. This is because you install npm
packages locally for Lambda and you want to be able to isolate and test what you will upload to Lambda.
Install your NPM packages locally with npm install packageName
while you're in your separate Lambda directory you created in step #1.
Make sure your function works when running locally: node lambdaFunc.js
(you can simply comment out the two export.handler
lines in your code to adapt your code to run with Node locally).
Go to the Lambda's directory and compress the contents, make sure not to include the directory itself.
zip -r lambdaFunc.zip .
If you have the aws-cli
installed, which I suggest having if you want to make your life easier, you can now enter this command:
aws lambda update-function-code --function-name lambdaFunc \
--zip-file fileb://~/path/to/your/lambdaFunc.zip
(no quotes around the lambdaFunc part above in case you wonder as I did)
Now you can click test in the Lambda console.
I suggest adding a short alias for both of the above commands. Here's what I have in mine for the much longer Lambda update command:
alias up="aws lambda update-function-code --function-name lambdaFunc \
--zip-file fileb://~/path/to/your/lambdaFunc.zip"
In place of 1.+ use the latest version of crashlytics -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
}
you should use this way -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
}
your problem will be resolved for sure. Happy coding !!
Simply You need to pass resizeMode like this to fit in your image in containing view
<Image style={styles.imageStyle} resizeMode={'cover'} source={item.image}/>
const style = StyleSheet.create({
imageStyle: {
alignSelf: 'center',
height:'100%',
width:'100%'
},]
})
I had the same problem. The problem was that the labels were in a column format while it expected it in a row.
use np.ravel()
knn.score(training_set, np.ravel(training_labels))
Hope this solves it.
Ideally you should create angualr 2 pipe for that. But you can do this trick.
<ng-container *ngFor="item in itemsList">
<div*ngIf="conditon(item)">{{item}}</div>
</ng-container>
Here are three different checkmark styles you can use:
ul:first-child li:before { content:"\2713\0020"; } /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; } /* OR */_x000D_
ul:last-child li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
References:
If you are using Sass:
$card-column-sizes: (
xs: 2,
sm: 3,
md: 4,
lg: 5,
);
@each $breakpoint-size, $column-count in $card-column-sizes {
@include media-breakpoint-up($breakpoint-size) {
.card-columns {
column-count: $column-count;
column-gap: 1.25rem;
.card {
display: inline-block;
width: 100%; // Don't let them exceed the column width
}
}
}
}
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
You can put into for loop, and use zip to pairs each column name in two array.
new_name = ["id", "sepal_length_cm", "sepal_width_cm", "petal_length_cm", "petal_width_cm", "species"]
new_df = df
for old, new in zip(df.columns, new_name):
new_df = new_df.withColumnRenamed(old, new)
When I had this issue with tf.train.string_input_producer()
and tf.train.batch()
initializing the local variables before I started the Coordinator solved the problem. I had been getting the error when I initialized the local variables after starting the Coordinator.
According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:
(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x)
Correct implementation of Box-Cox transformation formula by boxcox() in R:
https://www.r-bloggers.com/on-box-cox-transform-in-regression-models/
A great comparison between Box-Cox transformation and Tukey transformation. http://onlinestatbook.com/2/transformations/box-cox.html
One could also find the Box-Cox transformation formula on Wikipedia: en.wikipedia.org/wiki/Power_transform#Box.E2.80.93Cox_transformation
Please correct me if I misunderstood it.
json.loads()
takes a JSON encoded string, not a filename. You want to use json.load()
(no s
) instead and pass in an open file object:
with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
data = json.load(jsonfile)
The open()
command produces a file object that json.load()
can then read from, to produce the decoded Python object for you. The with
statement ensures that the file is closed again when done.
The alternative is to read the data yourself and then pass it into json.loads()
.
You could try using df['column'].str.
and then use any string function. Pandas documentation includes those like split
The service :
import 'rxjs/add/operator/map';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';
@Injectable()
export class ItemService {
private api = "your_api_url";
constructor(private http: Http) {
}
toSaveItem(item) {
return new Promise((resolve, reject) => {
this.http
.post(this.api + '/items', { item: item })
.map(res => res.json())
// This catch is very powerfull, it can catch all errors
.catch((err: Response) => {
// The err.statusText is empty if server down (err.type === 3)
console.log((err.statusText || "Can't join the server."));
// Really usefull. The app can't catch this in "(err)" closure
reject((err.statusText || "Can't join the server."));
// This return is required to compile but unuseable in your app
return Observable.throw(err);
})
// The (err) => {} param on subscribe can't catch server down error so I keep only the catch
.subscribe(data => { resolve(data) })
})
}
}
In the app :
this.itemService.toSaveItem(item).then(
(res) => { console.log('success', res) },
(err) => { console.log('error', err) }
)
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e
f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)
Here is the way to achieve it - though I do not yet know how to add the alias in this case
See the example below - Using Maps
val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))
val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)
val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")
claimRDD2DF1.groupBy("pid").agg(exprs) show false
TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.
For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.
However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b
to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe
, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.
FailedPreconditionError: Attempting to use uninitialized value is one of the most frequent errors related to tensorflow. From official documentation, FailedPreconditionError
This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.
In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1
. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading
Basically to initialize the variable you have 3 options:
tf.global_variables_initializer()
tf.variables_initializer(list_of_vars)
. Notice that you can use this function to mimic global_variable_initializer: tf.variable_initializers(tf.global_variables())
var_name.initializer
I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables
and check is_variable_initialized
.
Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:
df = pd.DataFrame(np.ones((5,6)),columns=['one','two','three',
'four','five','six'])
df.one *=5
df.two = df.two*5
df.three = df.three.multiply(5)
df['four'] = df['four']*5
df.loc[:, 'five'] *=5
df.iloc[:, 5] = df.iloc[:, 5]*5
which results in
one two three four five six
0 5.0 5.0 5.0 5.0 5.0 5.0
1 5.0 5.0 5.0 5.0 5.0 5.0
2 5.0 5.0 5.0 5.0 5.0 5.0
3 5.0 5.0 5.0 5.0 5.0 5.0
4 5.0 5.0 5.0 5.0 5.0 5.0
This answer relevant for Vue.js version 2
<th
class="initial "
v-on:click="myFilter"
v-bind:class="{ active: isActive }"
>
<span class="wkday">M</span>
</th>
The rest of the answer by Douglas is still applicable (setting up the new Vue instance with isActive: false
, etc).
Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers
Full Example (Python 3):
For Python 2.x look into Note below
import re
mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)
Prints:
['cat', 'wildcat', 'thundercat']
Note:
For Python 2.x developers, filter
returns a list already. In Python 3.x filter
was changed to return an iterator so it has to be converted to list
(in order to see it printed out nicely).
And this:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
suppose to be solution of deprecated:
FirebaseInstanceId.getInstance().getToken()
EDIT
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener
) is correct way to do it.
Kotlin:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}
After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.
You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.
Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.
Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.
Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.
Application.Exit
End
will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.
Best regrads,
request.remote_ip
is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
In error situations, I wanted to return a specific error details class, in whatever format the client requested instead of the happy path object.
I want to have my controller methods return the domain specific happy path object and to throw an exception otherwise.
The problem I had was that the HttpResponseException constructors do not allow domain objects.
This is what I eventually came up with
public ProviderCollection GetProviders(string providerName)
{
try
{
return _providerPresenter.GetProviders(providerName);
}
catch (BadInputValidationException badInputValidationException)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
badInputValidationException.Result));
}
}
Result
is a class that contains error details, while ProviderCollection
is my happy path result.
Just use watch nvidia-smi
, it will output the message by 2s interval in default.
For example, as the below image:
You can also use watch -n 5 nvidia-smi
(-n 5 by 5s interval).
STATICFILES_DIRS
is used in development and STATIC_ROOT
in production,
STATICFILES_DIRS
and STATIC_ROOT
should not have same folder name,
If you need to use the exact same static folder in development and production, try this method
include this in settings.py
import socket
HOSTNAME = socket.gethostname()
# if hostname same as production url name use STATIC_ROOT
if HOSTNAME == 'www.example.com':
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
else:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
Here you go:
InputStream is = new ByteArrayInputStream( myString.getBytes() );
Update For multi-byte support use (thanks to Aaron Waibel's comment):
InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());
Please see ByteArrayInputStream manual.
It is safe to use a charset argument in String#getBytes(charset) method above.
After JDK 7+ you can use
java.nio.charset.StandardCharsets.UTF_16
instead of hardcoded encoding string:
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());
I tried the following three methods, my file size is 1M, and I got results:
I run the program several times it looks that BufferedReader is faster.
@Test
public void testLargeFileIO_Scanner() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
InputStream inputStream = new FileInputStream(fileName);
try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
//System.out.println(line);
}
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Scanner Time Consumed => " + time);
}
@Test
public void testLargeFileIO_BufferedReader() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
String fileLineContent;
while ((fileLineContent = fileBufferReader.readLine()) != null) {
//System.out.println(fileLineContent);
}
}
long end = new Date().getTime();
long time = (long) (end - start);
System.out.println("BufferedReader Time Consumed => " + time);
}
@Test
public void testLargeFileIO_Stream() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
//inputStream.forEach(System.out::println);
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Stream Time Consumed => " + time);
}
<RatingBar android:id="@+id/id_tv_rating_bar"
style="@style/Widget.AppCompat.RatingBar.Small"
android:layout_width="wrap_content"
android:layout_height="@dimen/_20sdp"
android:layout_marginLeft="@dimen/_80sdp"
android:numStars="5"
android:paddingTop="@dimen/_5sdp"
android:rating="5" />
Just use style="@style/Widget.AppCompat.RatingBar.Small"
it'll work for Sure!
Stephen Taub has implemented a solution to this question, see Building Async Coordination Primitives, Part 7: AsyncReaderWriterLock.
Stephen Taub is highly regarded in the industry, so anything he writes is likely to be solid.
I won't reproduce the code that he posted on his blog, but I will show you how to use it:
/// <summary>
/// Demo class for reader/writer lock that supports async/await.
/// For source, see Stephen Taub's brilliant article, "Building Async Coordination
/// Primitives, Part 7: AsyncReaderWriterLock".
/// </summary>
public class AsyncReaderWriterLockDemo
{
private readonly IAsyncReaderWriterLock _lock = new AsyncReaderWriterLock();
public async void DemoCode()
{
using(var releaser = await _lock.ReaderLockAsync())
{
// Insert reads here.
// Multiple readers can access the lock simultaneously.
}
using (var releaser = await _lock.WriterLockAsync())
{
// Insert writes here.
// If a writer is in progress, then readers are blocked.
}
}
}
If you want a method that's baked into the .NET framework, use SemaphoreSlim.WaitAsync
instead. You won't get a reader/writer lock, but you will get tried and tested implementation.
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
I don't know if this was "the" official use case, but the following produces a warning in Java (that can further produce compile errors if mixed with return
statements, leading to unreachable code):
while (1 == 2) { // Note that "if" is treated differently
System.out.println("Unreachable code");
}
However this is legal:
while (isUserAGoat()) {
System.out.println("Unreachable but determined at runtime, not at compile time");
}
So I often find myself writing a silly utility method for the quickest way to dummy out a code block, then in completing debugging find all calls to it, so provided the implementation doesn't change this can be used for that.
JLS points out if (false)
does not trigger "unreachable code" for the specific reason that this would break support for debug flags, i.e., basically this use case (h/t @auselen). (static final boolean DEBUG = false;
for instance).
I replaced while
for if
, producing a more obscure use case. I believe you can trip up your IDE, like Eclipse, with this behavior, but this edit is 4 years into the future, and I don't have an Eclipse environment to play with.
.PDB file is the short name of "Program Database". It contains the information about debug point for debugger and resources which are used or reference. Its generated when we build as debug mode. Its allow to application to debug at runtime.
The size is increase of .PDB file in debug mode. It is used when we are testing our application.
Good article of pdb file.
http://www.codeproject.com/Articles/37456/How-To-Inspect-the-Content-of-a-Program-Database-P
You need antMatcher
for multiple HttpSecurity
, see Spring Security Reference:
5.7 Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple
<http>
blocks. The key is to extend theWebSecurityConfigurationAdapter
multiple times. For example, the following is an example of having a different configuration for URL’s that start with/api/
.@EnableWebSecurity public class MultiHttpSecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { 1 auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); } @Configuration @Order(1) 2 public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") 3 .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration 4 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
1 Configure Authentication as normal
2 Create an instance of
WebSecurityConfigurerAdapter
that contains@Order
to specify whichWebSecurityConfigurerAdapter
should be considered first.3 The
http.antMatcher
states that thisHttpSecurity
will only be applicable to URLs that start with/api/
4 Create another instance of
WebSecurityConfigurerAdapter
. If the URL does not start with/api/
this configuration will be used. This configuration is considered afterApiWebSecurityConfigurationAdapter
since it has an@Order
value after1
(no@Order
defaults to last).
In your case you need no antMatcher
, because you have only one configuration. Your modified code:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()
You need %in%
instead of ==
:
library(dplyr)
target <- c("Tom", "Lynn")
filter(dat, name %in% target) # equivalently, dat %>% filter(name %in% target)
Produces
days name
1 88 Lynn
2 11 Tom
3 1 Tom
4 222 Lynn
5 2 Lynn
To understand why, consider what happens here:
dat$name == target
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
Basically, we're recycling the two length target
vector four times to match the length of dat$name
. In other words, we are doing:
Lynn == Tom
Tom == Lynn
Chris == Tom
Lisa == Lynn
... continue repeating Tom and Lynn until end of data frame
In this case we don't get an error because I suspect your data frame actually has a different number of rows that don't allow recycling, but the sample you provide does (8 rows). If the sample had had an odd number of rows I would have gotten the same error as you. But even when recycling works, this is clearly not what you want. Basically, the statement dat$name == target
is equivalent to saying:
return
TRUE
for every odd value that is equal to "Tom" or every even value that is equal to "Lynn".
It so happens that the last value in your sample data frame is even and equal to "Lynn", hence the one TRUE
above.
To contrast, dat$name %in% target
says:
for each value in
dat$name
, check that it exists intarget
.
Very different. Here is the result:
[1] TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE
Note your problem has nothing to do with dplyr
, just the mis-use of ==
.
public static <T, K, V> Collector<T, HashMap<K, V>, HashMap<K, V>> toHashMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper
)
{
return Collector.of(
HashMap::new,
(map, t) -> map.put(keyMapper.apply(t), valueMapper.apply(t)),
(map1, map2) -> {
map1.putAll(map2);
return map1;
}
);
}
public static <T, K> Collector<T, HashMap<K, T>, HashMap<K, T>> toHashMap(
Function<? super T, ? extends K> keyMapper
)
{
return toHashMap(keyMapper, Function.identity());
}
Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
var left = el.offset().left;_x000D_
var top = el.offset().top;_x000D_
var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
if (percent) {_x000D_
x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
} else {_x000D_
x = (evt.pageX - left - (hotspot / 2));_x000D_
y = (evt.pageY - top - (hotspot / 2));_x000D_
}_x000D_
_x000D_
return {_x000D_
x: x,_x000D_
y: y_x000D_
};_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$('.box').click(function(e) {_x000D_
_x000D_
var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
var hotspot = $('<div class="hotspot">').css({_x000D_
left: hp.x,_x000D_
top: hp.y,_x000D_
});_x000D_
$(this).append(hotspot);_x000D_
$("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
});_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
background: #efefef;_x000D_
margin: 20px;_x000D_
padding: 20px;_x000D_
position: relative;_x000D_
top: 20px;_x000D_
left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
height: 20px;_x000D_
width: 20px;_x000D_
background: green;_x000D_
border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
<p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
I've personally never seen .cc
in any project that I've worked on, but in all technicality the compiler won't care.
Who will care is the developers working on your source, so my rule of thumb is to go with what your team is comfortable with. If your "team" is the open source community, go with something very common, of which .cpp
seems to be the favourite.
ZedGraph is a good choice.
To see local changes compare to your current branch
git diff .
To see local changed compare to any other existing branch
git diff <branch-name> .
To see changes of a particular file
git diff <branch-name> -- <file-path>
Make sure you run git fetch
at the beginning.
ES6 allows a construct where a function argument is specified with a "..." notation such as
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
Do "double g=1.0/3.0;" instead.
The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add
will still match when looking to add exactly text to add
.
So the correct solution is something like:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)
It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.
However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.
But you can make your life easier using the gulp-jbb-profile
(https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:
# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
properties:
- age
- isOld
For example you can have a look on the jbb-profile-three
profile.
When you have your profile ready, you can use JBB like this:
var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');
// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );
// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);
// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.
var p1 = new Person(77);
bundle.encode( p1, 'person' );
var people = [
new Person(45),
new Person(77),
...
];
bundle.encode( people, 'people' );
// Close the bundle when you are done
bundle.close();
And you can read it back like this:
var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');
// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );
// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );
// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );
// Load and callback when ready
binaryLoader.load(function( error, database ) {
// Your objects are in the database
// and ready to use!
var people = database['people'];
});
Just linking the CSS worked for me. It may have been missing from my project entirely:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
the easy robust way cross-platform and work in pipenv as well is:
pip freeze
pip uninstall -r requirement
by pipenv:
pipenv run pip freeze
pipenv run pip uninstall -r requirement
but won't update piplock or pipfile so be aware
To add an element to an array you need to use the format:
array[index] = element;
Where array
is the array you declared, index
is the position where the element will be stored, and element
is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add()
method is available for Collections
like List
and Set
. You could use it if you were using an ArrayList
(see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
netstat -tapen | grep ssh | awk '{ print $10}'
Output:
two # in my experiment
netstat -tapen | grep ssh | awk '{ print $4}'
gives the IP address.
Output:
127.0.0.1:22 # in my experiment
But the results are mixed with other users and stuff. It needs more work.
in ubuntu 14.04 based on your php version : 5.6,7.0,7.1,7.2,7.3
sudo apt-get install php{version}-mcrypt
sudo apt-get install php7.1-mcrypt
sudo phpenmod mcrypt
For those who have Underscore.js included in their project you can do:
_({a:'', b:''}).size() // => 2
or functional style:
_.size({a:'', b:''}) // => 2
window.open('https://support.wwf.org.uk', '_blank');
The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)
I solved this by copying it over to the missing directory:
cp /opt/X11/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib
brew reinstall libpng kept installing libpng16, not libpng15 so I was forced to do the above.
I would check the DDL for the sequence in the schema. JPA Implementation is responsible only creation of the sequence with the correct allocation size. Therefore, if the allocation size is 50 then your sequence must have the increment of 50 in its DDL.
This case may typically occur with the creation of a sequence with allocation size 1 then later configured to allocation size 50 (or default) but the sequence DDL is not updated.
> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.
Sometimes yes, but sometimes not. Let's see an example of a corrupted file:
echo Pete > my_name
tar -cf my_data.tar my_name
# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file
tar -xvf my_data_now.tar -O
It shows:
my_name
Fool
Even if you execute
echo $?
tar said that there was no error:
0
but the file was corrupted, it has now "Fool" instead of "Pete".
Please find below codes for ios 10 request permission sample for info.plist
.
You can modify for your custom message.
<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>
<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>
<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>
<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>
<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>
<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>
<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>
<key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>
<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>
<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>
<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>
<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>
<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>
<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
iOS 11 and plus, If you want to add photo/image to your library then you must add this key
<key>NSPhotoLibraryAddUsageDescription</key>
<string>${PRODUCT_NAME} library Usage</string>
Accessing CSS property & manipulating is quite easy using .css(). For example, to change single property:
$("selector").css('top', '50px');
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.
var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
I had same problem in eclipse windows that I couldn't added dependant .class files from the JNI. In order resolve the same, I ported all the code to NetBeans IDE.
Can not add all the classes files from the JNI/JNA folder in Eclipse (JAVA, Windows 7)
@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.
Everyone else has already answered it, but I think I still have something else to add.
Reasons to have that if
statement calling main()
(in no particular order):
Other languages (like C and Java) have a main()
function that is called when the program is executed. Using this if
, we can make Python behave like them, which feels more familiar for many people.
Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to import
that python code as a module without nasty side-effects.
This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside def main
are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
But, you are not required to write a main()
function and call it inside an if
statement.
I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash
scripts.
Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
This means you can call main()
from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.
In an object-oriented application I've written, the code looked like this:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
So, feel free to write the code that better suits you. :)
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
Immediately Invoked Async Arrow Function:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression:
(async function () {
console.log(await asyncFunction());
})();
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case 0:
{
return new AlertDialog.Builder(this)
.setMessage("text here")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
try
{
}//end try
catch(Exception e)
{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_LONG).show();
}//end catch
}//end onClick()
}).create();
}//end case
}//end switch
return null;
}//end onCreateDialog
Just use the change directory (cd) command.
cd d:\windows\movie
Use the children funcion of jQuery.
$("#text-field").keydown(function(event) {
if($('#popup').children('p.filled-text').length > 0) {
console.log("Found");
}
});
$.children('').length
will return the count of child elements which match the selector.
Have a look at:
http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx
I became interested in the issue and perform some experiments
I found that description here, but it is very short.
Then I tried to experiment with gcc.exe and g++.exe on my windows machine:
$ g++ --version | head -n1
g++.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3
$ gcc --version | head -n1
gcc.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3
I tried to compile c89, c99, and c++1998 simple test files and It's work well for me with correct extensions matching for language
gcc -std=c99 test_c99.c
gcc -std=c89 test_c89.c
g++ -std=c++98 test_cpp.cpp
gcc -std=c++98 test_cpp.cpp
But when I try to run "gnu compiler collection" tool in that fashion:
$ gcc -std=c++98 test_cpp.c
cc1.exe: warning: command line option '-std=c++98' is valid for C++/ObjC++ but not for C [enabled by default]
But this one still work with no errors
$ gcc -x c++ -std=c++98 test_cpp.c
And this also
$ g++ -std=c++0x test_cpp_11.cpp
p.s. Test files
$ cat test_c89.c test_c99.c test_cpp.cpp
// C89 compatible file
int main()
{
int x[] = {0, 2};
return sizeof(x);
}
// C99 compatible file
int main()
{
int x[] = {[1]=2};
return sizeof(x);
}
// C++1998,2003 compatible file
class X{};
int main()
{
X x;
return sizeof(x);
}
// C++11
#include <vector>
enum class Color : int{red,green,blue}; // scoped enum
int main()
{
std::vector<int> a {1,2,3}; // bracket initialization
return 0;
}
Findings:
If look at process tree then it seems that gcc, and g++ is backend to other tools, which in my environment are: cc1plus.exe, cc1.exe, collect2.exe, as.exe, ld.exe
gcc works fine as metatool for if you have correct extension or set correct -std -x flags. See this
Using mvn shell command line, spring-boot 2:
mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085'
Goto:
project>Properties>Android> select: google APIs Android 4.0.3
Click Icon:
Android Virtual Device Manager>Edit> Slect box in Tabget>Google APIs APIsLevel15
and select Built-in: is WQVGA400 > Edit AVD > Start
Below is the server side code that would call the handler and recieve the stream data and loads into xml doc
Stream stream = null;
**Create a web request with the specified URL**
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
**Senda a web request and wait for response.**
WebResponse webResponse = myWebRequest.GetResponse();
**Get the stream object from response object**
stream = webResponse.GetResponseStream();
XmlDocument xmlDoc = new XmlDocument();
**Load stream data into xml**
xmlDoc.Load(stream);
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
Combining some features of @HYRY and @arun's answers, you can print the top correlations for dataframe df
in a single line using:
df.corr().unstack().sort_values().drop_duplicates()
Note: the one downside is if you have 1.0 correlations that are not one variable to itself, the drop_duplicates()
addition would remove them
Open your font-awesome.css theres code like :
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.5.0');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.5.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.5.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.5.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.5.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.5.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
you must have folder like :
font awesome -> css
-> fonts
or the easiest way :
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
You can also use the join command (dplyr).
For example:
new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
I got around this with len()
and a simple if/else
statement.
List elements will come back as an integer when wrapped in len()
(1 for present, 0 for absent)
l = []
print(len(l)) # Prints 0
if len(l) == 0:
print("Element is empty")
else:
print("Element is NOT empty")
Output:
Element is empty
Look at how Runtime.getRuntime().exec()
passes the String command to the ProcessBuilder
. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......)
which constructs a ProcessBuilder
.
If you construct the ProcessBuilder
with an array of strings instead of a single one, you'll get to the same result.
The ProcessBuilder
constructor takes a String...
vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:
shell$ "command with args"
Although the DATEADD
is probably the most transparrent way of doing this, it is worth noting
that simply getdate()-30
will also suffice.
Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:
SELECT *
FROM Results
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)
Some additional steps may be needed to set both the project and default workspace JRE correctly, as MayoMan mentioned. Here is the complete sequence in Eclipse Luna:
Easy.... not.
As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:
Object.keys
, Object.values
, Object.entries
for..in
loopsJSON.stringify
But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.
Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys
and Object.getOwnPropertyNames
), the previously-unspecified methods will also iterate in the following order:
This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.
Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"
The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.
Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.
There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:
Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.
Neither the object nor anything in its prototype chain has its prototype change during iteration.
Neither the object nor anything in its prototype chain has a property deleted during iteration.
Nothing in the object's prototype chain has a property added during iteration.
No property of the object or anything in its prototype chain has its enumerability change during iteration.
No non-enumerable property shadows an enumerable one.
call the request function from anywhere without having to use catch().
First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.
So we now use a Promise based function:
const baseRequest = async (method: string, url: string, data: ?{}) =>
new Promise<{ data: any }>((resolve, reject) => {
const requestConfig: any = {
method,
data,
timeout: 10000,
url,
headers: {},
};
try {
const response = await axios(requestConfig);
// Request Succeeded!
resolve(response);
} catch (error) {
// Request Failed!
if (error.response) {
// Request made and server responded
reject(response);
} else if (error.request) {
// The request was made but no response was received
reject(response);
} else {
// Something happened in setting up the request that triggered an Error
reject(response);
}
}
};
you can then use the request like
try {
response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
// either handle errors or don't
}
Look at the following code
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
alert("Double click");
//here is your code for double click
return;
}else{
$this.addClass('clicked');
//your code for single click
setTimeout(function() {
$this.removeClass('clicked'); },500);
}//end of else
});
Demo goes here http://jsfiddle.net/cB484/
java.math.BigInteger
is an immutable class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:
sum = sum.add(BigInteger.valueOf(i));
You can pass $ in function()
jQuery(document).ready(function($){
// jQuery code is in here
});
or you can replace $(document);
with this jQuery(document);
or you can use jQuery.noConflict()
var jq=jQuery.noConflict();
jq(document).ready(function(){
jq('selector').show();
});
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
public class ApiClient {
private static Retrofit retrofit = null;
private static final Object LOCK = new Object();
public static void clear() {
synchronized (LOCK) {
retrofit = null;
}
}
public static Retrofit getClient() {
synchronized (LOCK) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(Constants.WEB_SERVICE)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
public static RequestBody plain(String content) {
return getRequestBody("text/plain", content);
}
public static RequestBody getRequestBody(String type, String content) {
return RequestBody.create(MediaType.parse(type), content);
}
}
@FormUrlEncoded
@POST("architect/project_list_Design_files")
Call<DesignListModel> getProjectDesign(
@Field("project_id") String project_id);
@Multipart
@POST("architect/upload_design")
Call<BoqListModel> getUpLoadDesign(
@Part("user_id") RequestBody user_id,
@Part("request_id") RequestBody request_id,
@Part List<MultipartBody.Part> image_file,
@Part List<MultipartBody.Part> design_upload_doc);
private void getMyProjectList()
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<MyProjectListModel> call = apiService.getMyProjectList("",Sorting,latitude,longitude,Search,Offset+"",Limit);
call.enqueue(new Callback<MyProjectListModel>() {
@Override
public void onResponse(Call<MyProjectListModel> call, Response<MyProjectListModel> response) {
try {
Log.e("response",response.body()+"");
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<MyProjectListModel> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
// file upload
private void getUpload(String path,String id)
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
MultipartBody.Part GalleryImage = null;
if (path!="")
{
File file = new File(path);
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
GalleryImage = MultipartBody.Part.createFormData("image", file.getName(), reqFile);
}
RequestBody UserId = RequestBody.create(MediaType.parse("text/plain"), id);
Call<uplod_file> call = apiService.geUplodFileCall(UserId,GalleryImage);
call.enqueue(new Callback<uplod_file>() {
@Override
public void onResponse(Call<uplod_file> call, Response<uplod_file> response) {
try {
Log.e("response",response.body()+"");
Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<uplod_file> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
I know I am late but hope this helps.
Following are the values for the position property.
position : static
This is default. It means the element will occur at a position that it normally would.
#myelem {
position : static;
}
position : fixed
This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.
(Ideal if you want scroll-to-top button at the bottom right corner of the page).
#myelem {
position : fixed;
bottom : 30px;
right : 30px;
}
position : relative
To place an element at a new location relative to its original position.
#myelem {
position : relative;
left : 30px;
top : 30px;
}
The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.
position : absolute
If we want an element to be placed at an exact position in the page.
#myelem {
position : absolute;
top : 30px;
left : 300px;
}
The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.
And finally...
position relative + absolute
We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position.
#container {
position : relative;
}
#div-2 {
position : absolute;
top : 0;
right : 0;
}
We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element.
GitHub: You can find the HTML of the above image here and CSS here.
Hope this tutorial helps.
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
I ended up abandoning the code for my other answer to this question and going with this answer instead.
I believe the best way to do this is to not use ng-show
and ng-animate
at all.
/* Executes jQuery slideDown and slideUp based on value of toggle-slidedown
attribute. Set duration using slidedown-duration attribute. Add the
toggle-required attribute to all contained form controls which are
input, select, or textarea. Defaults to hidden (up) if not specified
in slidedown-init attribute. */
fboApp.directive('toggleSlidedown', function(){
return {
restrict: 'A',
link: function (scope, elem, attrs, ctrl) {
if ('down' == attrs.slidedownInit){
elem.css('display', '');
} else {
elem.css('display', 'none');
}
scope.$watch(attrs.toggleSlidedown, function (val) {
var duration = _.isUndefined(attrs.slidedownDuration) ? 150 : attrs.slidedownDuration;
if (val) {
elem.slideDown(duration);
} else {
elem.slideUp(duration);
}
});
}
}
});
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a. For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example: Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error. CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
Specify the Line Number using NR
built-in variable.
awk 'NR==1{print $1}' /etc/*release
Firstly, thanks to Andrei as I've based my solution on his example.
I'm including mine as it's a more complete sample and might save readers some time.
The limitation of Andrei's approach is that doesn't handle logging, capturing potentially useful request variables and content negotiation (it will always return JSON no matter what the client has requested - XML / plain text etc).
My approach is to use an ObjectResult which allows us to use the functionality baked into MVC.
This code also prevents caching of the response.
The error response has been decorated in such a way that it can be serialized by the XML serializer.
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate next;
private readonly IActionResultExecutor<ObjectResult> executor;
private readonly ILogger logger;
private static readonly ActionDescriptor EmptyActionDescriptor = new ActionDescriptor();
public ExceptionHandlerMiddleware(RequestDelegate next, IActionResultExecutor<ObjectResult> executor, ILoggerFactory loggerFactory)
{
this.next = next;
this.executor = executor;
logger = loggerFactory.CreateLogger<ExceptionHandlerMiddleware>();
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
logger.LogError(ex, $"An unhandled exception has occurred while executing the request. Url: {context.Request.GetDisplayUrl()}. Request Data: " + GetRequestData(context));
if (context.Response.HasStarted)
{
throw;
}
var routeData = context.GetRouteData() ?? new RouteData();
ClearCacheHeaders(context.Response);
var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);
var result = new ObjectResult(new ErrorResponse("Error processing request. Server error."))
{
StatusCode = (int) HttpStatusCode.InternalServerError,
};
await executor.ExecuteAsync(actionContext, result);
}
}
private static string GetRequestData(HttpContext context)
{
var sb = new StringBuilder();
if (context.Request.HasFormContentType && context.Request.Form.Any())
{
sb.Append("Form variables:");
foreach (var x in context.Request.Form)
{
sb.AppendFormat("Key={0}, Value={1}<br/>", x.Key, x.Value);
}
}
sb.AppendLine("Method: " + context.Request.Method);
return sb.ToString();
}
private static void ClearCacheHeaders(HttpResponse response)
{
response.Headers[HeaderNames.CacheControl] = "no-cache";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
response.Headers.Remove(HeaderNames.ETag);
}
[DataContract(Name= "ErrorResponse")]
public class ErrorResponse
{
[DataMember(Name = "Message")]
public string Message { get; set; }
public ErrorResponse(string message)
{
Message = message;
}
}
}
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
ls -X works for that purpose, in case you have aliased ls to a more useful default.
If you're using Bootstrap 3, you can use the Glyphicons.
.slick-prev:before, .slick-next:before {
font-family: "Glyphicons Halflings", "slick", sans-serif;
font-size: 40px;
}
.slick-prev:before { content: "\e257"; }
.slick-next:before { content: "\e258"; }
Since the exact question is "what does enable bitcode do", I'd like to give a few thin technical details I've figured out thus far. Most of this is practically impossible to figure out with 100% certainty until Apple releases the source code for this compiler
First, Apple's bitcode does not appear to be the same thing as LLVM bytecode. At least, I've not been able to figure out any resemblance between them. It appears to have a proprietary header (always starts with "xar!") and probably some link-time reference magic that prevents data duplications. If you write out a hardcoded string, this string will only be put into the data once, rather than twice as would be expected if it was normal LLVM bytecode.
Second, bitcode is not really shipped in the binary archive as a separate architecture as might be expected. It is not shipped in the same way as say x86 and ARM are put into one binary (FAT archive). Instead, they use a special section in the architecture specific MachO binary named "__LLVM" which is shipped with every architecture supported (ie, duplicated). I assume this is a short coming with their compiler system and may be fixed in the future to avoid the duplication.
C code (compiled with clang -fembed-bitcode hi.c -S -emit-llvm
):
#include <stdio.h>
int main() {
printf("hi there!");
return 0;
}
LLVM IR output:
; ModuleID = '/var/folders/rd/sv6v2_f50nzbrn4f64gnd4gh0000gq/T/hi-a8c16c.bc'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
@llvm.embedded.module = appending constant [1600 x i8] c"\DE\C0\17\0B\00\00\00\00\14\00\00\00$\06\00\00\07\00\00\01BC\C0\DE!\0C\00\00\86\01\00\00\0B\82 \00\02\00\00\00\12\00\00\00\07\81#\91A\C8\04I\06\1029\92\01\84\0C%\05\08\19\1E\04\8Bb\80\10E\02B\92\0BB\84\102\148\08\18I\0A2D$H\0A\90!#\C4R\80\0C\19!r$\07\C8\08\11b\A8\A0\A8@\C6\F0\01\00\00\00Q\18\00\00\C7\00\00\00\1Bp$\F8\FF\FF\FF\FF\01\90\00\0D\08\03\82\1D\CAa\1E\E6\A1\0D\E0A\1E\CAa\1C\D2a\1E\CA\A1\0D\CC\01\1E\DA!\1C\C8\010\87p`\87y(\07\80p\87wh\03s\90\87ph\87rh\03xx\87tp\07z(\07yh\83r`\87th\07\80\1E\E4\A1\1E\CA\01\18\DC\E1\1D\DA\C0\1C\E4!\1C\DA\A1\1C\DA\00\1E\DE!\1D\DC\81\1E\CAA\1E\DA\A0\1C\D8!\1D\DA\A1\0D\DC\E1\1D\DC\A1\0D\D8\A1\1C\C2\C1\1C\00\C2\1D\DE\A1\0D\D2\C1\1D\CCa\1E\DA\C0\1C\E0\A1\0D\DA!\1C\E8\01\1D\00s\08\07v\98\87r\00\08wx\876p\87pp\87yh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \E6\81\1E\C2a\1C\D6\A1\0D\E0A\1E\DE\81\1E\CAa\1C\E8\E1\1D\E4\A1\0D\C4\A1\1E\CC\C1\1C\CAA\1E\DA`\1E\D2A\1F\CA\01\C0\03\80\A0\87p\90\87s(\07zh\83q\80\87z\00\C6\E1\1D\E4\A1\1C\E4\00 \E8!\1C\E4\E1\1C\CA\81\1E\DA\C0\1C\CA!\1C\E8\A1\1E\E4\A1\1C\E6\01X\83y\98\87y(\879`\835\18\07|\88\03;`\835\98\87y(\076X\83y\98\87r\90\036X\83y\98\87r\98\03\80\A8\07w\98\87p0\87rh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \EAa\1E\CA\A1\0D\E6\E1\1D\CC\81\1E\DA\C0\1C\D8\E1\1D\C2\81\1E\00s\08\07v\98\87r\006\C8\88\F0\FF\FF\FF\FF\03\C1\0E\E50\0F\F3\D0\06\F0 \0F\E50\0E\E90\0F\E5\D0\06\E6\00\0F\ED\10\0E\E4\00\98C8\B0\C3<\94\03@\B8\C3;\B4\819\C8C8\B4C9\B4\01<\BCC:\B8\03=\94\83<\B4A9\B0C:\B4\03@\0F\F2P\0F\E5\00\0C\EE\F0\0Em`\0E\F2\10\0E\EDP\0Em\00\0F\EF\90\0E\EE@\0F\E5 \0FmP\0E\EC\90\0E\ED\D0\06\EE\F0\0E\EE\D0\06\ECP\0E\E1`\0E\00\E1\0E\EF\D0\06\E9\E0\0E\E60\0Fm`\0E\F0\D0\06\ED\10\0E\F4\80\0E\809\84\03;\CCC9\00\84;\BCC\1B\B8C8\B8\C3<\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F3@\0F\E10\0E\EB\D0\06\F0 \0F\EF@\0F\E50\0E\F4\F0\0E\F2\D0\06\E2P\0F\E6`\0E\E5 \0Fm0\0F\E9\A0\0F\E5\00\E0\01@\D0C8\C8\C39\94\03=\B4\C18\C0C=\00\E3\F0\0E\F2P\0Er\00\10\F4\10\0E\F2p\0E\E5@\0Fm`\0E\E5\10\0E\F4P\0F\F2P\0E\F3\00\AC\C1<\CC\C3<\94\C3\1C\B0\C1\1A\8C\03>\C4\81\1D\B0\C1\1A\CC\C3<\94\03\1B\AC\C1<\CCC9\C8\01\1B\AC\C1<\CCC9\CC\01@\D4\83;\CCC8\98C9\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F50\0F\E5\D0\06\F3\F0\0E\E6@\0Fm`\0E\EC\F0\0E\E1@\0F\809\84\03;\CCC9\00\00I\18\00\00\02\00\00\00\13\82`B \00\00\00\89 \00\00\0D\00\00\002\22\08\09 d\85\04\13\22\A4\84\04\13\22\E3\84\A1\90\14\12L\88\8C\0B\84\84L\100s\04H*\00\C5\1C\01\18\94`\88\08\AA0F7\10@3\02\00\134|\C0\03;\F8\05;\A0\836\08\07x\80\07v(\876h\87p\18\87w\98\07|\88\038p\838\80\037\80\83\0DeP\0Em\D0\0Ez\F0\0Em\90\0Ev@\07z`\07t\D0\06\E6\80\07p\A0\07q \07x\D0\06\EE\80\07z\10\07v\A0\07s \07z`\07t\D0\06\B3\10\07r\80\07:\0FDH #EB\80\1D\8C\10\18I\00\00@\00\00\C0\10\A7\00\00 \00\00\00\00\00\00\00\868\08\10\00\02\00\00\00\00\00\00\90\05\02\00\00\08\00\00\002\1E\98\0C\19\11L\90\8C\09&G\C6\04C\9A\22(\01\0AM\D0i\10\1D]\96\97C\00\00\00y\18\00\00\1C\00\00\00\1A\03L\90F\02\134A\18\08&PIC Level\13\84a\D80\04\C2\C05\08\82\83c+\03ab\B2j\02\B1+\93\9BK{s\03\B9q\81q\81\01A\19c\0Bs;k\B9\81\81q\81q\A9\99q\99I\D9\10\14\8D\D8\D8\EC\DA\5C\DA\DE\C8\EA\D8\CA\5C\CC\D8\C2\CE\E6\A6\04C\1566\BB6\974\B227\BA)A\01\00y\18\00\002\00\00\003\08\80\1C\C4\E1\1Cf\14\01=\88C8\84\C3\8CB\80\07yx\07s\98q\0C\E6\00\0F\ED\10\0E\F4\80\0E3\0CB\1E\C2\C1\1D\CE\A1\1Cf0\05=\88C8\84\83\1B\CC\03=\C8C=\8C\03=\CCx\8Ctp\07{\08\07yH\87pp\07zp\03vx\87p \87\19\CC\11\0E\EC\90\0E\E10\0Fn0\0F\E3\F0\0E\F0P\0E3\10\C4\1D\DE!\1C\D8!\1D\C2a\1Ef0\89;\BC\83;\D0C9\B4\03<\BC\83<\84\03;\CC\F0\14v`\07{h\077h\87rh\077\80\87p\90\87p`\07v(\07v\F8\05vx\87w\80\87_\08\87q\18\87r\98\87y\98\81,\EE\F0\0E\EE\E0\0E\F5\C0\0E\EC\00q \00\00\05\00\00\00&`<\11\D2L\85\05\10\0C\804\06@\F8\D2\14\01\00\00a \00\00\0B\00\00\00\13\04A,\10\00\00\00\03\00\00\004#\00dC\19\020\18\83\01\003\11\CA@\0C\83\11\C1\00\00#\06\04\00\1CB\12\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00", section "__LLVM,__bitcode"
@llvm.cmdline = appending constant [67 x i8] c"-triple\00x86_64-apple-macosx10.10.0\00-emit-llvm\00-disable-llvm-optzns\00", section "__LLVM,__cmdline"
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.0.53.3)"}
The data array that is in the IR also changes depending on the optimization and other code generation settings of clang. It's completely unknown to me what format or anything that this is in.
EDIT:
Following the hint on Twitter, I decided to revisit this and to confirm it. I followed this blog post and used his bitcode extractor tool to get the Apple Archive binary out of the MachO executable. And after extracting the Apple Archive with the xar utility, I got this (converted to text with llvm-dis of course)
; ModuleID = '1'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.1.76)"}
The only notable difference really between the non-bitcode IR and the bitcode IR is that filenames have been stripped to just 1, 2, etc for each architecture.
I also confirmed that the bitcode embedded in a binary is generated after optimizations. If you compile with -O3 and extract out the bitcode, it'll be different than if you compile with -O0.
And just to get extra credit, I also confirmed that Apple does not ship bitcode to devices when you download an iOS 9 app. They include a number of other strange sections that I don't recognized like __LINKEDIT, but they do not include __LLVM.__bundle, and thus do not appear to include bitcode in the final binary that runs on a device. Oddly enough, Apple still ships fat binaries with separate 32/64bit code to iOS 8 devices though.
Linux Mint, Debian 9, Ubuntu 16.04 and older:
Short info:
apt policy <package_name>
Detailed info (With Description and Depends):
apt show <package_name>
"Cannot invoke an expression whose type lacks a call signature."
In your code :
class Post extends Component {
public toggleBody: string;
constructor() {
this.toggleBody = this.setProp('showFullBody');
}
public showMore(): boolean {
return this.toggleBody(true);
}
public showLess(): boolean {
return this.toggleBody(false);
}
}
You have public toggleBody: string;
. You cannot call a string
as a function. Hence errors on : this.toggleBody(true);
and this.toggleBody(false);
from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
from http://api.jquery.com/scrollTop/
$(window).scrollTop() // return the number of pixels scrolled vertically
If you are happy to use JavaScript then you can use Modernizr in your page. When the page loads, a non-touch screen browser will have the class '.no-touch' added to the html tag, but for a touch screen browser, the html tag will have the class '.touch' added to the html tag.
Then it is simply a case of checking to see if the html tag has the no-touch class before deciding to add your mouseenter and mouseleave listeners.
if($('html').hasClass('no-touch')){
$('.box').on("mouseenter", function(event){
$(this).css('background-color','#0000ff')
});
$('.box').on("mouseleave", function(event){
$(this).css('background-color','')
});
}
For a touchscreen device the events will have no listeners so you will get no hover effect when you tap.
Strings in C are represented as arrays of characters.
char *p = "String";
You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.
char p2[] = "String";
You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.
char p3[5] = "String";
You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.
char p3[7] = "String";
is the correct declaration ('\0' is the terminating character in c strings).
If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:
Boolean.TRUE.toString();
Boolean.FALSE.toString();
I wrote a little method to test out the basic color modes, based on answers by Erik Skoglund and others.
#outputs color table to console, regular and bold modes
def colortable
names = %w(black red green yellow blue pink cyan white default)
fgcodes = (30..39).to_a - [38]
s = ''
reg = "\e[%d;%dm%s\e[0m"
bold = "\e[1;%d;%dm%s\e[0m"
puts ' color table with these background codes:'
puts ' 40 41 42 43 44 45 46 47 49'
names.zip(fgcodes).each {|name,fg|
s = "#{fg}"
puts "%7s "%name + "#{reg} #{bold} "*9 % [fg,40,s,fg,40,s, fg,41,s,fg,41,s, fg,42,s,fg,42,s, fg,43,s,fg,43,s,
fg,44,s,fg,44,s, fg,45,s,fg,45,s, fg,46,s,fg,46,s, fg,47,s,fg,47,s, fg,49,s,fg,49,s ]
}
end
example output:
I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/
edit: I am now using msys2. Msys2 uses pacman
from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)
You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.
This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.
Use this
public static class EncryptedData {
private String encryptedData;
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
Instead of this
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
}
Here is an example class using CSS named colors:
.semi-transparent {
background: yellow;
opacity: 0.25;
}
This adds a background that is 25% opaque (colored) and 75% transparent.
CAVEAT
Unfortunately, opacity will affect then entire element it's attached to.
So if you have text in that element, it will set the text to 25% opacity too. :-(
The way to get past this is to use the rgba
or hsla
methods to indicate transparency as part of your desired background "color". This allows you to specify the background transparency, independent from the transparency of the other items in your element.
Here are 3 ways to set a blue background at 75% transparency, without affecting other elements:
background: rgba(0%, 0%, 100%, 0.75)
background: rgba(0, 0, 255, 0.75)
background: hsla(240, 100%, 50%, 0.75)
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
I got a solution for you, Why dont you rather use Explode if your url is something like
Url-> website.com/test/blog.php
$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);
In Visual Studio Professional 2017 Version 15.9.13:
First, either:
or
Then, wait for it while it is "getting things ready..." and being "almost there..."
Switch to the "Individual components" tab
Scroll down to the "Compilers, build tools, and runtimes" section
Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"
like this:
After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe
If you wish to use the bound column value, you can simply refer to the combo:
sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo
You can also refer to the column property:
sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"
Dim rs As DAO.Recordset
Set rs = CurrentDB.OpenRecordset(sSQL)
strText = rs!AText
strText = rs.Fields(1)
In a textbox:
= DlookUp("AText","MyTable","ID=" & MyCombo)
*edited
To add to the other responses, sp_lock
can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with sp_who2
to quickly zero in on locking problems.
There are multiple different versions of "friendlier" sp_lock
procedures available online, depending on the version of SQL Server in question.
In your case, for SQL Server 2005, sp_lock
is still available, but deprecated, so it's now recommended to use the sys.dm_tran_locks
view for this kind of thing. You can find an example of how to "roll your own" sp_lock function here.
For windows: just change file association of .js
file to node.exe
1) Take VSCode
2) Right click on the file in left pane
3) Click "Reveal in explorer" from context menu
4) Right click on the file -> Select "Open with" -> Select "Choose another program"
5) Check box "Always use this app to open .js file"
6) Click "More apps" -> "Look for another app in PC"
7) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"
8) Click "Open" and you can just see cmd flashing
9) Restart vscode and open the file -> Terminal Menu -> "Run active file".
Maybe encode them into a known set - something like base 64 is a popular choice.
Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.
You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.
Very old post but I'll add my two cents. I have been VERY happy with this hardware product ( https://apposite-tech.com/products/linktropy-mini/ ) which has enabled us to simulate a lot of real-world conditions. For a long time we had challenges troubleshooting various things that would work in emulator or with airplane mode.
We have several different profiles setup from zero-connectivity to various stages of marginal connectivity, with different degrees of latency, packet loss, and bit-errors. The great thing about it is we can change these on the fly without having to relaunch the app in an emulator. The price has been entirely worth it for our shop, and it's dead simple to use.
The only place I have successfully make it work is by searching in:
...\Qt\{5.9; or your version}\mingw{53_32; or your version}\mkspecs\win32-g++\qmake.conf:
Then at the line:
QMAKE_CFLAGS += -fno-keep-inline-dllexport
Edit :
QMAKE_CFLAGS += -fno-keep-inline-dllexport -std=c++11
add Microsoft.AspNet.Mvc nuget package.
Mainly join is used exclusively to join based on the index,not on the attribute names,so change the attributes names in two different dataframes,then try to join,they will be joined,else this error is raised
With Python 3.6 you can use:
from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
Output:
'2019-05-10 09:08:53.155'
More info here: https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat
buf.delete(0, buf.length());
Use include
if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.
Using require
means your script will halt if it can't load the specified file, and throw a Fatal error.
The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:
Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:
var foomodule = require('foo');
// do something with fooModule
What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...
var module = require(path); // Call RequireJS require
...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;
var moduleName = 'foo';
require([moduleName], function(fooModule){
// do something with fooModule
})
Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:
define(['dyn_modules'], function (dynModules) {
require(dynModules, function(){
// use arguments since you don't know how many modules you're getting in the callback
for (var i = 0; i < arguments.length; i++){
var mymodule = arguments[i];
// do something with mymodule...
}
});
});
EDIT: From your own answer, I see you're using underscore/lodash, so using _.values
and _.object
can simplify the looping through arguments array as above.
This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all
in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.
There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.
UPDATE: 2016-11-11As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.
UPDATES: 2016-05-16PATH
and Registry. After extraction, create a symlink to conda
in your bin
or install conda from PyPI. Then create another symlink called conda-activate
to activate
in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root
to enable Anaconda/Miniconda.conda update --all
to keep each conda environment updated,$ ln /c/Python33/python.exe python3
).If OP has 2.7.x and wants to install newer version of 2.7.x, then
It is recommended to uninstall any other Python distribution before installing Python(x,y)
Program Files\Enthought
or home\AppData\Local\Enthought\Canopy\App
for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.
sage -upgrade
command.Anaconda can be updated by using the conda
command:
conda update --all
Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.
Anaconda will likely disrupt any other Python installations. Installation uses MSI installer.
[UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe
installers and provide options to disable Windows PATH
and Registry alterations.
Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe
installer is used and the options to alter Windows PATH
and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore
keys.
Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\
with the following keys: Help
, InstallPath
, Modules
and PythonPath
- official Python registers these keys too, but under Python\PythonCore
. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore
, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.
App\lib\site-packages
and App\Scripts
could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list
to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip
to install pip if it wasn't installed.If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py
files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is
If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.
I hope this clears up any confusion.
Remember to not capitalize your text when writing this command. For example:
Do write:
rails g model product title:string description:text image_url:string price:decimal
Do not write:
rails g Model product title:string description:text image_url:string price:decimal
At least it was a problem to me.
In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
Ended up using .closest() instead.
$(document).on("click", function (event) {
if($(event.target).closest(".CustomControllerMainDiv").length == 1)
alert('element is a child of the custom controller')
});
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
select Country_id,country_title from(
select Country_id,country_title,row_number() over (partition by country_title
order by Country_id ) rn from country)a
where rn=1;
From the JLS:
The array's length is available as a final instance variable length
And:
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
And arrays are implemented in the JVM. You may want to look at the VM Spec for more info.
In HTML5, simply use:
<iframe src="https://www.youtube.com/embed/ID" allowfullscreen />
This attribute can be set to true
if the frame is allowed to be placed into full-screen mode by calling it's Element.requestFullscreen()
method. If this isn't set, the element can't be placed into full-screen mode. See Mozilla Docs
In React.js framework use property allowFullScreen
.
Note that there are more answers pointing to different directions, so hope this post will unite and simplify all mentioned with latest valid approach.
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
What is the reason for getting each of them and any thought process on how to deal with such errors?
They're closely related. A ClassNotFoundException
is thrown when Java went looking for a particular class by name and could not successfully load it. A NoClassDefFoundError
is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.
If you've got a C background, a CNFE is like a failure to dlopen()
/dlsym()
and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.
I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:
fun create(mongo: MongoTemplate) {
mongo.db.getCollection("sequence")
.insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))
}
An then a service that return unique (and ascending) numbers:
@Service
class IdCounter(val mongoTemplate: MongoTemplate) {
companion object {
const val collection = "sequence"
}
private val idField = "_id"
private val idValue = "globalCounter"
private val sequence = "sequenceValue"
fun nextValue(): Long {
val filter = Document(mapOf(idField to idValue))
val update = Document("\$inc", Document(mapOf(sequence to 1)))
val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
return updated[sequence] as Long
}
}
I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.
CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)
If you want to downgrade php from 7.1.1 to 5.6 in xampp follow the steps(For Windows):-
Delete php folder and apache folder present in C:\xampp
Copy php folder and apache folder from extracted file and paste it to C:\xampp
Add " C: " before \xampp\ to php ini file present in php folder.
Start your apache and MySQL and check php version. It will show php 5.6.36
Yes you can add text inside <span>
and override css. jsfiddle
html:
<h1>**This text should be bold**, <span>but this text should not</span><h1>
css:
span{
font-weight: normal;
}
Use @Spy
annotation
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Spy
private SomeService service = new RealServiceImpl();
@InjectMocks
private Demo demo;
/* ... */
}
Mockito will consider all fields having @Mock
or @Spy
annotation as potential candidates to be injected into the instance annotated with @InjectMocks
annotation. In the above case 'RealServiceImpl'
instance will get injected into the 'demo'
For more details refer
EDIT: Use this Solution here: https://stackoverflow.com/a/20559175/2033223 Works perfect!
First of, thank for your solution @luizfelipetx
I changed your solution a little bit. This works for me:
public static String getRealPathFromDocumentUri(Context context, Uri uri){
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(uri.toString());
if (!m.find()) {
Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ imgId }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.
Don't really think there is some direct method to get the last day but you could do something like this:
var dateInst = new moment();
/**
* adding 1 month from the present month and then subtracting 1 day,
* So you would get the last day of this month
*/
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));
For ASP.NET Core 3.1 you can follow this guide:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs
:
Host.CreateDefaultBuilder(args)
This enables the following:
This means you can inject IConfiguration
and fetch values with a string key, even nested values. Like IConfiguration["Parent:Child"];
Example:
appsettings.json
{
"ApplicationInsights":
{
"Instrumentationkey":"putrealikeyhere"
}
}
WeatherForecast.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var key = _configuration["ApplicationInsights:InstrumentationKey"];
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Without over-complicating the problem, to grant the EXECUTE on chosen database:
USE [DB]
GRANT EXEC TO [User_Name];
Going to provide a slightly different answer to those provided so far.
If you have a row for an anonymous user from localhost in your users table ''@'localhost'
then this will be treated as more specific than your user with wildcard'd host 'user'@'%'
. This is why it is necessary to also provide 'user'@'localhost'
.
You can see this explained in more detail at the bottom of this page.
In AndroidManifest.xml:
<application
android:icon="@drawable/launcher"
android:label="@string/app_name"
android:name="com..."
android:theme="@style/Theme">...</Application>
In styles.xml: (See android:icon
)
<style name="Theme" parent="@android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<style name="ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:icon">@drawable/icon</item>
</style>
I got the same issue when i newly installed pycharm in my windows 10 machine.
download python setup
install this solved my problem.
for more help visit goodluck
During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"
If myString contains an account number that begins at offset 6 and has length 9, then you can extract the account number this way: acct = myString[6:][:9]
.
If the OP accepts that, they might want to try, in an experimental fashion,
myString[2:][:999999]
It works - no error is raised, and no default 'string padding' occurs.
Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.
Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.
I had issues getting through a form because of this error.
I used Ctrl+Click to click the submit button and navigate through the form as usual.
All You need to do is remove spaces or tab spaces from the start of following codes
from django.contrib import admin
# Register your models here.
from .models import Myapp
admin.site.register(Myapp)
.post-container{_x000D_
margin: 20px 20px 0 0; _x000D_
border:5px solid #333;_x000D_
width:600px;_x000D_
overflow:hidden;_x000D_
}_x000D_
_x000D_
.post-thumb img {_x000D_
float: left;_x000D_
clear:left;_x000D_
width:50px;_x000D_
height:50px;_x000D_
border:1px solid red;_x000D_
}_x000D_
_x000D_
.post-title {_x000D_
float:left; _x000D_
margin-left:10px;_x000D_
}_x000D_
_x000D_
.post-content {_x000D_
float:right;_x000D_
}
_x000D_
<div class="post-container"> _x000D_
<div class="post-thumb"><img src="thumb.jpg" /></div>_x000D_
<div class="post-title">Post title</div>_x000D_
<div class="post-content"><p>post description description description etc etc etc</p></div>_x000D_
</div>
_x000D_
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
EDIT 19-MAR-2014:
Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core
), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.
This will display PDF, DOC and DOCX filetypes.
Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues
I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource
which takes care of GET
, POST
, and other requests.
In my case I left my route as is:
Route::resource('file', 'FilesController');
And simply modified my form to submit to the store
function in my FilesController
{{ Form::open(array('route' => 'file.store')) }}
This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST
route. This is an option but it's not necessary.
yourEnum.ordinal()
EnumType.values()[someInt]
EnumType.valueOf(yourString)
yourEnum.name()
A side-note:
As you correctly point out, the ordinal()
may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)
You can access IE8 script console by launching the "Developer Tools" (F12). Click the "Script" tab, then click "Console" on the right.
From within your JavaScript code, you can do any of the following:
<script type="text/javascript">
console.log('some msg');
console.info('information');
console.warn('some warning');
console.error('some error');
console.assert(false, 'YOU FAIL');
</script>
Also, you can clear the Console by calling console.clear()
.
NOTE: It appears you must launch the Developer Tools first then refresh your page for this to work.
You have to use the didSelectRow
delegate method, because a UIPickerView
can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.
If you have problems like that, first of all your TC
folder put in to the C:..drive.
after completing installation open turbo c blue screen.
there is a OPTIONS > Directories
..in that you can see for option to set up path..
C:\TC\INCUDE
C:\TC\LIB
C:\TC\BIN
..otherwise you can set another path where you want to store your output..Finally you can give OK and finished processes.. It will now work properly
I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.
Samples:
a = Nokogiri::HTML.parse "foo bär"
a.text
=> "foo bär"
or
a = Nokogiri::HTML.parse "¡I'm highly annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"
If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.
openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null
If the remote server is not using SNI, then you can skip -servername
parameter:
openssl s_client -showcerts -connect www.example.com:443 </dev/null
To view the full details of a site's cert you can use this chain of commands as well:
$ echo | \
openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
openssl x509 -text
Because the static version of the .Equal
method was not mentioned so far, I would like to add this here to summarize and to compare the 3 variations.
MyString.Equals("Somestring")) //Method 1
MyString == "Somestring" //Method 2
String.Equals("Somestring", MyString); //Method 3 (static String.Equals method) - better
where MyString
is a variable that comes from somewhere else in the code.
Background info and to summerize:
In Java using ==
to compare strings should not be used. I mention this in case you need to use both languages and also
to let you know that using ==
can also be replaced with something better in C#.
In C# there's no practical difference for comparing strings using Method 1 or Method 2 as long as both are of type string. However, if one is null, one is of another type (like an integer), or one represents an object that has a different reference, then, as the initial question shows, you may experience that comparing the content for equality may not return what you expect.
Suggested solution:
Because using ==
is not exactly the same as using .Equals
when comparing things, you can use the static String.Equals method instead. This way, if the two sides are not the same type you will still compare the content and if one is null, you will avoid the exception.
bool areEqual = String.Equals("Somestring", MyString);
It is a little more to write, but in my opinion, safer to use.
Here is some info copied from Microsoft:
public static bool Equals (string a, string b);
Parameters
a
String
The first string to compare, or null
.
b
String
The second string to compare, or null
.
Returns Boolean
true
if the value of a
is the same as the value of b
; otherwise, false
. If both a
and b
are null
, the method returns true
.
I'm using nnoremap in my .vimrc
To single quote a word:
nnoremap sq :silent! normal mpea'<Esc>bi'<Esc>`pl
To remove quotes (works on double quotes as well):
nnoremap qs :silent! normal mpeld bhd `ph<CR>
Rule to remember: 'sq' = single quote.
Just because I did not see it mentioned.
If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.
Example
Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
Insert Into @YourTable Values
(1,'A','B')
,(2,'R','C')
,(3,'X','D')
Select A.[ID]
,Item = B.[Key]
,Value = B.[Value]
From @YourTable A
Cross Apply ( Select *
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] not in ('ID','Other','Columns','ToExclude')
) B
Returns
ID Item Value
1 Col1 A
1 Col2 B
2 Col1 R
2 Col2 C
3 Col1 X
3 Col2 D
The @android did not work for me. When I use android (without the @) it works like a charm.
Example:
<style name="CustomActionBarTheme"
parent="android:style/Theme.Holo.Light.DarkActionBar">
As has been discussed in detail, self-signed certificates are not trusted for the Internet. You can add your self-signed certificate to many but not all browsers. Alternatively you can become your own certificate authority.
The primary reason one does not want to get a signed certificate from a certificate authority is cost -- Symantec charges between $995 - $1,999 per year for certificates -- just for a certificate intended for internal network, Symantec charges $399 per year. That cost is easy to justify if you are processing credit card payments or work for the profit center of a highly profitable company. It is more than many can afford for a personal project one is creating on the internet, or for a non-profit running on a minimal budget, or if one works in a cost center of an organization -- cost centers always try to do more with less.
An alternative is to use certbot (see about certbot). Certbot is an easy-to-use automatic client that fetches and deploys SSL/TLS certificates for your web server.
If you setup certbot, you can enable it to create and maintain a certificate for you issued by the Let’s Encrypt certificate authority.
I did this over the weekend for my organization. I installed the required packages for certbot on my server (Ubuntu 16.04) and then ran the command necessary to setup and enable certbot. One likely needs a DNS plugin for certbot - we are presently using DigitalOcean though may be migrating to another service soon.
Note that some of the instructions were not quite right and took a little poking and time with Google to figure out. This took a fair amount of my time the first time but now I think I could do it in minutes.
For DigitalOcean, one area I struggled was when I was prompted to input the path to your DigitalOcean credentials INI file. What the script is referring to is the Applications & API page and the Tokens/Key tab on that page. You need to have or generate a personal access token (read and write) for DigitalOcean's API -- this is a 65 character hexadecimal string. This string then needs to be put into a file on the webserver from which you are running certbot. That file can have a comment as its first line (comments start with #). The seccond line is:
dns_digitalocean_token = 0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff
Once I figured out how to set up a read+write token for DigitalOcean's API, it was pretty easy to use certbot to setup a wildcard certificate. Note that one does not have to setup a wildcard certificate, one may instead specify each domain and sub-domain that one wants the certificate to appply to. It was the wildcard certificate that required the credentials INI file that contained the personal access token from DigitalOcean.
Note that public key certificates (also known as identity certificates or SSL certificates) expire and require renewal. Thus you will need to renew your certificate on a periodic (reoccurring) basis. The certbot documentation covers renewing certificates.
My plan is to write a script to use the openssl command to get my certificate's expiration date and to trigger renewal when it is 30 days or less until it expires. I will then add this script to cron and run it once per day.
Here is the command to read your certificate's expiration date:
root@prod-host:~# /usr/bin/openssl x509 -enddate -noout -in path-to-certificate-pem-file
notAfter=May 25 19:24:12 2019 GMT
public class ConfigureActivity extends Activity {
EditText etOne;
EditText etTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure);
Button btnConfigure = findViewById(R.id.btnConfigure1);
btnConfigure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
configure();
}
});
}
public void configure(){
String one = etOne.getText().toString();
String two = etTwo.getText().toString();
}
}
You want matplotlib.pcolor
:
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)
plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()
This gives:
@DawidDrozd's answer above is excellent.
I would add one point. Recent versions of the Clang compiler complain about requiring a "bridging cast" if attempting to use his code.
This seems reasonable: using a trampoline creates a potential bug: since Objective-C classes are reference counted, if we pass their address around as a void *, we risk having a hanging pointer if the class is garbage collected up while the callback is still active.
Solution 1) Cocoa provides CFBridgingRetain and CFBridgingRelease macro functions which presumably add and subtract one from the reference count of the Objective-C object. We should therefore be careful with multiple callbacks, to release the same number of times as we retain.
// C++ Module
#include <functional>
void cppFnRequiringCallback(std::function<void(void)> callback) {
callback();
}
//Objective-C Module
#import "CppFnRequiringCallback.h"
@interface MyObj : NSObject
- (void) callCppFunction;
- (void) myCallbackFn;
@end
void cppTrampoline(const void *caller) {
id callerObjC = CFBridgingRelease(caller);
[callerObjC myCallbackFn];
}
@implementation MyObj
- (void) callCppFunction {
auto callback = [self]() {
const void *caller = CFBridgingRetain(self);
cppTrampoline(caller);
};
cppFnRequiringCallback(callback);
}
- (void) myCallbackFn {
NSLog(@"Received callback.");
}
@end
Solution 2) The alternative is to use the equivalent of a weak reference (ie. no change to the retain count), without any additional safety.
The Objective-C language provides the __bridge cast qualifier to do this (CFBridgingRetain and CFBridgingRelease seem to be thin Cocoa wrappers over the Objective-C language constructs __bridge_retained and release respectively, but Cocoa does not appear to have an equivalent for __bridge).
The required changes are:
void cppTrampoline(void *caller) {
id callerObjC = (__bridge id)caller;
[callerObjC myCallbackFn];
}
- (void) callCppFunction {
auto callback = [self]() {
void *caller = (__bridge void *)self;
cppTrampoline(caller);
};
cppFunctionRequiringCallback(callback);
}
In my case, LoginActivity was closed as well. As a result,
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
did not help.
However, setting
Intent.FLAG_ACTIVITY_NEW_TASK
helped me.
const regex = /myRegexp/
console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!
_x000D_
The Regex literal notation is commonly used to create new instances of RegExp
regex needs no additional escaping
v
/ regex / gm
^ ^ ^
start end optional modifiers
As others sugguested, you can also use the new RegExp('myRegex')
constructor.
But you will have to be especially careful with escaping:
regex: 12\d45
matches: 12345
const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things
this works even if iframe is loading a different domain
check about postMessage()
plan is, send the css to iframe as a message like
iframenode.postMessage('h2{color:red;}','*');
*
is to send this message irrespective of what domain it is in iframe
and receive the message in iframe and add the received message(CSS) to that document head.
code to add in iframe page
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];
if you have a certain output type then do something like this
cat /path/to/files/*.txt >> finalout.txt
If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.
var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();
Then you'll be able to access it like:
nodes.Any(n => n.Checked);
Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.
nodes.Add(new { Checked = false, /* etc */ });
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Probably the simplest way to do it is to create a delegate and then BeginInvoke
, followed by a wait at some time in the future, and an EndInvoke
.
public bool Foo(){
Thread.Sleep(100000); // Do work
return true;
}
public SomeMethod()
{
var fooCaller = new Func<bool>(Foo);
// Call the method asynchronously
var asyncResult = fooCaller.BeginInvoke(null, null);
// Potentially do other work while the asynchronous method is executing.
// Finally, wait for result
asyncResult.AsyncWaitHandle.WaitOne();
bool fooResult = fooCaller.EndInvoke(asyncResult);
Console.WriteLine("Foo returned {0}", fooResult);
}
The following code I use mostly for achieving the asked effect:
body {
background-image: url('../images/bg.jpg');
background-repeat: no-repeat;
background-size: 100%;
}
There are two separate things here:
For example:
{
vector<MyObject> v;
// do some stuff, push some objects onto v
v.clear(); // 1
// maybe do some more stuff
} // 2
At 1
, you clear v
: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject
is now released.
However, vector v
has the right to keep the raw storage around in case you want it later.
If you decide to push some more things into it between 1
and 2
, this saves time as it can reuse the old memory.
At 2
, the vector v
goes out of scope: any objects you pushed into it since 1
will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v
won't be around to reuse it any more).
If I change the example so v
becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2
doesn't do that for you. It's better to use something like std::unique_ptr
in that case, but if you don't and v
is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v
is deleted, and calling clear
isn't sufficient.
To add to marcio's awesome solution, dismissActionSheet:
can be implemented as follows.
Add this method to your code.
- (void)dismissActionSheet:(id)sender{
[_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
[_myButton setTitle:@"new title"]; //set to selected text if wanted
}
It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.
You can try this:
#include<stdio.h>
#include<stdlib.h>
int *fun();
int main()
{
int *ptr;
ptr=fun();
printf("\n\t\t%d\n",*ptr);
}
int *fun()
{
int ptr;
ptr=12;
return(&ptr);
}
This answer is applicable to .NET Core only!
Typing dotnet --version
in your terminal of choice will print out the version of the .NET Core SDK in use.
Learn more about the dotnet
command here.
Ok so Form1
has a textbox, first of all you have to set this Form1
textbox to public in textbox property.
Code Form1:
Public button1_click()
{
Form2 secondForm = new Form2(this);
secondForm.Show();
}
Pass Form1
as this
in the constructor.
Code Form2:
Private Form1 _firstForm;
Public Form2(Form1 firstForm)
{
_firstForm = firstForm:
}
Public button_click()
{
_firstForm.textBox.text=label1.text;
This.Close();
}
For people that need the title set statically. This can be done in the AndroidManifest.xml
<activity
android:name=".ActivityName"
android:label="Title Text" >
</activity>
You can get annotations on the getter method:
propertyDescriptor.getReadMethod().getDeclaredAnnotations();
Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.
ng If else statement
ng-if="receiptData.cart == undefined ? close(): '' ;"
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
info registers
shows all the registers; info registers eax
shows just the register eax
. The command can be abbreviated as i r
function GetPixel(context, x, y)
{
var p = context.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
Here's how you should do it:
change_column :users, :admin, :boolean, :default => false
But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.
Like this:
<?php
$option = $_POST['taskOption'];
?>
The index of the $_POST
array is always based on the value of the name
attribute of any HTML input.
One approach (which I can't imagine is good programming practice) is to add the ...
which is traditionally used to pass arguments specified in one function to another.
> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8
You can read more about ...
is intended to be used here
You're looking for the onclose event.
see: https://developer.mozilla.org/en/DOM/window.onclose
note that not all browsers support this (for example firefox 2)
What works for me is
dataset = pd.read_csv('FBI_CRIME11.csv')
Highlight it and press enter. It also depends on the IDE you are using. I am using Anaconda Spyder or Jupiter.
You miss the class declaration.
public class DerivativeQuiz{
public static void derivativeQuiz(String args[]){ ... }
}
If you're working in a security sensitive environment, then please read this through.
Please refrain from ever trusting a property obtained via the System#getProperty(String)
subroutine! Actually, almost every property including os.arch
, os.name
, and os.version
isn't readonly as you'd might expect — instead, they're actually quite the opposite.
First of all, any code with sufficient permission of invoking the System#setProperty(String, String)
subroutine can modify the returned literal at will. However, that's not necessarily the primary issue here, as it can be resolved through the use of a so called SecurityManager
, as described in greater detail over here.
The actual issue is that any user is able to edit these properties when running the JAR
in question (through -Dos.name=
, -Dos.arch=
, etc.). A possible way to avoid tampering with the application parameters is by querying the RuntimeMXBean
as shown here. The following code snippet should provide some insight into how this may be achieved.
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
for (String argument : arguments) {
if (argument.startsWith("-Dos.name") {
// System.getProperty("os.name") altered
} else if (argument.startsWith("-Dos.arch") {
// System.getProperty("os.arch") altered
}
}
There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.
window.open(url)
1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<script>
var url1 ='https://stackoverflow.com/a/54675103';
var winRef = window.open(url1);
winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
window.onload=function(){document.getElementById('url').href = url1;}
</script>
</head>
<body>
Kindly allow pop ups</br>
Or <a id='url'>Click here </a>to continue!!!
</body>
</html>
function modalUrl(){
SpreadsheetApp.getUi()
.showModalDialog(
HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
'Opening StackOverflow'
)
}
Is this what you're looking for?
#include <chrono>
#include <iostream>
int main()
{
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
auto t0 = Time::now();
auto t1 = Time::now();
fsec fs = t1 - t0;
ms d = std::chrono::duration_cast<ms>(fs);
std::cout << fs.count() << "s\n";
std::cout << d.count() << "ms\n";
}
which for me prints out:
6.5e-08s
0ms
if (grid.selectedKeyNames().length > 0) {
$('#btnRemoveFromList').show();
} else {
$('#btnRemoveFromList').hide();
}
}
()
- calls the method
no parentheses - returns the property
Resetting the src attribute directly:
iframe.src = iframe.src;
Resetting the src with a time stamp for cache busting:
iframe.src = iframe.src.split("?")[0] + "?_=" + new Date().getTime();
Clearing the src when query strings option is not possible (Data URI):
var wasSrc = iframe.src
iframe.onload = function() {
iframe.onload = undefined;
iframe.src = wasSrc;
}
If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status
from your terminal you'd see which location you are. In some cases, you'd see origin/main
.
If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.
example:
git push heroku main
If your index is less than the size of your list then it does exist, possibly with null
value. If index is bigger then you may call ensureCapacity()
to be able to use that index.
If you want to check if a value at your index is null
or not, call get()
I have created a function for this purpose.
function free_port() {
if [ -z $1 ]
then
echo no Port given
else
PORT=$1;
PID=$(sudo lsof -i :$PORT) # store the PID, that is using this port
if [ -z $PID ]
then
echo port: $PORT is already free.
else
sudo kill -9 $PID # kill the process, which frees the port
echo port: $PORT is now free.
fi
fi
}
free_port 80 # you need to change this port number
Copy & pasting this block of code in your terminal should free your desired port. Just remember to change the port number in last line.
Keep it simple
dataGridView1.Columns.Add("newColumnName", "Column Name in Text");
To add rows
dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
The absolute easiest method if all you want to run is a simple script, (or anything) is if you have a gui to use system > preferences then startup apps.
just browse to the script you want and there you go. (make script executable)
Dragon NaturallySpeaking seems to support MP3 input.
If you want an open source version (I think there are some Asterisk integration projects based on this one).
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
I just found the way. Right click on the desired package then Source
-> Organize Imports
.
Shortcut keys:
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.
try:
from urllib import quote # Python 2.X
except ImportError:
from urllib.parse import quote # Python 3+
You could also use the python compatibility wrapper six to handle this.
from six.moves.urllib.parse import quote
I had similar issue. Try use the HQL editor. It will display you the SQL (as you have a SQL grammar exception). Copy your SQL and execute it separately. In my case the problem was in schema definition. I defined the schema, but I should leave it empty. This raised the same exception as you got. And the error description reflected the actual state, as the schema name was included in SQL statement.
bool isMultiple = a % b == 0;
This will be true if a is a multiple of b
You can index into a tuple:
(falseValue, trueValue)[test]
test
needs to return True or False.
It might be safer to always implement it as:
(falseValue, trueValue)[test == True]
or you can use the built-in bool()
to assure a Boolean value:
(falseValue, trueValue)[bool(<expression>)]
Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).
Had same issue with Firefox. I switched over to Chrome with options and all has been fine since.
ChromeOptions options = new ChromeOptions();
options.AddArgument("no-sandbox");
ChromeDriver driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), options, TimeSpan.FromMinutes(3));
driver.Manage().Timeouts().PageLoad.Add(System.TimeSpan.FromSeconds(30));
If you are using CORS middleware and you want to send withCredential
boolean true, you can configure CORS like this:
var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));