Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
I just got a similar error for the first time today. It appears in \node_modules\metro-config\src\defaults\blacklist.js
, there is an invalid regular expression that needed changed. I changed the first expression under sharedBlacklist
from:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
to:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
Problem occurs when we want to import CommonJS module into ES6 module codebase.
Before these flags we had to import CommonJS modules with star (* as something
) import:
// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// transpiled js (simplified):
const moment = require("moment");
moment();
We can see that *
was somehow equivalent to exports
variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment
in our case) can be only a plain object, not callable (moment()
is not allowed).
With flag esModuleInterop
we can import CommonJS modules in compliance with es6
modules spec. Now our import code looks like this:
// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec
// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
It works and it's perfectly valid with es6 modules spec, because moment
is not namespace from star import, it's default import.
But how does it work? As you can see, because we did a default import, we called the default
property on a moment
object. But we didn't declare a default
property on the exports
object in the moment library. The key is the __importDefault
function. It assigns module (exports
) to the default
property for CommonJS modules:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default
key. This makes it possible to import defaults on CommonJS modules.
__importStar
does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default
property:
// index.ts file in our app
import * as moment from 'moment'
// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
And what about allowSyntheticDefaultImports
- what is it for? Now the docs should be clear:
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
In moment
typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop
on. So allowSyntheticDefaultImports
will not report an error if we want to import default from a third-party module which doesn't have a default export.
If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32
I have the same problem after upgrading to Gradle Wrapper 5.0., Now I switch back to 4.10.3 which just released 5 December 2018 based on Gradle documentation and use Android Gradle Plugin: 3.2.1 (the latest stable version).
I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())
This is a popular question. If you do not use these methods, the solution is updating the libraries. Please update your kotlin version, and all your dependencies like fabric, protobuf etc. If you are sure that you have updated everything, try asking the author of the library.
open file gradle.properties and add these two lines to it:
android.useAndroidX = true
android.enableJetifier = true
clean and build
If you receive an error stating the library cannot be found, check the Google maven repo for your library and version. I had a version suddenly disappear and make my builds fail.
Inside your lib file
Create a folder called colors
.
Inside the colors
folder create a dart file and name it color
.
Paste this code inside it
const MaterialColor primaryOrange = MaterialColor(
_orangePrimaryValue,
<int, Color>{
50: Color(0xFFFF9480),
100: Color(0xFFFF9480),
200: Color(0xFFFF9480),
300: Color(0xFFFF9480),
400: Color(0xFFFF9480),
500: Color(0xFFFF9480),
600: Color(0xFFFF9480),
700: Color(0xFFFF9480),
800: Color(0xFFFF9480),
900: Color(0xFFFF9480),
},
);
const int _orangePrimaryValue = 0xFFFF9480;
Go to your main.dart
file and place this code in your theme
theme:ThemeData(
primarySwatch: primaryOrange,
),
Import the color
folder in your main.dart
like this import 'colors/colors.dart'
;
Check MediaQuery
class
For example, to learn the size of the current media (e.g., the window containing your app), you can read the
MediaQueryData.size
property from theMediaQueryData
returned byMediaQuery.of
:MediaQuery.of(context).size
.
So you can do the following:
new Container(
height: MediaQuery.of(context).size.height/2,
.. )
About the removal of componentWillReceiveProps
: you should be able to handle its uses with a combination of getDerivedStateFromProps
and componentDidUpdate
, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps
updates the state similarly to an object passed to setState
.
In case you really need the old value of a prop, you can always cache it in your state with something like this:
state = {
cachedSomeProp: null
// ... rest of initial state
};
static getDerivedStateFromProps(nextProps, prevState) {
// do things with nextProps.someProp and prevState.cachedSomeProp
return {
cachedSomeProp: nextProps.someProp,
// ... other derived state properties
};
}
Anything that doesn't affect the state can be put in componentDidUpdate
, and there's even a getSnapshotBeforeUpdate
for very low-level stuff.
UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.
It worked when I downgrade the support appcompat
gradle dependency, like follwing :
implementation 'com.android.support:appcompat-v7:27.0.2'
previously it was
implementation 'com.android.support:appcompat-v7:27.1.0'
OR
Also this can be fixed by just adding support design dependency
of version 27.1.0 or above to your app level build.gradle
as following :
implementation 'com.android.support:design:27.1.0'
-May be the problem is that you have deleted .java files doing this doesn't delete the .XML files so go to res-> layout and delete those .XML files that you had delete before. -the another problem may be you haven't delete the files that is present in manifests under syntax that you deleted recently... So delete and run the code
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.dev.khamsat"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "2.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
I found the solution as Its problem with Android Studio 3.1 Canary 6
My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.
Now My build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.example.demo"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.android.support.constraint:constraint-layout:1.0.2"
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
implementation "com.squareup.picasso:picasso:2.5.2"
implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
compile 'com.github.elevenetc:badgeview:v1.0.0'
annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
testImplementation "junit:junit:4.12"
androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
exclude group: "com.android.support", module: "support-annotations"
})
}
and My gradle is:
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
and its working finally.
I think there problem in Android Studio 3.1 Canary 6
Thank you all for your time.
Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)
Search for cursorColumnSelectDown
or cursorColumnSelectUp
which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow
The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'
interface AppProps {
//code related to your props goes here
}
interface AppState {
value: any
}
class App extends React.Component<AppProps, AppState> {
// ...
}
Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
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.
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
For Cordova based project, run cordova clean android
before build again, as @mkimmet suggested.
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....
use .then()
example:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
some refs =>
...
<head>
// CSRF for all ajax call
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
...
...
<script>
// CSRF for all ajax call
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...
If this error appeared for you after including kotlin support, and none of the other solutions work, try changing the kotlin dependency of app module's build.gradle
to:
implementation ("org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version") {
exclude group: 'org.jetbrains', module: 'annotations'
}
This works for me on Android Studio 3.0 Beta 6. See this answer for further explanation.
Just ran into this... I have a common library shared among multiple transpiled products. I was using symlinks with brunch to handle sharing things between the projects. When moving to webpack, this stopped working.
What did get things working was using webpack configuration to turn off symlink resolving.
i.e. adding this in webpack.config.js
:
module.exports = {
//...
resolve: {
symlinks: false
}
};
as documented here:
https://webpack.js.org/configuration/resolve/#resolvesymlinks
I solved this problem as follow:
npm install
.Actually, when you read docs the ListView should be inside Expanded Widget so it can work.
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Align(
child: PayableWidget(),
),
Expanded(
child: _myListView(context),
)
],
));
}
Make sure you're adding these dependencies in android/app/build.gradle, not android/build.gradle
change
compile 'com.android.support:appcompat-v7:26.0'
to
`compile 'com.android.support:appcompat-v7:26.+'`
worked for me fine.
For Flutter 1.17.3 (stable channel as of June 2020), use
FocusManager.instance.primaryFocus.unfocus();
Replace a hard coded version to + example:
implementation 'com.google.android.gms:play-services-base:+'
implementation 'com.google.android.gms:play-services-maps:+'
Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.
For me, I was using someone's project and I was having issue compiling the lib.
The solution to add packagingOptions
didn't helped because it would prevent compiling latest .so file of armeabi-v7a and will copy the .so file from jniLibs
to the built APK file
I deleted the jniLibs
folder from \app\src\main
and it solved the problem
Just Change the Distribution url at gradle-wrapper.properties
Place it : https://services.gradle.org/distributions/gradle-4.10.1-all.zip
In my case error was caused by this line
@BindColor(R.color.colorAccent) var mColor: Int? = 0
Solved By
@JvmField @BindColor(android.R.color.white) @ColorInt internal var mColor: Int = 0
Error in GradleConsole
:app:kaptDebugKotlin e: \app\build\tmp\kapt3\stubs\debug\MainFragment.java:23: error: @BindColor field type must be 'int' or 'ColorStateList'. (com.sample.MainFragment.mColor) e:
e: private java.lang.Integer mColor;
Remove the declaration from AppModule
, but update the AppModule
configuration to import your AddEventModule
.
.....
import { AddEventModule } from './add-event.module'; // <-- don't forget to import the AddEventModule class
@NgModule({
declarations: [
MyApp,
HomePage,
Login,
Register,
//AddEvent, <--- remove this
EventDetails
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule,
AngularFireModule.initializeApp(config),
AddEventModule, // <--- add this import here
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
Login,
Register,
AddEvent,
EventDetails
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}, Eventdata, AuthProvider
]
})
export class AppModule {}
Also,
Note that it's important that your AddEventModule
exports the AddEvent
component if you want to use it outside that module. Luckily, you already have that configured, but if it was omitted, you would've gotten an error if you tried to use the AddEvent
component in another component of your AppModule
When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:
entity.HasKey(X => x.Id);
I'm not saying this is better, or even the right way. I'm just saying that it worked for me.
Simply call it inside any function you like.
this.props.history.push('/main');
I changes only two points
Obviously they were according to the version of the versions that it has, otherwise they would have to download them
buil.gradle(Project)
dependencies {
classpath 'com.android.toolsg.build:gradle:2.3.2'
..
}
gradle.wrapper.properties
...
distributionUrl=https://services.gradle.org/distributions/gradle-3.3-all.zip
This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.
Example:
Solution: change the Unit Test to C++17 as well.
I solved same situation.
INSTALLED VERSION
python 3.6, django 2.1
SITUATION
I installed Node.js in Windows 10. After python manage.py runserver
caused error.
ERROR
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax
REASON
My python path changed to python-2.7 from python-3.6. (3.6 is correct in my PC.)
SOLUTION
Fix python path.
Linux Users:
cp -r Android AndroidUnity
cd AndroidUnity/Sdk
rm -rf tools
wget http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip
unzip tools_r25.2.5-windows.zip
In Unity preferences change to this newly created sdk folder.
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
Run bellow command in Android studio terminal after opening the same project. It worked for me.
On Windows:
gradlew cleanBuildCache
On Mac or Linux:
./gradlew cleanBuildCache
in my case i was using compile sdk 23
and build tools 25.0.0
just changed compile sdk
to 25 and done..
To handle sortable list in Framework7 when user release currently sorting element in new position, you can use this code:
$$('li').on('sortable:sort',function(event){
alert("From " + event.detail.startIndex + " to " + event.detail.newIndex);
});
Fiddle : https://jsfiddle.net/0zf5w4y7/
The problem is not with the Event type, but that the EventTarget interface in typescript only has 3 methods:
interface EventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: Date;
type: string;
}
So it is correct that name
and value
don't exist on EventTarget. What you need to do is to cast the target to the specific element type with the properties you need. In this case it will be HTMLInputElement
.
update = (e: React.SyntheticEvent): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
Also for events instead of React.SyntheticEvent, you can also type them as following: Event
, MouseEvent
, KeyboardEvent
...etc, depends on the use case of the handler.
The best way to see all these type definitions is to checkout the .d.ts files from both typescript & react.
Also check out the following link for more explanations: Why is Event.target not Element in Typescript?
I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command
For reset all field in one form you can use event.target.reset()
const app = new Vue({_x000D_
el: '#app', _x000D_
data(){_x000D_
return{ _x000D_
name : null,_x000D_
lastname : null,_x000D_
address : null_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
submitForm : function(event){_x000D_
event.preventDefault(),_x000D_
//process... _x000D_
event.target.reset()_x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
form input[type=text]{border-radius:5px; padding:6px; border:1px solid #ddd}_x000D_
form input[type=submit]{border-radius:5px; padding:8px; background:#060; color:#fff; cursor:pointer; border:none}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>_x000D_
<div id="app">_x000D_
<form id="todo-field" v-on:submit="submitForm">_x000D_
<input type="text" v-model="name"><br><br>_x000D_
<input type="text" v-model="lastname"><br><br>_x000D_
<input type="text" v-model="address"><br><br>_x000D_
<input type="submit" value="Send"><br>_x000D_
</form>_x000D_
</div>
_x000D_
I have examined all the above answer's, We just need to implement two things to work it as expected.
Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its explicitly for navigating to external links, Instead use routerLink = " " which helps in navigating views.
<ul>
<li><a routerLink="" (click)="hitAnchor1($event)"><p>Click One</p></a></li>
<li><a routerLink="" (click)="hitAnchor2($event)"><p>Click Two</p></a></li>
</ul>
Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,
hitAnchor1(e){
console.log("Events", e);
alert("You have clicked the anchor-1 tag");
}
hitAnchor2(e){
console.log("Events", e);
alert("You have clicked the anchor-2 tag");
}
That's all. It work's as expected. I created the example below, You can have a look:-
Btw, just had the same problem.
If you had my case, then you probably have the tsconfig.json not in the same directory as the .ts file.
(In my case I stupidly had next to launch.json and tasks.json inside the .vscode folder :P)
No need to redirect logs.
Docker by default store logs to one log file. To check log file path run command:
docker inspect --format='{{.LogPath}}' containername
/var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log
Open that log file and analyse.
if you redirect logs then you will only get logs before redirection. you will not be able to see live logs.
EDIT:
To see live logs you can run below command
tail -f `docker inspect --format='{{.LogPath}}' containername`
Note:
This log file /var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log
will be created only if docker generating logs if there is no logs then this file will not be there. it is similar like sometime if we run command docker logs containername
and it returns nothing. In that scenario this file will not be available.
Follow these steps to begin using Angular Material.
Step 1: Install Angular Material
npm install --save @angular/material
Step 2: Animations
Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the @angular/animations
module and include the BrowserAnimationsModule in your app.
npm install --save @angular/animations
Then
import {BrowserAnimationsModule} from '@angular/platform browser/animations';
@NgModule({
...
imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }
Step 3: Import the component modules
Import the NgModule for each component you want to use:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdCardModule} from '@angular/material';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdCardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4: Include a theme
Including a theme is required to apply all of the core and theme styles to your application.
To get started with a prebuilt theme, include the following in your app's index.html:
<link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
You can replace "quote" characters with an empty string, like this:
>>> a = '"sajdkasjdsak" "asdasdasds"'
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'
In your case, you can do the same for out
variable.
try this :
driver = webdriver.Chrome(ChromeDriverManager().install())
if error from butterknife auto generated file then update butterknife dependency version
implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'
This error message...
FileNotFoundError: [WinError 2] The system cannot find the file specified
...implies that your program was unable to locate the specified file and while handling the exception the following exception occurred:
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
... which implies that your program was unable to locate the GeckoDriver in the process of initiating/spawnning a new Browsing Context i.e. Firefox Browser session.
You can download the latest GeckoDriver from mozilla / geckodriver, unzip/untar and store the GeckoDriver binary/executable anywhere with in your system passing the absolute path of the GeckoDriver through the key executable_path
as follows:
from selenium import webdriver
driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
driver.get('http://google.com/')
In case firefox is not installed at the default location (i.e. installed at a custom location) additionally you need to pass the absolute path of firefox
binary through the attribute binary_location
as follows:
# An Windows example
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get('http://google.com/')
In the app build.gradle
dependency, you must add the following code
classpath 'com.google.gms:google-services:$last_version'
And then please check the Google Play Service SDK tools installing status.
add in project root path google-services.json
dependencies {
compile 'com.android.support:support-v4:25.0.1'
**compile 'com.google.firebase:firebase-ads:9.0.2'**
compile files('libs/StartAppInApp-3.5.0.jar')
compile 'com.android.support:multidex:1.0.1'
}
apply plugin: 'com.google.gms.google-services'
To add the latest solution for 2021...
I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.
After installing using npm install nanoid
, use as follows:
import { nanoid } from 'nanoid';
// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];
// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
According to the Apache documentation, found here, the DirectoryIndex
directive needs to be specified in the site .conf
file (typically found in /etc/apache2/sites-available
on linux).
Quoting from the docs, it reads:
If no file from the
DirectoryIndex
directive can be located in the directory, then mod_autoindex can generate a listing of the directory contents. This is turned on and off using theOptions
directive. For example, to turn on directory listings for a particular directory, you can use:<Directory /usr/local/apache2/htdocs/listme> Options +Indexes </Directory>
To prevent directory listings (for security purposes, for example), you should remove the Indexes keyword from every Options directive in your configuration file. Or to prevent them only for a single directory, you can use:
<Directory /usr/local/apache2/htdocs/dontlistme> Options -Indexes </Directory>
There are many suggestions but I found two of them most common.
I first tried export JAVA_OPTS="-Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2"
on command line before startup of program but it didn't work for me.
Then I added the following code in the startup class constructor and it worked for me.
try {
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, null, null);
SSLContext.setDefault(ctx);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Frankly, I don't know in detail why ctx.init(null, null, null);
but all (SSL/TLS) is working fine for me.
There is one more option: System.setProperty("https.protocols", "SSLv3,TLSv1,TLSv1.1,TLSv1.2");
. It will also go in code but I've not tried it.
If you don't want to modify current codes and just for debug usage.
Add this macro:
#define printf(args...) fprintf(stderr, ##args)
//under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
//under MSVC
Change stderr
to stdout
if you want to roll back.
It's helpful for debug, but it's not a good practice.
All previous contributes are fine, but a little note:
a) if orientation is set in plist, only portrait or example, You will be not notified via viewWillTransition
b) if we anyway need to know if user has rotated device, (for example a game or similar..) we can only use:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
tested on Xcode8, iOS11
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
You can basically switch the class using [ngClass]
for example
<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>
This is an easy way to prevent the click event from moving forward to the next component and then call your yourFunction.
<Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button>
It solved for me using
checkout scm: ([
$class: 'GitSCM',
userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
branches: [[name: 'refs/tags/${project_tag}']]
])
Please check you oppened in your VS Code the folder of the entire project and not only the src folder, because if you open only the src, then ts.config.json (located in the project folder) file will not be in scope, and VS will not recognize the experimental decorators parameters.
In my case this fixed all the problems related to this issue.
I got this working by installing the various plugins below.
Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.
Screenshot of Extensions
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Look here -> https://material-ui.com/guides/composition/#button.
This is the official material-ui guide. Maybe it'll be useful to you as it was for me.
However, in some cases, underline persists and you may want to use text-decoration: "none" for that. For a more cleaner approach, you can import and use makeStyles from material-ui/core.
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles(() => ({
menu-btn: {
textDecoration: 'none',
},
}));
const classes = useStyles();
And then set className attribute to {classes.menu-btn} in your JSX code.
As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
first you remove this thing in your project .. its is in build.gradle(module:app) then build your app now you project show the actual error and you find what is your actual problem is .. and after you find actual problem again paste it where its is belong to
allprojects { gradle.projectsEvaluated {
tasks.withType(JavaCompile)
{ options.encoding = 'UTF-8'
options.compilerArgs
<< "-Xlint:unchecked" << "-Xlint:deprecation"}]}}
In my case I had 2 projects A
and B
. And I upgraded to gradle 4.5
.
A
was dependent on B
but both had references of my 3rd party jar
I was getting this error
com.android.tools.r8.errors.CompilationError: Program type already present: com.mnox.webservice.globals.WebServiceLightErrorHashCode
Program type already present: com.mnox.webservice.globals.WebServiceLightErrorHashCode
To fix it
api
in the B
build.gradle file so that it gets referred to in A
.The other root cause can be if you have upgraded to gradle 4.5
and used implementation
instead of api
in your commons build.gradle
If you have just added FCM to an existing app, onTokenRefresh()
will NOT be called. I got it to run by uninstalling the app and installing it again.
The problem, as stated in your logs, is 2 dependencies trying to use different versions of 3rd dependency. Add one of the following to the app-gradle file:
androidTestCompile 'com.google.code.findbugs:jsr305:2.0.1'
androidTestCompile 'com.google.code.findbugs:jsr305:1.3.9'
Just set targetSdkVersion to 19. The notification icon will be colored. Then wait for Firebase to fix this issue.
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.
apachectl configtest
I had the same issue and this is what I did and I was able to solve my issue:
Gradle file was updated from classpath 'com.android.tools.build:gradle:3.6.1' to
classpath 'com.android.tools.build:gradle:3.1.3'
Then distribution URL in gradle-wrapper.properties file was updated from distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip to
distributionUrl=https://services.gradle.org/distributions/gradle-5.4.1-all.zip
Gradle was then synched.
In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:
- name: set pkg copy dir name
set_fact:
PKG_DIR: >-
{% if ansible_os_family == "RedHat" %}centos/*.rpm
{%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
{%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
{%- else %}{%- endif %}
you can enable "Instant Run" on Android Studio to get multidex support.
In react 16, I use
<Input id="number"
type="time"
onChange={(evt) => { console.log(evt.target.value); }} />
You need to import moment() the function and Moment the class separately in TS.
I found a note in the typescript docs here.
/*~ Note that ES6 modules cannot directly export callable functions
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
So the code to import moment js into typescript actually looks like this:
import { Moment } from 'moment'
....
let moment = require('moment');
...
interface SomeTime {
aMoment: Moment,
}
...
fn() {
...
someTime.aMoment = moment(...);
...
}
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
I solved this by setting a higher timeout value for the proxy:
location / {
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_pass http://localhost:3000;
}
Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html
` Adding the following to pom.xml will resolve the issue. <pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories> `
If you use checkbox
<input
type='checkbox'
onChange={this.checkboxHandler}
/>
stopPropagation and stopImmediatePropagation won't be working.
Because you must using onClick={this.checkboxHandler}
After updating my Android SDK I stumbled upon this very problem and I tried many ways without success. What was most irritating to me when searching for a fix, were the lots of answers suggesting to change the CompileSdkVersion to a certain number while obviously this number changes with time, so here's what I did instead.
I created a new project and ran it on the emulator to make sure it's working, then checked its "\android\app\build.gradle" file and copied the numeric value of CompileSdkVersion and pasted into the same file in my other project that could not be built properly anymore. Now my problem's gone. Hope that helps.
in my case just
const myReducers = combineReducers({
user: UserReducer
});
const store: any = createStore(
myReducers,
applyMiddleware(thunk)
);
shallow(<Login />, { context: { store } });
TL;DR: Check the path to your keystore.jks
file.
In my case, here's what happened:
I moved the project folder of my entire app to another location on my PC. Much later, I wanted to generate a signed apk file. Unknown to me, the default location of the path to my keystore.jks
had been reset to a wrong location and I had clicked okay. Since it could not find a keystore at the path I selected, I got that error.
The solution was to check whether the path to my keystore.jks
file was correct.
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.
do like this simply: (as said in comment here is with example with two methods)
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
<button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
`
})
export class AppComponent {
checkEvent(event, id){
console.log(event, id, event.srcElement.attributes.id);
}
}
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
Add this line to ProGuard-rules.pro file:
-keepparameternames
That helped me while obfuscating library. I was getting zip exception when I add library as dependency.
In my case, it's because of apache server is running somehow. So I stop apache then restart nginx. Work like a charm!
sudo /etc/init.d/apache2 stop
sudo systemctl restart nginx
In addition to available solutions, please check this also.
If you have set android:allowBackup="false"
in your AndroidManifest.xml
then there may be a conflict for android:allowBackup="true"
in other dependencies.
Solution
As suggested by @CLIFFORD P Y, switch to Merged Manifest
in your AndroidManifest.xml
. Android Studio will suggest to add tools:replace="android:allowBackup"
in <application />
in your AndroidManifest.xml
.
The best way to handle styling is by using classes with set of css properties.
example:
<Component className={this.getColor()} />
getColor() {
let class = "badge m2";
class += this.state.count===0 ? "warning" : danger;
return class;
}
From my experience in React Native, you can also restart your CLI and this error goes away.
I prefer to solve this in the classic way, creating a new array of my desired data type:
List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));
You need to override this code in your Activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu, this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
and set your toolbar like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
For me the problem was that right after making the request, my main activity launched another activity. That superseded the dialog so it was never seen.
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "POST",
url: urlToSend,
data: { id: clickedButton.val(), access_token: $("#access_token").val() },
success:function(result){
alert('ok');
},
error:function(result)
{
alert('error');
}
});
}
$(document).ready(function(){
$("#button_1").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
$("#button_2").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
});
Angular 9 out of the box should work absolutely fine in IE11 now.
I tried all of the suggestions listed here and none of them worked. However I did manage to track it down to a specific library I was importing in app.module
(ZXingScannerModule
to be precise). If your app is failing in IE11 on the first page, try removing libraries one at a time and check in IE11 - it was completely missed in all my build warning errors. If you do find this is the case, then consider compartmentalising the area of your site which uses this library as a lazy loaded module.
You must change your activity_contact_list
to be binded - add layout tag as you did in content_contact_list
. Don't forget, The root layout inside activity_contact_list
must have an id for the Binding class to be generated and will be named ActivityContactListBinding (i.e. the name of the layout with camel casting instead of underscores).
Next, inside activity_contact_list
, give <include layout="@layout/content_contact_list" />
an id, then you will have access for its binding instance through your ActivityContactListBinding instance.
Somthing like:
binding.contentContactList.setContact(user);
Let me know if it works.
An easier way is to use redux-auto.
from the documantasion
redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.
The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.
It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.
also try to increase gradle version in your project's build.gradle. It helped me
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.
It's kind of hard to tell in your exact situation but I'd probably use a v-for
and make an array of finds
to push to as I need more.
Here's how I'd set up my instance:
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ value: '' });
}
}
});
And here's how I'd set up my template:
<div id="app">
<h1>Finds</h1>
<div v-for="(find, index) in finds">
<input v-model="find.value" :key="index">
</div>
<button @click="addFind">
New Find
</button>
</div>
Although, I'd try to use something besides an index
for the key
.
Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/
The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8"
and then let your API method consume JSON. Like this:
var basicInfo = JSON.stringify({
firstName: playerProfile.firstName(),
lastName: playerProfile.lastName(),
gender: playerProfile.gender(),
address: playerProfile.address(),
country: playerProfile.country(),
bio: playerProfile.bio()
});
$.ajax({
url: "http://localhost:8080/social/profile/update",
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: basicInfo,
success: function(data) {
// ...
}
});
@RequestMapping(
value = "/profile/update",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
@RequestBody User usersNewDetails,
HttpServletRequest request,
HttpServletResponse response
) {
// ...
}
I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.
Note: the default content type for ajax is "application/x-www-form-urlencoded"
.
For me, I had to check the google-services.json
file and make sure "package_name"
was correctly set to the package name of my android app. The auto generated services file had .backend
appended to it in my case.
Update September 26, 2016:
As @Taytay's answer says, instead of the 'typings' installations that we used a few months ago, we can now use:
npm install --save @types/lodash
Here are some additional references supporting that answer:
If still using the typings installation, see the comments below (by others) regarding '''--ambient''' and '''--global'''.
Also, in the new Quick Start, config is no longer in index.html; it's now in systemjs.config.ts (if using SystemJS).
Original Answer:
This worked on my mac (after installing Angular 2 as per Quick Start):
sudo npm install typings --global
npm install lodash --save
typings install lodash --ambient --save
You will find various files affected, e.g.
Angular 2 Quickstart uses System.js, so I added 'map' to the config in index.html as follows:
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
map: {
lodash: 'node_modules/lodash/lodash.js'
}
});
Then in my .ts code I was able to do:
import _ from 'lodash';
console.log('lodash version:', _.VERSION);
Edits from mid-2016:
As @tibbus mentions, in some contexts, you need:
import * as _ from 'lodash';
If starting from angular2-seed, and if you don't want to import every time, you can skip the map and import steps and just uncomment the lodash line in tools/config/project.config.ts.
To get my tests working with lodash, I also had to add a line to the files array in karma.conf.js:
'node_modules/lodash/lodash.js',
this is happening because you are using the rxjs and in rxjs function are not static which means you can't call them directly you have to call the methods inside the pipe and import that function from the rxjs library
But if you are using rxjs-compat then you just need to import the rxjs-compat operators
I was encountering the same issue. In my App build.gradle I had
apply plugin: 'com.android.application'
apply plugin: 'dexguard'
apply plugin: 'io.fabric'
I just switched Dexguard and Fabric, then it worked!
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'dexguard'
Please add this block inside android in build.gradle
dexOptions {
preDexLibraries = false
}
My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.
While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do
EVP_CIPHER_CTX_set_padding(context, 0);
So non matching padding options can be one reason.
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
With tensorflow version >3.2 you may use this command:
x1 = tf.Variable(5)
y1 = tf.Variable(3)
z1 = x1 + y1
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
init.run()
print(sess.run(z1))
The output: 8 will be displayed.
From tensorflow official docs
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
100000, 0.96, staircase=True)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step))
If java 8 or above is used then the problem is the libraries we use are incompatible with java 8. So to solve this add these two lines to build.gradle of your app and all sub modules if any. (Android studio clearly show how to do this in error message)
targetCompatibility = '1.7' sourceCompatibility = '1.7'
If you´re building a new app, put the jsonfile in the right place and make sure it's the jsonfile for that app. Before I realized this, when I clicked the jsonfile, I didn't get the information that wanted.
Go to firebase configurations, download the correct version of google-services.json
, and replace the version that didn't work for you. When using the wrong version, you might see the wrong Projectid, storagebucket etc.
This error can be because of too much reasons. Try first with testAds ca-app-pub id to avoid admob account issues.
Check that you extends AppCompatActivity in your mainActivity, in my case that was the issue
Also check all this steps again https://developers.google.com/admob/android/quick-start?hl=en-419#import_the_mobile_ads_sdk
Ensure the IDE recognizes that you have the package. It didn't on mine even after downloading 28, so I uninstalled then reinstalled it after realizing it wasn't showing up under File-Project Structure-Modules-App as a choice for SDK.
On top of that, you may want to change your build path to match.
Slightly related, the latest updates seem able to compile when I forced an update all the way to 28 for CompileSDK, and not just up to the new API 26 min requirement from Google Play. This is related to dependencies though, and might not affect yours
In Android Studio open:
File > Project Structure
and check if JDK location points to your JDK 1.8 directory.
Note: you can use compileSdkVersion 24
.
It works trust me. For this to work first download latest JDK from Oracle.
Some sites are detecting this:
function d() {
try {
if (window.document.$cdc_asdjflasutopfhvcZLmcfl_.cache_)
return !0
} catch (e) {}
try {
//if (window.document.documentElement.getAttribute(decodeURIComponent("%77%65%62%64%72%69%76%65%72")))
if (window.document.documentElement.getAttribute("webdriver"))
return !0
} catch (e) {}
try {
//if (decodeURIComponent("%5F%53%65%6C%65%6E%69%75%6D%5F%49%44%45%5F%52%65%63%6F%72%64%65%72") in window)
if ("_Selenium_IDE_Recorder" in window)
return !0
} catch (e) {}
try {
//if (decodeURIComponent("%5F%5F%77%65%62%64%72%69%76%65%72%5F%73%63%72%69%70%74%5F%66%6E") in document)
if ("__webdriver_script_fn" in document)
return !0
} catch (e) {}
It's been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.
Now we can write this:
useEffect(() => {
const listener = event => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
console.log("Enter key was pressed. Run your function.");
// callMyFunction();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
This registers a listener on the keydown
event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.
Use project root in terminal like this:-/Users/rajnish/Desktop/RankProjects/ProjectCloud
After that enter this command ./gradlew clean
It will work.
To build on the previous answer if you add -f
you can tail the logs.
kubectl logs -f deployment/app
First composer requires doctrine/dbal
, then:
$table->longText('column_name')->change();
The example in your question is that of a curried function
which makes use of arrow function
and has an implicit return
for the first argument.
Arrow function lexically bind this i.e they do not have their own this
argument but take the this
value from the enclosing scope
An equivalent of the above code would be
const handleChange = (field) {
return function(e) {
e.preventDefault();
/// Do something here
}.bind(this);
}.bind(this);
One more thing to note about your example is that define handleChange
as a const or a function. Probably you are using it as part of a class method and it uses a class fields syntax
so instead of binding the outer function directly, you would bind it in the class constructor
class Something{
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(field) {
return function(e) {
e.preventDefault();
// do something
}
}
}
Another thing to note in the example is the difference between implicit and explicit return.
const abc = (field) => field * 2;
Above is an example of implicit return ie. it takes the value field as argument and returns the result field*2
which explicitly specifying the function to return
For an explicit return you would explicitly tell the method to return the value
const abc = () => { return field*2; }
Another thing to note about arrow functions is that they do not have their own arguments
but inherit that from the parents scope as well.
For example if you just define an arrow function like
const handleChange = () => {
console.log(arguments) // would give an error on running since arguments in undefined
}
As an alternative arrow functions provide the rest parameters that you can use
const handleChange = (...args) => {
console.log(args);
}
Are you running Android M? If so, this is because it's not enough to declare permissions in the manifest. For some permissions, you have to explicitly ask user in the runtime: http://developer.android.com/training/permissions/requesting.html
Laravel 5.8
use the csrf in the ajax url(separate js file)
$.ajax({
url: "/addCart" + "?_token=" + productCSRF,
type: "POST",
..
})
You just rebuilt your project
compile fileTree(dir: 'libs', include: ['*.jar'])
If none of these answers for you, try clearing the Android Studio cache/restart. That was the only thing that worked for me:
From the file menu option, I selected "invalidate caches/restart".
https://teamtreehouse.com/community/gradle-project-sync-failed-7
First you need to download the latest support repository (17 by the time I write this) from internal SDK manager of Android Studio or from the stand alone SDK manager. Then you can add compile 'com.android.support:appcompat-v7:23.0.0'
or any other support library you want to your build.gradle file. (Don't forget the last .0
)
If your data changes a lot, you can use
mAdapter.notifyItemRangeChanged(0, yourData.size());
or some single items in your data set changes, your can use
mAdapter.notifyItemChanged(pos);
For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged()
.
In my case the route in my router was:
Route::post('/new-order', 'Api\OrderController@initiateOrder')->name('newOrder');
and from the client app I was posting the request to:
https://my-domain/api/new-order/
So, because of the trailing slash I got a 405. Hope it helps someone
Below Different tools for Editing Rdlc report:
If nothing mentioned in the above comments is working for you. It might mean the problem lies somewhere else.
One place I found the solution was in the way I was setting the list to the adapter. In my activity the list was a instance variable and I was changing it directly when any data changed. Due to it being a reference variable there was something weird going on. So I changed the reference variable to a local one and used another variable to update data and then pass to addAll()
function mentioned in above answers.
Responded to a similar question with a potentially simple solution to this if anyone is still after an answer, the catch is it involves the use of redux-sagas:
https://stackoverflow.com/a/38701184/978306
Or just skip straight to the article I wrote on the topic:
import withRouter
import { withRouter } from 'react-router-dom';
Export your component as:
export withRouter(nameofcomponent)
Example, on button click, call goBack
:
<button onClick={this.props.history.goBack}>Back</button>
Tested on react-router-dom
v4.3
I noticed downgrading Gradle build tools to 1.2.3 solved my problem of the Crunching PNG error, but on 1.5.0 the problem continues.
I encountered a rare edge case in cygwin, where I would get this error when doing exec('rsync');
somewhere before the query. Might be a general PHP problem, but I could only reproduce this in cygwin with rsync.
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mysql', 'root');
var_dump($pdo->query('SELECT * FROM db'));
exec('rsync');
var_dump($pdo->query('SELECT * FROM db'));
produces
object(PDOStatement)#2 (1) {
["queryString"]=>
string(16) "SELECT * FROM db"
}
PHP Warning: Error while sending QUERY packet. PID=15036 in test.php on line 5
bool(false)
Bug reported in https://cygwin.com/ml/cygwin/2017-05/msg00272.html
When calling a function that is declared with throws
in Swift, you must annotate the function call site with try
or try!
. For example, given a throwing function:
func willOnlyThrowIfTrue(value: Bool) throws {
if value { throw someError }
}
this function can be called like:
func foo(value: Bool) throws {
try willOnlyThrowIfTrue(value)
}
Here we annotate the call with try
, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws
, because this function could throw an exception (i.e., when willOnlyThrowIfTrue()
throws, then foo
will automatically rethrow the exception upwards.
If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!
.
func bar() {
try! willOnlyThrowIfTrue(false)
}
This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.
try!
is enforced at runtime: if you use try!
and the function does end up throwing, then your program's execution will be terminated with a runtime error.
Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()
), or sometimes via defer
ed code.
func baz(value: Bool) throws {
var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
var data = NSData(contentsOfFile:filePath)
try willOnlyThrowIfTrue(value)
// data and filePath automatically cleaned up, even when an exception occurs.
}
If for whatever reason you have clean up code that needs to run but isn't in a deinit()
function, you can use defer
.
func qux(value: Bool) throws {
defer {
print("this code runs when the function exits, even when it exits by an exception")
}
try willOnlyThrowIfTrue(value)
}
Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit()
or defer
. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.
Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.
Handling exceptions is done via catch
statements.
func quux(value: Bool) {
do {
try willOnlyThrowIfTrue(value)
} catch {
// handle error
}
}
You can have multiple catch statements, each catching a different kind of exception.
do {
try someFunctionThatThowsDifferentExceptions()
} catch MyErrorType.errorA {
// handle errorA
} catch MyErrorType.errorB {
// handle errorB
} catch {
// handle other errors
}
For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.
For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).
I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
This the method used to get the filepath
public static String getFilePath(Context context, Uri uri) {
Cursor cursor = null;
final String[] projection = {
MediaStore.MediaColumns.DISPLAY_NAME
};
try {
cursor = context.getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
Add this to the module build.gradle:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
I faced the same problem, even if I was working on my home wifi connection, without any proxy requirements.
My project was created at c:\users\<>\Workspace\Project\
When I went to above location and ran
mvn clean install
I got below error:
[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its de
endencies could not be resolved: Failed to read artifact descriptor for org.apa
he.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.ap
che.maven.plugins:maven-clean-plugin:pom:2.5 from/to central (https://repo.mave
.apache.org/maven2)
It took me entire day to try ways and means to crack this, but the solution in my case, was damn simple.
I moved my project to non-user specific location, at E:\Workspace\Project\
This has done wonders for me!
In my case, the problem occurred when writing in Kotlin and using IDEA 2020.3. Despite proper entries in build.gradle.kts. It turned out that the problem was when generating test functions by IDEA IDE (Alt + Insert). It generates the following code:
@Test
internal fun name () {
TODO ("Not yet implemented")
}
And the problem will be fixed after removing the "internal" modifier:
@Test
fun name () {
TODO ("Not yet implemented")
}
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
This should be
compile("org.springframework.boot:spring-boot-starter-tomcat")
I faced the same problem here's the solution:(Explained)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/form").hasRole("ADMIN") // Specific api method request based on role.
.antMatchers("/home","/basic").permitAll() // permited urls to guest users(without login).
.anyRequest().authenticated()
.and()
.formLogin() // not specified form page to use default login page of spring security.
.permitAll()
.and()
.logout().deleteCookies("JSESSIONID") // delete memory of browser after logout.
.and()
.rememberMe().key("uniqueAndSecret"); // remember me check box enabled.
http.csrf().disable(); **// ADD THIS CODE TO DISABLE CSRF IN PROJECT.**
}
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Login APi Put Two Parameters
{
"UserId": "1234",
"Password":"1234"
}
Login Response
{
"UserId": "1234",
"FirstName": "Keshav",
"LastName": "Gera",
"ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {
public static final String BASE_URL = "Your Base Url ";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface interface
interface APIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
Login Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("UserId")
public String UserId;
@SerializedName("FirstName")
public String FirstName;
@SerializedName("LastName")
public String LastName;
@SerializedName("ProfilePicture")
public String ProfilePicture;
@SerializedName("Password")
public String Password;
@SerializedName("ResponseCode")
public String ResponseCode;
@SerializedName("ResponseMessage")
public String ResponseMessage;
public LoginResponse(String UserId, String Password) {
this.UserId = UserId;
this.Password = Password;
}
public String getUserId() {
return UserId;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getProfilePicture() {
return ProfilePicture;
}
public String getResponseCode() {
return ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
public class MainActivity extends AppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
private void loginRetrofit2Api(String userId, String password) {
final LoginResponse login = new LoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
String responseCode = loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
public boolean checkValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
return false;
} else if (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
return false;
}
return true;
}
}
CommonMethod.java
public class CommonMethod {
public static final String DISPLAY_MESSAGE_ACTION =
"com.codecube.broking.gcm";
public static final String EXTRA_MESSAGE = "message";
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connectivityManager
= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLogin"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:padding="5dp"
android:background="@mipmap/ic_launcher_round"
/>
<TextView
android:id="@+id/txtLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgLogin"
android:layout_centerHorizontal="true"
android:text="Holostik Track and Trace"
android:textSize="20dp"
android:visibility="gone" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:layout_marginTop="8dp"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:fontFamily="sans-serif"
android:gravity="top"
android:hint="Login ID"
android:maxLines="10"
android:paddingLeft="@dimen/edit_input_padding"
android:paddingRight="@dimen/edit_input_padding"
android:paddingTop="@dimen/edit_input_padding"
android:singleLine="true"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout1"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rel12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
>
<Button
android:id="@+id/loginSub"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/border_button"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginRight="10dp"
android:text="Login"
android:textColor="#ffffff" />
</RelativeLayout>
</LinearLayout>
It was reproducible only when I use proxy on genymotion(<4.4).
Check your proxy settings in Settings-> Wireless & Networks-> WiFi->(Long Press WiredSSID)-> Modify Network
Select show advanced options: set Proxy settings to NONE.
Essentially Matt Daley/Johnny Mohseni's solution worked for me.
I faced exactly the same problem on a fresh Android Studio V 1.2.1.1 installation. I created a new project (blank activity) and straightaway god this build error.
Error:Execution failed for task ':app:compileDebugAidl'.
> aidl is missing
As suggested, changing the gradle dependency from 1.2.3 to 1.3.0-beta1 fixed it.
classpath 'com.android.tools.build:gradle:1.3.0-beta1' // <--- WORKS!
//classpath 'com.android.tools.build:gradle:1.2.3' // <--- default - failed
Once 1.3.0-beta1 change was saved, I got a prompt to upgrade dependencies. Upon accepting the request to upgrade, the gradle build status bar at the bottom tracked the packages being synced. When that completed, the build was automatically triggered and completed successfully.
Possible problem: You have exceeded dex 65k methods limit, may be you added some library or several methods before problem occurred?
This is worked for me, Hope to help someone (Using my own button not FB login button )
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_sign_in_user);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.i("RESAULTS : ", object.getString("email"));
}catch (Exception e){
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
Log.i("RESAULTS : ", error.getMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void signupwith_facebook(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}
You are converting cert into BKS Keystore, why aren't you using .cert
directly, from https://developer.android.com/training/articles/security-ssl.html:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
ca = cf.generateCertificate(instream);
} finally {
caInput.close();
}
KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(context.getSocketFactory());
i had the same problem i resolve it by removing files that i added in the assets folder and those files name contains insupported characteres like "é" , " ", "ï" "è"... by renaming those name files or removing them you will have no problem.
the output is from NonFinalPluginExpiry.java
example 2.4.0-alpha7
either need to:
make a automation script to generate env var and set it daily
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(String.format(
"%1$s:%2$s:%3$s",
now.getYear(),
now.getMonthValue() -1,
now.getDayOfMonth())
.getBytes("utf8"));
String overrideValue = new BigInteger(1, crypt.digest()).toString(16);
EXAMPLE APP IN JAVA (sources + JAR):
https://github.com/c3ph3us/ado
https://github.com/c3ph3us/ado/releases
example bash function to export env and start idea / or studio:
// eval export & start idea :)
function sti() {
export `java -jar AndroidDailyOverride.jar p`
idea.sh
}
For me this works:
defaultConfig {
multiDexEnabled true
}
Today I also met this problem. Here is how I solved it:
xxx.9.png
. xxx9.png
and rebuilt. There were no errors, and the java files with the red wave under the name are gone too.@Inherently Curious - thanks for posting this. You are almost there - you have to add two more params to SSLContext.init() method.
TrustManager[] trustManagers = new TrustManager[] { new TrustManagerManipulator() };
sc.init(null, trustManagers, new SecureRandom());
it will start working. Again thank you very much for posting this. I solved this/my issue with your code.
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
I had the same problem error that is shown, i solve it by adding
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
I had this problem cause i exceeded the 65K methods dex limit imposed by Android i used so many libraries
Apart from the accepted answer, other problems can cause the exception too. For me it was that the certificate was not trusted (i.e., self-signed cert and not in the trust store).
If the certificate file does not exists, or could not be loaded (e.g., typo in path) can---in certain circumstances---cause the same exception.
System.ArgumentNullException: Value cannot be null. Parameter name: value
This error message is not very helpful!
You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.
As a generic way to solve this, look at the stack trace or call stack:
Test method GetApiModel threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: value
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
You can see that the parameter name value
is the first parameter for DeserializeObject
. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.
You can change the code to check for null.
For me follwing steps helped.
It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:
File ? Settings ? Experimental ? Gradle ? Only sync the active variant
Try this;
function X (id,parameter1,parameter2,...) {
$.ajax({
url: '@Url.Action("Actionre", "controller")',+ id,
type: "Get",
data: { parameter1: parameter1, parameter2: parameter2,...}
}).done(function(result) {
your code...
});
}
So controller method would looks like :
public ActionResult ActionName(id,parameter1, parameter2,...)
{
Your Code .......
}
I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.
1.Class
@WebServlet("/display")
public class MyFirst extends HttpServlet {
2.Class
@WebServlet("/display")
public class MySecond extends HttpServlet {
From the looks of things you haven't passed enough data to Spring Boot to configure the datasource
Create/In your existing application.properties
add the following
spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
making sure you append a value for each of properties.
Try To Give Full path for reading image.
Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));
your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java
If the object of your class is created at end your code works fine for me and displays the image
// PracticeFrame pframe = new PracticeFrame();//comment this
new PracticeFrame().add(panel);
The word check_
in the name means that if the command (the shell in this case that returns the exit status of the last command (yum
in this case)) returns non-zero status then it raises CalledProcessError
exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_
methods. You could use subprocess.call
in your case because you are ignoring the captured output, e.g.:
import subprocess
rc = subprocess.call(['grep', 'pattern', 'file'],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
...
elif rc == 1: # not found
...
elif rc > 1: # error
...
You don't need shell=True
to run the commands from your question.
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
OSError: [Errno 8] Exec format error
can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:
>>> with open('a','w') as f: f.write('exit 0') # create the script
...
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable
>>> os.execl('./a', './a') # execute it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/os.py", line 312, in execl
execv(file, args)
OSError: [Errno 8] Exec format error
To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh
at the top of your script:
>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
...
>>> os.execl('./a', './a')
It executes exit 0
without any errors.
On POSIX systems, shell parses the command line i.e., your script won't see spaces around =
e.g., if script
is:
#!/usr/bin/env python
import sys
print(sys.argv)
then running it in the shell:
$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST
produces:
['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
Note: no spaces around '='
. I've added quotes around <hostname>
to escape the redirection metacharacters <>
.
To emulate the shell command in Python, run:
from subprocess import check_call
cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)
Note: no shell=True
. And you don't need to escape <>
because no shell is run.
"Exec format error"
might indicate that your script
has invalid format, run:
$ file /usr/local/bin/script
to find out what it is. Compare the architecture with the output of:
$ uname -m
I had a similar issue, when I upgraded to the latest version of Android Studio 1.3.2. What seemed to work for me was removing the .gradle
folder from my project directory:
rm -rf ~/project/.gradle
The left inset is caused by Toolbar's contentInsetStart
which by default is 16dp.
Change this to align to the keyline.
Update for support library v24.0.0:
To match the Material Design spec there's an additional attribute contentInsetStartWithNavigation
which by default is 16dp. Change this if you also have a navigation icon.
It turned out that this is part of a new Material Design Specification introduced in version 24 of Design library.
https://material.google.com/patterns/navigation.html
However, it is possible to remove the extra space by adding the following property to Toolbar widget.
app:contentInsetStartWithNavigation="0dp"
The issue is fixed by adding repository url under distributionManagement tab in main pom.xml.
Jenkin maven goal : clean deploy -U -Dmaven.test.skip=true
<distributionManagement>
<repository>
<id>releases</id>
<url>http://domain:port/content/repositories/releases</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<url>http://domain:port/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
use ondragstart(event)
instead of ondrag(event)
runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.
To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.
I think the most correct way to get item position is
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override public void onClick(View v) {
View view = v;
View parent = (View) v.getParent();
while (!(parent instanceof RecyclerView)){
view=parent;
parent = (View) parent.getParent();
}
int position = recyclerView.getChildAdapterPosition(view);
}
Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);
Based on the work of Denis Nek, it works well if the sum of item's widths is smaller than the size of the container. other than that, it will make the recyclerview non scrollable and only will show subset of the data.
to solve this problem, i modified the solution alittle so that it choose the min of the provided size and calculated size. see below:
package com.linkdev.gafi.adapters;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.linkdev.gafi.R;
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.c = context;
}
private Context c;
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
int widthDesired = Math.min(widthSize,width);
setMeasuredDimension(widthDesired, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}}
Calling preventDefault
on touchmove
while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault()
from touchstart
and everything should be ok.
There is a problem with setting the tint color on the view after presenting; even if you do it in the completion block of presentViewController:animated:completion:, it causes a flicker effect on the color of the button titles. This is sloppy, unprofessional and completely unacceptable.
Other solutions presented depend on the view hierarchy remaining static, something that Apple is loathe to do. Expect those solutions to fail in future releases of iOS.
The one sure-fire way to solve this problem and to do it everywhere, is via adding a category to UIAlertController and swizzling the viewWillAppear.
The header:
//
// UIAlertController+iOS9TintFix.h
//
// Created by Flor, Daniel J on 11/2/15.
//
#import <UIKit/UIKit.h>
@interface UIAlertController (iOS9TintFix)
+ (void)tintFix;
- (void)swizzledViewWillAppear:(BOOL)animated;
@end
The implementation:
//
// UIAlertController+iOS9TintFix.m
//
// Created by Flor, Daniel J on 11/2/15.
//
#import "UIAlertController+iOS9TintFix.h"
#import <objc/runtime.h>
@implementation UIAlertController (iOS9TintFix)
+ (void)tintFix {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method method = class_getInstanceMethod(self, @selector(viewWillAppear:));
Method swizzle = class_getInstanceMethod(self, @selector(swizzledViewWillAppear:));
method_exchangeImplementations(method, swizzle);});
}
- (void)swizzledViewWillAppear:(BOOL)animated {
[self swizzledViewWillAppear:animated];
for (UIView *view in self.view.subviews) {
if (view.tintColor == self.view.tintColor) {
//only do those that match the main view, so we don't strip the red-tint from destructive buttons.
self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
[view setNeedsDisplay];
}
}
}
@end
Add a .pch (precompiled header) to your project and include the category:
#import "UIAlertController+iOS9TintFix.h"
Make sure you register your pch in the project properly, and it will include the category methods in every class that uses the UIAlertController.
Then, in your app delegates didFinishLaunchingWithOptions method, import your category and call
[UIAlertController tintFix];
and it will automatically propagate to every single instance of UIAlertController within your app, whether launched by your code or anyone else's.
This solution works for both iOS 8.X and iOS 9.X and lacks the flicker of the tint change post-presentation approach. It is also completely agnostic with respect to the view hierarchy of the sub-views of the UIAlertController.
Happy hacking!
Insted of
drawer.setDrawerListener(toggle);
You can use
drawer.addDrawerListener(toggle);
You'll want to add a Symbolic Breakpoint
. Apple provides an excellent guide on how to do this.
cmd+7
(cmd+8
in Xcode 9)Add
button in the lower leftAdd Symbolic Breakpoint...
Symbol
just type in UIViewAlertForUnsatisfiableConstraints
You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.
You did every thing correct, I have been gone through same problem.
First delete you db and migrations
I solved my adding name of my app in makemigrations
:
python manage.py makemigrations appname
python manage.py migrate
This will definitely work.
The error is caused by constrains automatically created from autoresizing mask, they are created because UIView property translatesAutoresizingMaskIntoConstraints is true by default.
Consider using BoxView to get rid of all manual constraint creation boilerplate, and make your code concize and readable. To make layout in question with BoxView is very easy:
boxView.items = [
new_view.boxed.centerX().centerY().relativeWidth(1.0).relativeHeight(1.0)
]
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:
export DJANGO_SETTINGS_MODULE=mysite.settings
Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name>
In my specific case I ran these two and everything worked out:
export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal
Edit
I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings
to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
$(document).ready(function () {
$('#allot').click(function () {
if ($(this).is(':checked')) {
alert("Allot Thai Gayo Bhai");
}
});
$('#transfer').click(function () {
if ($(this).is(':checked')) {
alert("Transfer Thai Gayo");
}
});
});
Remove any capital letters or other not allowed symbols in resource file name.
Example: activity_parkingList --> activity_parking_list
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
let's demonstrate in Code Implementation
def duplication given_array
seen_objects = []
duplication_objects = []
given_array.each do |element|
duplication_objects << element if seen_objects.include?(element)
seen_objects << element
end
duplication_objects
end
Now call duplication method and output return result -
dup_elements = duplication [1,2,3,4,4,5,6,6]
puts dup_elements.inspect
Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.
my_form_post
).request.form
.templates/my-form.html
:
<form method="POST">
<input name="text">
<input type="submit">
</form>
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('my-form.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
return processed_text
This is the Flask documentation about accessing request data.
If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.
Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).
Assuming you do not have permissions set from your LogCat
error description, here is my contents for my AndroidManifest.xml
file that has access to the internet:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
Other than that, you should be fine to download a file from the internet.
There is another way to accomplish that (described in more details in Stephen Walther's Pager example
Essentially, you create a link in the view:
Html.ActionLink("Next page", "Index", routeData)
In routeData you can specify name/value pairs (e.g., routeData["page"] = 5), and in the controller Index function corresponding parameters receive the value. That is,
public ViewResult Index(int? page)
will have page passed as 5. I have to admit, it's quite unusual that string ("page") automagically becomes a variable - but that's how MVC works in other languages as well...
When the browser sends p
in the querystring, it is received as a string, not an int. is_int()
will therefore always return false.
Instead try is_numeric()
or ctype_digit()
You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:
select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;
which will return "12345569".
also you can use this one:
select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual
which will return "12345569" for numbers and "StackOverFlow" for characters.
Maybe you could make the field readonly and on submit disable all readonly fields
$(".myform").submit(function(e) {
$("input[readonly]").prop("disabled", true);
});
and the input (+ script) should be
<input type="text" readonly="readonly" name="test" value="test" />
$('input[readonly]').click(function () {
$(this).removeAttr('readonly');
});
$(".myform").submit(function(e) {
$("input[readonly]").prop("disabled", true);
e.preventDefault();
});
$('.reset').click(function () {
$("input[readonly]").prop("disabled", false);
})
$('input[readonly]').click(function () {
$(this).removeAttr('readonly');
})
_x000D_
input[readonly] {
color: gray;
border-color: currentColor;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myform">
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<button>Submit</button>
<button class="reset" type="button">Reset</button>
</form>
_x000D_
You can do it the OO way, just an alternative and flexible:
class Logger {
private
$file,
$timestamp;
public function __construct($filename) {
$this->file = $filename;
}
public function setTimestamp($format) {
$this->timestamp = date($format)." » ";
}
public function putLog($insert) {
if (isset($this->timestamp)) {
file_put_contents($this->file, $this->timestamp.$insert."<br>", FILE_APPEND);
} else {
trigger_error("Timestamp not set", E_USER_ERROR);
}
}
public function getLog() {
$content = @file_get_contents($this->file);
return $content;
}
}
Then use it like this .. let's say you have user_name
stored in a session (semi pseudo code):
$log = new Logger("log.txt");
$log->setTimestamp("D M d 'y h.i A");
if (user logs in) {
$log->putLog("Successful Login: ".$_SESSION["user_name"]);
}
if (user logs out) {
$log->putLog("Logout: ".$_SESSION["user_name"]);
}
Check your log with this:
$log->getLog();
Result is like:
Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe
Like @Ardee said you sharer.php uses data from the meta tags, the Dialog API accepts parameters. Facebook have removed the ability to use the message parameter but you can use the quote parameter which can be useful in a lot of cases e.g.
https://www.facebook.com/dialog/share?
app_id=[your-app-id]
&display=popup
&title=This+is+the+title+parameter
&description=This+is+the+description+parameter
"e=This+is+the+quote+parameter
&caption=This+is+the+caption+parameter
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fwww.[url-in-your-accepted-list].com
Just have to create an app id:
https://developers.facebook.com/docs/apps/register
Then make sure the redirect url domain is listed in the accepted domains for that app.
You mention that you are doing this because IE doesn't support SVG.
The good news is that IE does support vector graphics. Okay, so it's in the form of a language called VML which only IE supports, rather than SVG, but it is there, and you can use it.
Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.
Then there's the Raphael library, which is a Javascript browswer-based graphics library, which supports either SVG or VML, again depending on the browser.
Another one which may help: SVGWeb.
All of which means that you can support your IE users without having to resort to bitmap graphics.
See also the top answer to this question, for example: XSL Transform SVG to VML
Use the Application Verifier (AppVerifier) tool from Microsoft.
In my case I need to simulate memory no longer being available so I did the following in the tool:
After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.
Use .text()
instead, and change your selector:
$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');
try{
let vari = obj.propTest; // obj may be don't have propTest property
...
} catch(NullException){
// do something here
}
I think using try catch will avoid any error of null check, also in Angular or JavaScript Just catching null exception and process in it.
while @vitocorleone is technically correct. If you have already installed, there is no need to reinstall. You just need to add it to your path. You will find yourself doing this for many of the tools for the mean stack so you should get used to doing it. You don't want to have to be in the folder that holds the executable to run it.
at the end of the line type (assuming this is where you installed it)
;C:\Program Files (x86)\git\cmd
click ok, ok, and ok to save
This essentially tells the OS.. if you don't find this executable in the folder I am typing in, look in Path to fide where it is.
There is good explanation for linux users how to update node version step by step.
P.S type instead of sudo n stable
sudo n latest
for receive latest node version.
If you receive following error
Error: Module version mismatch. Expected 48, got 46.
You have just rebuilt npm by the following command npm rebuild
it should fix the problem.
I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".
but how I resolved is By using Math.round()
eg:
if ($(this).attr('name') == 'time') {
var value = parseFloat($(this).val());
value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
alert(value);
}
this thing surely works for me and it might help you guys too...
echo "[email protected];[email protected]" | sed -e 's/;/\n/g'
[email protected]
[email protected]
The answer is a simple PowerShell
one-liner:
Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
If you only want to pull the UNC
for one particular drive, add a where statement:
Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:' | ft "RemoteName","LocalName" -A
BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or String filteredString=inString.replaceAll(",","")
.
You then simply call BigDecimal myBigD=new BigDecimal(filteredString);
You can also create a NumberFormat
and call setParseBigDecimal(true)
. Then parse(
will give you a BigDecimal without worrying about manually formatting.
I think you should re-format your code a bit:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
mkdir -p /home/mlzboy/b2c2/shared/db;
fi;
You can use this website to obtain a channelId
https://commentpicker.com/youtube-channel-id.php
I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: inactive (dead) TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
On a system where "docker ps" had been run with no other Docker commands, I got the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago
TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
Main PID: 3135 (dockerd)
Tasks: 13
Memory: 116.9M
CGroup: /system.slice/docker.service
+-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
... [various messages not shown ]
The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:
[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run. This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps
[Install]
WantedBy=multi-user.target
So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).
I use addActionListener
for JButtons while addItemListener
is more convenient for a JToggleButton
. Together with if(event.getStateChange()==ItemEvent.SELECTED)
, in the latter case, I add Events for whenever the JToggleButton is checked/unchecked.
A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)
HTML
<menu id="ctxMenu">
<menu title="File">
<menu title="Save"></menu>
<menu title="Save As"></menu>
<menu title="Open"></menu>
</menu>
<menu title="Edit">
<menu title="Cut"></menu>
<menu title="Copy"></menu>
<menu title="Paste"></menu>
</menu>
</menu>
Note: the menu tag does not exist, I'm making it up (you can use anything)
CSS
#ctxMenu{
display:none;
z-index:100;
}
menu {
position:absolute;
display:block;
left:0px;
top:0px;
height:20px;
width:20px;
padding:0;
margin:0;
border:1px solid;
background-color:white;
font-weight:normal;
white-space:nowrap;
}
menu:hover{
background-color:#eef;
font-weight:bold;
}
menu:hover > menu{
display:block;
}
menu > menu{
display:none;
position:relative;
top:-20px;
left:100%;
width:55px;
}
menu[title]:before{
content:attr(title);
}
menu:not([title]):before{
content:"\2630";
}
The JavaScript is just for this example, I personally remove it for persistent menus on windows
var notepad = document.getElementById("notepad");
notepad.addEventListener("contextmenu",function(event){
event.preventDefault();
var ctxMenu = document.getElementById("ctxMenu");
ctxMenu.style.display = "block";
ctxMenu.style.left = (event.pageX - 10)+"px";
ctxMenu.style.top = (event.pageY - 10)+"px";
},false);
notepad.addEventListener("click",function(event){
var ctxMenu = document.getElementById("ctxMenu");
ctxMenu.style.display = "";
ctxMenu.style.left = "";
ctxMenu.style.top = "";
},false);
Also note, you can potentially modify menu > menu{left:100%;}
to menu > menu{right:100%;}
for a menu that expands from right to left. You would need to add a margin or something somewhere though
if (position ==0) {
if (rYes.isChecked()) {
Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
} else if (rNo.isChecked()) {
Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
}
}
This code is supposed to select both check boxes.
Is there a problem with it?
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
@Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")
Here Value is that object of model where you want to save your Selected Value
It depends on how you access the data:
Go for Option 1:
Go for Option 2:
P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.
The correct version of hythlodayr's answer.
-- ERROR: operator does not exist: double precision % integer
-- LINE 1: select (trunc(random() * 10) % 10) + 1
The output from trunc
has to be converted to INTEGER
. But it can be done without trunc
. So it turns out to be simple.
select (random() * 9)::INTEGER + 1
Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.
For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER
.
You cannot have ref
or out
parameters in async
methods (as was already noted).
This screams for some modelling in the data moving around:
public class Data
{
public int Op {get; set;}
public int Result {get; set;}
}
public async void Method1()
{
Data data = await GetDataTaskAsync();
// use data.Op and data.Result from here on
}
public async Task<Data> GetDataTaskAsync()
{
var returnValue = new Data();
// Fill up returnValue
return returnValue;
}
You gain the ability to reuse your code more easily, plus it's way more readable than variables or tuples.
I have created a demo for you.
Here is how your nested structure should be in Bootstrap 3:
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</div>
</div>
Notice how the whole form-inline
is nested within the col-xs-10
div containing the control of the horizontal form. In other terms, the whole form-inline
is the "control" of the birthday label in the main horizontal form.
Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:
.form-inline .form-group{
margin-left: 0;
margin-right: 0;
}
Limitation
Android PCAP should work so long as:
Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API
Limitation
Phone should be rooted
Limitation
Phone should be rooted
Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.
https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en
Advantages
Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.
http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot
If you are talking about the length of the string, you can use len()
:
>>> s = 'please answer my question'
>>> len(s) # number of characters in s
25
If you need the size of the string in bytes, you need sys.getsizeof()
:
>>> import sys
>>> sys.getsizeof(s)
58
Also, don't call your string variable str
. It shadows the built-in str()
function.
UIWebview
s can also load the .pdf
using loadData
method, if you acquire it as NSData
:
[self.webView loadData:self.pdfData
MIMEType:@"application/pdf"
textEncodingName:@"UTF-8"
baseURL:nil];
On the basic question of why openssl is not found: Short answer:Some installation packages for openssl have a default openssl.cnf pre-included. Other packages do not. In the latter case you will include one from the link shown below; You can enter additional user-specifics --DN name,etc-- as needed.
From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:
"OPENSSL LIBRARY CONFIGURATION
Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.
To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.
The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"
So it appears one must self configure openssl.cnf according to your Distinguished Name (DN), along with other entries specific to your use.
Here is the template file from which you can generate openssl.cnf with your specific entries.
One Application actually has a demo installation that includes a demo .cnf file.
Additionally, if you need to programmatically access .cnf files, you can include appropriate headers --openssl/conf.h-- and parse your .cnf files using
CONF_modules_load_file(const char *filename, const char *appname,
unsigned long flags);
Here are docs for "CONF_modules_load_file";
From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.
For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]
From server A, create a session to server B:
$b = New-PSSession B
And then, still from A:
Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt
Copying items to B is done with -ToSession
. Note that local paths are used in both cases; you have to keep track of what server you're on.
[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession
, an apparently copying doesn't work at all with -FromSession
.
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.
An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.
<div style="width:100%">
<!-- This div will be the full width of the browser, whatever size it is -->
<div style="width:300px">
<!-- this div will be 300px, whatever size the browser is -->
<p style="width:50%">
This paragraph's width will be 50% of it's parent (150px).
</p>
</div>
</div>
Another relative measurement is ems which are relative to font size.
An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.
If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().
But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).
The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.
It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.
At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)
Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.
http://caniuse.com/#search=::after
::after
and ::before
with content
are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.
Is this what you're looking for?
.Modal::after{
content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
position:relative; /*or absolute*/
z-index:100000; /*a number that's more than the modal box*/
left:-50px;
top:10px;
}
.ModalCarrot{
position:absolute;
left:50%;
margin-left:-8px;
top:-16px;
}
If not, can you explain a little better?
or you could use jQuery, like Joshua said:
$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");
When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.
From the ILSpy website (https://github.com/icsharpcode/ILSpy/):
ILSpy is the open-source .NET assembly browser and decompiler.
Update:
April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:
Update:
Having worked with them in many circumstances, I've really come to think that iframe's are the web programming equivalent of the goto statement. That is, something to be generally avoided. Within a site they can be somewhat useful. However, cross-site, they are almost always a bad idea for anything but the simplest of content.
Consider the possibilities ... if used for parameterized content, they've created an interface. And in a professional site, that interface requires an SLA and version management - which are almost always ignored in rush to get online.
If used for active content - frames that host script - then there are the (different) cross domain script restrictions. Some can be hacked, but rarely consistently. And if your framed content has a need to be interactive, it will struggle to do so beyond the frame.
If used with licensed content, then the participating sites are burdened by the need to move entitlement information out of band between the hosts.
So, although, occaisionally useful within a site, they are rather unsuited to mashups. You're far better looking at real portals and portlets. Worse, they are a darling of every web amateur - many a tech manager has siezed on them as a solution to many problems. In fact, they create more.
os.walk
does recursive walk by default. For each dir, starting from root it yields a 3-tuple (dirpath, dirnames, filenames)
from os import walk
from os.path import splitext, join
def select_files(root, files):
"""
simple logic here to filter out interesting files
.py files in this example
"""
selected_files = []
for file in files:
#do concatenation here to get full path
full_path = join(root, file)
ext = splitext(file)[1]
if ext == ".py":
selected_files.append(full_path)
return selected_files
def build_recursive_dir_tree(path):
"""
path - where to begin folder scan
"""
selected_files = []
for root, dirs, files in walk(path):
selected_files += select_files(root, files)
return selected_files
I'm using this to only enable a button if a listview item is selected (ie not null):
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=lvMyList, Path=SelectedItem}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.
To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
Shelving is a way of saving all of the changes on your box without checking in. The changes are persisted on the server. At any later time you or any of your team-mates can "unshelve" them back onto any one of your machines.
It's also great for review purposes. On my team for a check in we shelve up our changes and send out an email with the change description and name of the changeset. People on the team can then view the changeset and give feedback.
FYI: The best way to review a shelveset is with the following command
tfpt review /shelveset:shelvesetName;userName
tfpt is a part of the Team Foundation Power Tools
I would simply write each line to a file, since it's already in a CSV format:
write_file = "output.csv"
with open(write_file, "w") as output:
for line in text:
output.write(line + '\n')
I can't recall how to write lines with line-breaks at the moment, though :p
Also, you might like to take a look at this answer about write()
, writelines()
, and '\n'
.
Just restart
your AS, then Rebuild
your app!
A possible solutions is to declare a second bean which reads from the same properties file:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/app.properties" />
</bean>
<util:properties id="appProperties" location="classpath:/WEB-INF/app.properties"/>
The bean named 'appProperties' is of type java.util.Properties and can be dependency injected using the @Resource attruibute shown above.
After i tried all methods and they did not work for me.
I get the solution by using another PortDuff.MODE.
imgEstadoBillete.setColorFilter(context.getResources().getColor(R.color.green),PorterDuff.Mode.SRC_IN);
VB sample:
@Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})
Sample Css:
.someClass
{
color: Green !important;
}
In my case, I found that I need the !important attribute to over ride the site.css a:link css class
Both r+
and w+
can read and write to a file. However, r+
doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereas w+
deletes the content of the file and creates it if it doesn't exist.
You may use trick in unix/linux environment:
in gnuplot program: plot "/dev/stdin" ...
In command line: gnuplot program.plot < data.dat
This code makes a window with the conditions that the user cannot change the dimensions of the Tk()
window, and also disables the maximise button.
import tkinter as tk
root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()
Within the program you can change the window dimensions with @Carpetsmoker's answer, or by doing this:
root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))
It should be fairly easy for you to implement that into your code. :)
Try just clearing the data (not the entire table including headers):
ACell.ListObject.DataBodyRange.ClearContents
According to the documentation you can simply return false;
to break:
$(xml).find("strengths").each(function() {
if (iWantToBreak)
return false;
});
You can use this way:
And in the CSS:
.tooltip-arrow,
.red-tooltip + .tooltip > .tooltip-inner {background-color: #000;}
key
is simply a variable.
For Python2.X:
d = {'x': 1, 'y': 2, 'z': 3}
for my_var in d:
print my_var, 'corresponds to', d[my_var]
... or better,
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.iteritems():
print the_key, 'corresponds to', the_value
For Python3.X:
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.items():
print(the_key, 'corresponds to', the_value)
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
Similar to what is already posted, just using bit-shift and mask to get the bit; usable for any type, being a template (only not sure if there is a standard way to get number of bits in 1 byte, I used 8 here).
#include<iostream>
#include <climits>
template<typename T>
void printBin(const T& t){
size_t nBytes=sizeof(T);
char* rawPtr((char*)(&t));
for(size_t byte=0; byte<nBytes; byte++){
for(size_t bit=0; bit<CHAR_BIT; bit++){
std::cout<<(((rawPtr[byte])>>bit)&1);
}
}
std::cout<<std::endl;
};
int main(void){
for(int i=0; i<50; i++){
std::cout<<i<<": ";
printBin(i);
}
}
I had the same problem, here is my solution:
<form method="post" class="form-inline form-horizontal" role="form">
<label class="control-label col-sm-5" for="jbe"><i class="icon-envelope"></i> Email me things like this: </label>
<div class="input-group col-sm-7">
<input class="form-control" type="email" name="email" placeholder="[email protected]"/>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit">Submit</button>
</span>
</div>
</form>
here is the Demo
Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.
A good python library called noplay can be used. More info here.
This is the code I use:
var ifrm = document.getElementById('myFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();
contentWindow vs. contentDocument
- IE (Win) and Mozilla (1.7) will return the window object inside the iframe with oIFrame.contentWindow.
- Safari (1.2.4) doesn't understand that property, but does have oIframe.contentDocument, which points to the document object inside the iframe.
- To make it even more complicated, Opera 7 uses oIframe.contentDocument, but it points to the window object of the iframe. Because Safari has no way to directly access the window object of an iframe element via standard DOM (or does it?), our fully modern-cross-browser-compatible code will only be able to access the document within the iframe.
Some improved version with max lvl to go down in directory and option to exclude folders:
using System;
using System.IO;
class MainClass {
public static void Main (string[] args) {
var dir = @"C:\directory\to\print";
PrintDirectoryTree(dir, 2, new string[] {"folder3"});
}
public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
{
excludedFolders = excludedFolders ?? new string[0];
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator+Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(directory))
{
Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
{
PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+" ");
}
}
}
}
input directory:
-folder1
file1.txt
-folder2
file2.txt
-folder5
file6.txt
-folder3
file3.txt
-folder4
file4.txt
file5.txt
output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):
-folder1
file1.txt
-folder2
file2.txt
-folder5
-folder3
-folder4
file4.txt
file5.txt
Exported variables such as $HOME
and $PATH
are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.
$ env | grep '^variable='
$ # No environment variable called variable
$ variable=Hello # Create local (non-exported) variable with value
$ env | grep '^variable='
$ # Still no environment variable called variable
$ export variable # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$
For more information, see the entry for the export
builtin in the GNU Bash manual, and also the sections on command execution environment and environment.
Note that non-exported variables will be available to subshells run via ( ... )
and similar notations because those subshells are direct clones of the main shell:
$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$
The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.
Some information about subshells can be found under command grouping and command execution environment in the Bash manual.
var day = value.Date; // a DateTime that will just be whole days
var time = value.TimeOfDay; // a TimeSpan that is the duration into the day
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.
Character Devices
Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).
TTY
/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty
, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty
, your subsequent input gets duplicated (until you press Ctrl-C).
/dev/tty
doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0
is normally your serial port)
This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :
/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).
Here is the man page: http://linux.die.net/man/4/tty
The ifelse
function would be a quick and easy way to do this.
BrenBarn is correct. The error means you tried to do something like None[5]
. In the backtrace, it says self.imageDef=self.values[2]
, which means that your self.values
is None
.
You should go through all the functions that update self.values
and make sure you account for all the corner cases.
Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.
@SuppressWarnings("deprecation")
...
Date hitDate = new Date();
hitDate.setHours(0);
hitDate.setMinutes(0);
hitDate.setSeconds(0);
Using Swift 3 and adopting the fastest hacking-method, you can improve code using extensions:
extension UITableViewCell {
var isSeparatorHidden: Bool {
get {
return self.separatorInset.right != 0
}
set {
if newValue {
self.separatorInset = UIEdgeInsetsMake(0, self.bounds.size.width, 0, 0)
} else {
self.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
}
}
}
Then, when you configure cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
switch indexPath.row {
case 3:
cell.isSeparatorHidden = true
default:
cell.isSeparatorHidden = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if cell.isSeparatorHidden {
// do stuff
}
}
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
string
is a reference type, a class. You can only use Nullable<T>
or the T?
C# syntactic sugar with non-nullable value types such as int
and Guid
.
In particular, as string
is a reference type, an expression of type string
can already be null:
string lookMaNoText = null;
The Bearer
authentication scheme is what you are looking for.
Is it related to bears?
Errr... No :)
According to the Oxford Dictionaries, here's the definition of bearer:
bearer /'b??r?/
noun
A person or thing that carries or holds something.
A person who presents a cheque or other order to pay money.
The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.
And here's the definition of bearer token according to the RFC 6750:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer
authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer
scheme for access tokens in applications that don't use OAuth 2.0.
Stick to the standards as much as you can and don't create your own authentication schemes.
An access token must be sent in the Authorization
request header using the Bearer
authentication scheme:
2.1. Authorization Request Header Field
When sending the access token in the
Authorization
request header field defined by HTTP/1.1, the client uses theBearer
authentication scheme to transmit the access token.For example:
GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer mF_9.B5f-4.1JqM
[...]
Clients SHOULD make authenticated requests with a bearer token using the
Authorization
request header field with theBearer
HTTP authorization scheme. [...]
In case of invalid or missing token, the Bearer
scheme should be included in the WWW-Authenticate
response header:
3. The WWW-Authenticate Response Header Field
If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP
WWW-Authenticate
response header field [...].All challenges defined by this specification MUST use the auth-scheme value
Bearer
. This scheme MUST be followed by one or more auth-param values. [...].For example, in response to a protected resource request without authentication:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="example"
And in response to a protected resource request with an authentication attempt using an expired access token:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="example", error="invalid_token", error_description="The access token expired"
Try this simple solution:
In your activity implement onBackPressed
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStack();
} else {
finish();
}
}
This will work if you want to pop the top fragment on each back press. Note:- While adding fragment to activity always do add the transaction to back stack for this to work
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
From what I have found, your query is mostly correct. Just change "select r" to "select r.Text" is all and that should solve the problem. This is how MSDN documented how it should work.
Ex:
var query = (from r in table1 orderby r.Text select r.Text).distinct();
An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Virtual Library</title>
</head>
<body>
<p>Moved to <a href="http://example.org/">example.org</a>.</p>
</body>
</html>
Please refer to the W3 standards for XML.
You could use the implementation in org.apache.hadoop.hbase.util.Bytes http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html
The source code is here:
Look for the toLong and toBytes methods.
I believe the software license allows you to take parts of the code and use it but please verify that.
Jan 2021: autocomplete="off"
does work as expected now (tested on Chrome 88 macOS).
Sept 2020: autocomplete="chrome-off"
disables Chrome autofill.
Original answer, 2015:
For new Chrome versions you can just put autocomplete="new-password"
in your password field and that's it. I've checked it, works fine.
Got that tip from Chrome developer in this discussion: https://bugs.chromium.org/p/chromium/issues/detail?id=370363#c7
P.S. Note that Chrome will attempt to infer autofill behavior from name, id and any text content it can get surrounding the field including labels and arbitrary text nodes. If there is a autocomplete token like street-address
in context, Chrome will autofill that as such. The heuristic can be quite confusing as it sometimes only trigger if there are additional fields in the form, or not if there are too few fields in the form. Also note that autocomplete="no"
will appear to work but autocomplete="off"
will not for historical reasons. autocomplete="no"
is you telling the browser that this field should be auto completed as a field called "no"
. If you generate unique random autocomplete
names you disable auto complete.
If your users have visited bad forms their autofill information may be corrupt. Having them manually go in and fix their autofill information in Chrome may be a necessary action from them to take.
def word_replace(filename,old,new):
c=0
with open(filename,'r+',encoding ='utf-8') as f:
a=f.read()
b=a.split()
for i in range(0,len(b)):
if b[i]==old:
c=c+1
old=old.center(len(old)+2)
new=new.center(len(new)+2)
d=a.replace(old,new,c)
f.truncate(0)
f.seek(0)
f.write(d)
print('All words have been replaced!!!')
You can use JsonNode
for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");
SQL> select trunc(months_between(sysdate,dob)/12) year,
2 trunc(mod(months_between(sysdate,dob),12)) month,
3 trunc(sysdate-add_months(dob,trunc(months_between(sysdate,dob)/12)*12+trunc(mod(months_between(sysdate,dob),12)))) day
4 from (Select to_date('15122000','DDMMYYYY') dob from dual);
YEAR MONTH DAY
---------- ---------- ----------
9 5 26
SQL>
You can try the following steps and code using qrtools
:
Create a qrcode
file, if not already existing
pyqrcode
for doing this, which can be installed using pip install pyqrcode
And then use the code:
>>> import pyqrcode
>>> qr = pyqrcode.create("HORN O.K. PLEASE.")
>>> qr.png("horn.png", scale=6)
Decode an existing qrcode
file using qrtools
qrtools
using sudo apt-get install python-qrtools
Now use the following code within your python prompt
>>> import qrtools
>>> qr = qrtools.QR()
>>> qr.decode("horn.png")
>>> print qr.data
u'HORN O.K. PLEASE.'
Here is the complete code in a single run:
In [2]: import pyqrcode
In [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")
In [4]: qr.png("horn.png", scale=6)
In [5]: import qrtools
In [6]: qr = qrtools.QR()
In [7]: qr.decode("horn.png")
Out[7]: True
In [8]: print qr.data
HORN O.K. PLEASE.
Caveats
PyPNG
using pip install pypng
for using pyqrcode
In case you have PIL
installed, you might get IOError: decoder zip not available
. In that case, try uninstalling and reinstalling PIL
using:
pip uninstall PIL
pip install PIL
If that doesn't work, try using Pillow
instead
pip uninstall PIL
pip install pillow
To avoid blank line skipping (give readability in conf file) I combine aflat and jeb answer (here) to something like this:
@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %INTEXTFILE%"') do (
SET string=%%A
for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
if "!string!" == "" (
echo.>>%OUTTEXTFILE%
) else (
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
echo !modified! >> %OUTTEXTFILE%
)
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
answer is;
select date_part('year', timestamp '2001-02-16 20:38:40') as year,
date_part('month', timestamp '2001-02-16 20:38:40') as month,
date_part('day', timestamp '2001-02-16 20:38:40') as day,
date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
date_part('minute', timestamp '2001-02-16 20:38:40') as minute
UPDATE 2018: C++20 will come with templated and conceptualized lambdas. The feature has already been integrated into the standard draft.
UPDATE 2014: C++14 has been released this year and now provides Polymorphic lambdas with the same syntax as in this example. Some major compilers already implement it.
At it stands (in C++11), sadly no. Polymorphic lambdas would be excellent in terms of flexibility and power.
The original reason they ended up being monomorphic was because of concepts. Concepts made this code situation difficult:
template <Constraint T>
void foo(T x)
{
auto bar = [](auto x){}; // imaginary syntax
}
In a constrained template you can only call other constrained templates. (Otherwise the constraints couldn't be checked.) Can foo
invoke bar(x)
? What constraints does the lambda have (the parameter for it is just a template, after all)?
Concepts weren't ready to tackle this sort of thing; it'd require more stuff like late_check
(where the concept wasn't checked until invoked) and stuff. Simpler was just to drop it all and stick to monomorphic lambdas.
However, with the removal of concepts from C++0x, polymorphic lambdas become a simple proposition again. However, I can't find any proposals for it. :(
With that code you load the file in memory (as a big string) and then you read that string line by line.
By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
You can also get all fragments like this:
For v4 fragmets
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
For app.fragment
List<Fragment> allFragments = getFragmentManager().getFragments();
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
If you're using Interface builder, try this:
In your xib file:
1) Select the main view, set the background color to black (or whatever color you want the status bar to be
2) Make sure the background is a self contained subview positioned as a top level child of the controller's view.
Move your background to become a direct child of the controller's view. Check the autosizing panel to be sure that you've locked all frame edges, activated both flexibility axes, and if this is a UIImageView, set the content mode to Scale to fill. Programmatically this translates to contentMode set to UIViewContentModeScaleToFill and has its auto resizing mask set to (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight).
3) Now move everything that is locked to the top - down by 20 pts and set a iOS 6/7 delta Y to -20.
All top level children that are locked to the top frame in the autosizing panel need to be moved down by 20pts and have their iOS 6/7 delta Y set to -20. (Cmd select all of those, and click down arrow 20 times - is there a better way anyone?)
4) Adjust the iOS 6/7 delta height of all of the above items that had a flexible height. Any of the items that were locked to the frame top and bottom and had flexible height enabled in the autosizing panel must also have their iOS 6/7 delta height set to 20. That includes the background view mentioned above. This may seem anti-intuitive, but due to the order in which these are applied, it is necessary. The frame height is set first (based on device), then the deltas are applied, and finally the autosizing masks are applied based upon the offset positions of all of the child frames - think it through for a bit, it will make sense.
5) Finally, items that were locked to the bottom frame but not the top frame need no deltas at all.
That will give you the identical status bar in iOS7 and iOS6.
On the other hand, if you want iOS7 styling while maintaining iOS6 compatibility, then set the delta Y / delta height values to 0 for the background view.
To see more iOS7 migration info read the full post: http://uncompiled.blogspot.com/2013/09/legacy-compatible-offsets-in-ios7.html
Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines
.
Pretty Picture:
In matplotlib
it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.
Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy
and a couple of functions from the standard math
library.
The default behaviour of the labelLines
function is to space the labels evenly along the x
axis (automatically placing at the correct y
-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.
In addition, the label_lines
function does not account for the lines which have not had a label assigned in the plot
command (or more accurately if the label contains '_line'
).
Keyword arguments passed to labelLines
or labelLine
are passed on to the text
function call (some keyword arguments are set if the calling code chooses not to specify).
1
and 10
annotations in the top left plot. I'm not even sure this can be avoided.y
position instead sometimes.x
-axis values are float
slabelLines
function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x
range 0.5
-1
then then we couldn't possibly place a label at the desired location (which is a little less than 0.2
). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals
argument; a list of x
-values specified by the user instead of the default linear distribution across the width. So the user can decide which x
-values to use for the label placement of each data series.Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)
label_lines.py:
from math import atan2,degrees
import numpy as np
#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):
ax = line.axes
xdata = line.get_xdata()
ydata = line.get_ydata()
if (x < xdata[0]) or (x > xdata[-1]):
print('x label location is outside data range!')
return
#Find corresponding y co-ordinate and angle of the line
ip = 1
for i in range(len(xdata)):
if x < xdata[i]:
ip = i
break
y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])
if not label:
label = line.get_label()
if align:
#Compute the slope
dx = xdata[ip] - xdata[ip-1]
dy = ydata[ip] - ydata[ip-1]
ang = degrees(atan2(dy,dx))
#Transform to screen co-ordinates
pt = np.array([x,y]).reshape((1,2))
trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]
else:
trans_angle = 0
#Set a bunch of keyword arguments
if 'color' not in kwargs:
kwargs['color'] = line.get_color()
if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
kwargs['ha'] = 'center'
if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
kwargs['va'] = 'center'
if 'backgroundcolor' not in kwargs:
kwargs['backgroundcolor'] = ax.get_facecolor()
if 'clip_on' not in kwargs:
kwargs['clip_on'] = True
if 'zorder' not in kwargs:
kwargs['zorder'] = 2.5
ax.text(x,y,label,rotation=trans_angle,**kwargs)
def labelLines(lines,align=True,xvals=None,**kwargs):
ax = lines[0].axes
labLines = []
labels = []
#Take only the lines which have labels other than the default ones
for line in lines:
label = line.get_label()
if "_line" not in label:
labLines.append(line)
labels.append(label)
if xvals is None:
xmin,xmax = ax.get_xlim()
xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]
for line,x,label in zip(labLines,xvals,labels):
labelLine(line,x,label,align,**kwargs)
Test code to generate the pretty picture above:
from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2
from labellines import *
X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]
plt.subplot(221)
for a in A:
plt.plot(X,np.arctan(a*X),label=str(a))
labelLines(plt.gca().get_lines(),zorder=2.5)
plt.subplot(222)
for a in A:
plt.plot(X,np.sin(a*X),label=str(a))
labelLines(plt.gca().get_lines(),align=False,fontsize=14)
plt.subplot(223)
for a in A:
plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))
xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')
plt.subplot(224)
for a in A:
plt.plot(X,chi2(5).pdf(a*X),label=str(a))
lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)
plt.show()
The difference is in the scope of the variable. The @version is available to all methods of the class instance.
The short answer, if you're in the controller and you need to make the variable available to the view then use @variable
.
For a much longer answer try this: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html
If you only care about html5 browsers you can use error event (since this is only for error handling, it should be ok to only support this on next gen browsers for KISS IMHO).
From the spec:
If the src attribute's value is the empty string or if it could not be resolved, then the user agent must queue a task to fire a simple event named error at the element, and abort these steps.
~
If the load resulted in an error (for example a DNS error, or an HTTP 404 error) Executing the script block must just consist of firing a simple event named error at the element.
This means you don't have to do any error prone polling and can combine it with async and defer attribute to make sure the script is not blocking page rendering:
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.
You can do it manually with the next command:
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
This will remove all *.pyc files and __pycache__ directories recursively in the current directory.
In A1 of your new sheet, put this:
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
This can be copied right too.
Kill the process that is listening to the port in question. I believe netstat shows you process ids.
It is possible to change port in .angular-cli
file. For example:
"defaults": {
"styleExt": "css",
"component": {},
"serve": {
"port": 4205
}
}
In addition, it is necessary to add this to your package.json
:
"ng": "ng",
"start": "ng serve"
Note: textdb is the database which you are going to explore with 'alex' user
root@kalilinux:~# sudo su - postgres
postgres=# psql
postgres=# create database testdb;
postgres=# create user alex with password 'alex';
postgres=# GRANT ALL PRIVILEGES ON DATABASE testdb TO alex;`enter code here`
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
For multicolumn listbox extract data from any column of selected row by
listboxControl.List(listboxControl.ListIndex,col_num)
where col_num is required column ( 0 for first column)
I tried most of methods mentioned above but they didn't work for me, after some searches I found these points:
-n [number]
del
but if there are thousands or millions of keys it's better to use unlink
because unlink is non-blocking while del is blocking, for more information visit this page unlink vs delkeys
are like del and is blockingso I used this code to delete keys by pattern:
redis-cli -n 2 --scan --pattern '[your pattern]' | xargs redis-cli -n 2 unlink
Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.
http://www.jasypt.org/encrypting-configuration.html
By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:
datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost/reportsdb
datasource.username=reportsUser
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).
How do we read this value? like this:
/*
* First, create (or ask some other component for) the adequate encryptor for
* decrypting the values in our .properties file.
*/
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("jasypt"); // could be got from web, env variable...
/*
* Create our EncryptableProperties object and load it the usual way.
*/
Properties props = new EncryptableProperties(encryptor);
props.load(new FileInputStream("/path/to/my/configuration.properties"));
/*
* To get a non-encrypted value, we just get it with getProperty...
*/
String datasourceUsername = props.getProperty("datasource.username");
/*
* ...and to get an encrypted value, we do exactly the same. Decryption will
* be transparently performed behind the scenes.
*/
String datasourcePassword = props.getProperty("datasource.password");
// From now on, datasourcePassword equals "reports_passwd"...
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation
).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
Use .getMinutes()
to get the current minutes, then add 20 and use .setMinutes()
to update the date object.
var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);
/appointments?users=1d1,1d2..
is fine. It's pretty much your only sensible option since you can't pass in a body with a GET.
If you run $ heroku logs
you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs
. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.
I know this is an old question, but still posting this here incase someone else gets stuck.
Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
/*
Adding Method printMe() to this class, outputs son
even though Attribute me from class Dad can apparently not be overridden
*/
public void printMe()
{
System.out.println(me);
}
}
class Tester
{
public static void main(String[] arg)
{
new Son().printMe();
}
}
Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ? To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.
Your code isn't working, because the hidden attibute is not supported in versions of IE before v11
If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:
*[hidden] { display: none; }
public static class GlobalVariables
{
// readonly variable
public static string Foo
{
get
{
return "foo";
}
}
// read-write variable
public static string Bar
{
get
{
return HttpContext.Current.Application["Bar"] as string;
}
set
{
HttpContext.Current.Application["Bar"] = value;
}
}
}
When calling Toast inside android fragment:
1. Activity mActivity=this.getActivity();
2. Toast.makeText(mActivity,"Text you want to display",Toast.LENGTH_SHORT).show();
This works for me.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
if youd dont have adb in folder android-sdk-macosx/platform-tools/
you should install platform tools first. Run android-sdk-macosx/tools/android
and Install platform tools from Android SDK manager.
var linkGo = function(item) {_x000D_
$(item).on('click', function() {_x000D_
var _$this = $(this);_x000D_
var _urlBlank = _$this.attr("data-link");_x000D_
var _urlTemp = _$this.attr("data-url");_x000D_
if (_urlBlank === "_blank") {_x000D_
window.open(_urlTemp, '_blank');_x000D_
} else {_x000D_
// cross-origin_x000D_
location.href = _urlTemp;_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
This can also be solved using a boolean.
For Each rngCol In rngAll.Columns
doCol = False '<==== Resets to False at top of each column
For Each cell In Selection
If cell.row = 1 Then
If thisColumnShouldBeProcessed Then doCol = True
End If
If doCol Then
'Do what you want to do to each cell in this column
End If
Next cell
Next rngCol
For example, here is the full example that:
(1) Identifies range of used cells on worksheet
(2) Loops through each column
(3) IF column title is an accepted title, Loops through all cells in the column
Sub HowToSkipForLoopIfConditionNotMet()
Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
Set rngAll = Range("A1").CurrentRegion
'MsgBox R.Address(0, 0), , "All data"
cnt = 0
For Each rngCol In rngAll.Columns
rngCol.Select
doCol = False
For Each cell In Selection
If cell.row = 1 Then
If cell.Value = "AnAllowedColumnTitle" Then doCol = True
End If
If doCol Then '<============== THIS LINE ==========
cnt = cnt + 1
Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
End If
Next cell
Next rngCol
End Sub
Note: If you didn't immediately catch it, the line If docol Then
is your inverted CONTINUE. That is, if doCol
remains False, the script CONTINUES to the next cell and doesn't do anything.
Certainly not as fast/efficient as a proper continue
or next for
statement, but the end result is as close as I've been able to get.
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
This one is quite simple and does not require a delegate as you say.
resultString = Regex.Replace(subjectString,
@"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$",
"'$0'");
This matches the following styles, which are all equivalent and acceptable formats for a GUID.
ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)
Update 1
@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.
This can be avoided by regex conditionals which are broadly supported.
Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)
The regex that follows Will match
{123}
(123)
123
And will not match
{123)
(123}
{123
(123
123}
123)
Regex:
^({)?(\()?\d+(?(1)})(?(2)\))$
The solutions is simplified to match only numbers to show in a more clear way what is required if needed.
I generally prefer defining my own: const double PI = 2*acos(0.0);
because not all implementations provide it for you.
The question of whether this function gets called at runtime or is static'ed out at compile time is usually not an issue, because it only happens once anyway.
There are a few npm libraries for cancellable promises.
p-cancelable https://github.com/sindresorhus/p-cancelable
cancelable-promise https://github.com/alkemics/CancelablePromise
Set the second function parameter to true if you require an associative array
Some versions of php require a 2nd paramter of true if you require an associative array
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
I also had problem with refused connection on port 80. I didn't use localhost.
curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"
Problem was that I had umlauts äåö in my textfile.txt.
If you override the equality of People then you can also use:
peopleList2.Except(peopleList1)
Except
should be significantly faster than the Where(...Any)
variant since it can put the second list into a hashtable. Where(...Any)
has a runtime of O(peopleList1.Count * peopleList2.Count)
whereas variants based on HashSet<T>
(almost) have a runtime of O(peopleList1.Count + peopleList2.Count)
.
Except
implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.
Or if you want fast code but don't want to override the equality:
var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));
This variant does not remove duplicates.
I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:
using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
try
{
using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
{
try
{
bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
GC.Collect();
}
catch (Exception ex)
{
throw ex;
}
}
}
catch (ArgumentException aex)
{
throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
}
}
The following line was causing an error:
Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)
The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it. The fix was to control/ validate the image for a valid jpeg image.
Hope it helps!
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
i faced this same, i check in in program and feature. there was an update has install for jdk1.8 which is not compatible with my old setting(jdk1.6.0) for ant in eclipse. I install that update. right now, my ant project is build success.
Try it, hope this will be helpful.
In this case why Java allows downcasting if it cannot be executed at the runtime?
I believe this is because there is no way for the compiler to know at compile-time if the cast will succeed or not. For your example, it's simple to see that the cast will fail, but there are other times where it is not so clear.
For instance, imagine that types B, C, and D all extend type A, and then a method public A getSomeA()
returns an instance of either B, C or D depending on a randomly generated number. The compiler cannot know which exact run-time type will be returned by this method, so if you later cast the results to B
, there is no way to know if the cast will succeed (or fail). Therefore the compiler has to assume casts will succeed.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
well there are really enough examples for this, but anyway, here you go
using System;
using System.Security.Cryptography;
namespace RsaCryptoExample
{
static class Program
{
static void Main()
{
//lets take a new CSP with a new 2048 bit rsa key pair
var csp = new RSACryptoServiceProvider(2048);
//how to get the private key
var privKey = csp.ExportParameters(true);
//and the public key ...
var pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new System.IO.StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
}
//converting it back
{
//get a stream from the string
var sr = new System.IO.StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
pubKey = (RSAParameters)xs.Deserialize(sr);
}
//conversion for the private key is no black magic either ... omitted
//we have a public key ... let's get a new csp and load that key
csp = new RSACryptoServiceProvider();
csp.ImportParameters(pubKey);
//we need some data to encrypt
var plainTextData = "foobar";
//for encryption, always handle bytes...
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);
//apply pkcs#1.5 padding and encrypt our data
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
var cypherText = Convert.ToBase64String(bytesCypherText);
/*
* some transmission / storage / retrieval
*
* and we want to decrypt our cypherText
*/
//first, get our bytes back from the base64 string ...
bytesCypherText = Convert.FromBase64String(cypherText);
//we want to decrypt, therefore we need a csp and load our private key
csp = new RSACryptoServiceProvider();
csp.ImportParameters(privKey);
//decrypt and strip pkcs#1.5 padding
bytesPlainTextData = csp.Decrypt(bytesCypherText, false);
//get our original plainText back...
plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
}
}
}
as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation
In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.
This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:
) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:
. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.
Script based on Joe answer (detach, copy files, attach both).
It's not necessary, but maybe access denied error on executing.
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
@dbName
and @copyDBName
variables before.USE master;
GO
DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'
-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
INSERT INTO ##DBFileNames([FileName])
SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')
-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')
EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')
-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')
-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE
@oldAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @dbName + ' ON ',
@newAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @copyDBName + ' ON '
DECLARE curs CURSOR FOR
SELECT [filename] FROM ##DBFileNames
OPEN curs
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0
BEGIN
SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
SET @ext = RIGHT(@filename,4)
SET @copyFileName = @path + @copyDBName + @ext
SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
PRINT @command
EXEC(@command);
SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'
FETCH NEXT FROM curs INTO @filename
END
CLOSE curs
DEALLOCATE curs
-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'
-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)
-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)
DROP TABLE ##DBFileNames
After all else failed...
My solution was to change the layout file from
= stylesheet_link_tag "reset-min", 'application'
to
= stylesheet_link_tag 'application'
And it worked! (You can put the reset file inside the manifest.)
convert an array to a GET param string that can be appended to a url could be done as follows
function encodeGet(array){
return getParams = $.map(array , function(val,index) {
var str = index + "=" + escape(val);
return str;
}).join("&");
}
call this function as
var getStr = encodeGet({
search: $('input[name="search"]').val(),
location: $('input[name="location"]').val(),
dod: $('input[name="dod"]').val(),
type: $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;
which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.
For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRectMake(0, 50, 320, 200)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Make sure you have remembered to import UIKit
.
Thank you Rob W for your answer.
I have been using this within a Cordova application to avoid having to load the API and so that I can easily control iframes which are loaded dynamically.
I always wanted the ability to be able to extract information from the iframe, such as the state (getPlayerState) and the time (getCurrentTime).
Rob W helped highlight how the API works using postMessage, but of course this only sends information in one direction, from our web page into the iframe. Accessing the getters requires us to listen for messages posted back to us from the iframe.
It took me some time to figure out how to tweak Rob W's answer to activate and listen to the messages returned by the iframe. I basically searched through the source code within the YouTube iframe until I found the code responsible for sending and receiving messages.
The key was changing the 'event' to 'listening', this basically gave access to all the methods which were designed to return values.
Below is my solution, please note that I have switched to 'listening' only when getters are requested, you can tweak the condition to include extra methods.
Note further that you can view all messages sent from the iframe by adding a console.log(e) to the window.onmessage. You will notice that once listening is activated you will receive constant updates which include the current time of the video. Calling getters such as getPlayerState will activate these constant updates but will only send a message involving the video state when the state has changed.
function callPlayer(iframe, func, args) {
iframe=document.getElementById(iframe);
var event = "command";
if(func.indexOf('get')>-1){
event = "listening";
}
if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': event,
'func': func,
'args': args || []
}), '*');
}
}
window.onmessage = function(e){
var data = JSON.parse(e.data);
data = data.info;
if(data.currentTime){
console.log("The current time is "+data.currentTime);
}
if(data.playerState){
console.log("The player state is "+data.playerState);
}
}
In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.
import {NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {EventListComponent} from './EventList.Component';
import {EventThumbnailComponent} from './EventThumbnail.Component';
import { EventService } from './shared/Event.Service'
import {ToastrService} from '../shared/toastr.service';
import {EventDetailsComponent} from './event-details/event.details.component';
import { RouterModule } from "@angular/router";
@NgModule({
imports:[BrowserModule,RouterModule],
declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
providers: [EventService,ToastrService]
})
export class EventModule {
}
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
It is sample extension
public class GetModelErrors
{
//Usage return Json to View :
//return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
public class KeyMessages
{
public string Key { get; set; }
public string Message { get; set; }
}
private readonly ModelStateDictionary _entry;
public GetModelErrors(ModelStateDictionary entry)
{
_entry = entry;
}
public int Count()
{
return _entry.ErrorCount;
}
public string Exceptions(string sp = "\n")
{
return string.Join(sp, _entry.Values
.SelectMany(v => v.Errors)
.Select(e => e.Exception));
}
public string Messages(string sp = "\n")
{
string msg = string.Empty;
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
}
}
return msg;
}
public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
{
List<KeyMessages> list = new List<KeyMessages>();
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
list.Add(new KeyMessages
{
Key = item.Key,
Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
});
}
}
return list;
}
}
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({
stop: function(event, ui) {
alert("New position: " + ui.item.index());
}
});
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
Just to offer the alternative to the Test-Path
cmdlet (since nobody mentioned it):
[System.IO.File]::Exists($path)
Does (almost) the same thing as
Test-Path $path -PathType Leaf
except no support for wildcard characters
There are a couple of variants of a rename command, in your case, it may be as simple as
rename ABC XYZ *.dat
You may have a version which takes a Perl regex;
rename 's/ABC/XYZ/' *.dat
Builder and Abstract Factory
The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That's why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory's methods to create its own objects. In the Builder's case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.
Common interface for products
In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.
If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:
CREATE TABLE categories (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE products (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE categories_products (
category_id int unsigned not null,
product_id int unsigned not null,
PRIMARY KEY (category_id, product_id),
KEY pkey (product_id),
FOREIGN KEY (category_id) REFERENCES categories (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (id)
ON DELETE CASCADE
ON UPDATE CASCADE
)Engine=InnoDB;
This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.
e.g.
products: boots, mittens, hats, coats
categories: red, green, blue, white, black
prod/cats: red boots, green mittens, red coats, black hats
If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.
The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.
comment followup:
you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red
. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.
Here's a more concrete example:
categories: products:
+----+------+ +----+---------+
| id | name | | id | name |
+----+------+ +----+---------+
| 1 | red | | 1 | mittens |
| 2 | blue | | 2 | boots |
+---++------+ +----+---------+
products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1 | 1 | // red mittens
| 1 | 2 | // blue mittens
| 2 | 1 | // red boots
| 2 | 2 | // blue boots
+------------+-------------+
Let's say you delete category #2 (blue):
DELETE FROM categories WHERE (id = 2);
the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories
, you end up with this table once the delete completes:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1 | 1 | // red mittens
| 2 | 1 | // red boots
+------------+-------------+
There's no foreign key defined in the products
table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.
bringToFront()
is the right way, but, NOTE that you must call bringToFront()
and invalidate()
method on highest-level view (under your root view), for e.g.:
Your view's hierarchy is:
-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6
So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView
. To bring it over (above) the ImageView
you must call bringToFront()
and invalidate()
method on your LinearLayout
s. Then it will work :)
**NOTE: Remember to set android:clipChildren="false"
for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:
.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hw="http://schemas.android.com/apk/res-auto"
android:id="@+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/common_theme_color"
android:orientation="vertical" >
<com.binh.helloworld.customviews.HWActionBar
android:id="@+id/action_bar"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_actionbar_height"
android:layout_alignParentTop="true"
hw:titleText="@string/app_name" >
</com.binh.helloworld.customviews.HWActionBar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/action_bar"
android:clipChildren="false" >
<LinearLayout
android:id="@+id/layout_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center_horizontal"
android:orientation="horizontal" >
</LinearLayout>
<ImageView
android:id="@+id/imgv_main"
android:layout_width="@dimen/common_imgv_height"
android:layout_height="@dimen/common_imgv_height"
android:layout_centerInParent="true"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:id="@+id/layout_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Some code in .java
private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example)
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);
GLuck!
Right click in the query pane, select Query Options...
and in the Execution->General section (the default when you first open it) there is an Execution time-out
setting.
Add-on software packages.
See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.
Also described at Wikipedia.
Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.
One more example:
If you have Column from A to D, and need to highlight the whole line (e.g. from A to D) if B is "Complete", then you can do it following:
"Custom formula is": =$B:$B="Completed"
Background Color: red
Range: A:D
Of course, you can change Range to A:T if you have more columns.
If B contains "Complete", use search as following:
"Custom formula is": =search("Completed",$B:$B)
Background Color: red
Range: A:D
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
Found successful workaround that is applicable for my scenario:
Don't log off, just lock the session!
Since this script is running on a Domain Controller, I am logging in to the server via the Remote Desktop console and then log off of the server to terminate my session. When setting up the Task in the Task Scheduler, I was using user accounts and local services that did not have access to run in an offline mode, or logon strictly to run a script.
Thanks to some troubleshooting assistance from Cole, I got to thinking about the RunAs function and decided to try and work around the non-functioning logons.
Starting in the Task Scheduler, I deleted my manually created Tasks. Using the new function in Server 2008 R2, I navigated to a 4740 Security Event in the Event Viewer, and used the right-click > Attach Task to this Event... and followed the prompts, pointing to my script on the Action page. After the Task was created, I locked my session and terminated my Remote Desktop Console connection. WIth the profile 'Locked' and not logged off, everything works like it should.
You can use:
select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name
You can also use:
var obj = {
alert: alert.bind(window)
};
obj.alert('I´m an alert!!');
If you're using VS Code, this is an awesome extension for generating file trees.
Added directly to markdown...
quakehunter
? client
? node_modules
? server
? ? index.js
? .gitignore
? package-lock.json
? package.json
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
I don't think using document.write is a bad practice at all. In simple words it is like a high voltage for inexperienced people. If you use it the wrong way, you get cooked. There are many developers who have used this and other dangerous methods at least once, and they never really dig into their failures. Instead, when something goes wrong, they just bail out, and use something safer. Those are the ones who make such statements about what is considered a "Bad Practice".
It's like formatting a hard drive, when you need to delete only a few files and then saying "formatting drive is a bad practice".
When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek()
operation moves that pointer to some other part of the file so you can read or write at that place.
So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20)
to move to where you want to start reading, then continue with reading the file.
Or say you want to read every 10th byte, you could write a loop that does seek(9, 1)
(moves 9 bytes forward relative to the current positions), read(1)
(reads one byte), repeat.
In Eclipse
Right click Project --> Java Build Path --> Libraries
EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.
armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.
armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.
I would use JPA's constructor expression feature. See also following answer:
JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped
Following the example in the question, it would be something like this.
SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c
A couple short, sweet extension methods on IEnumerable
and IEnumerable<T>
do it for me:
public static IEnumerable Append(this IEnumerable first, params object[] second)
{
return first.OfType<object>().Concat(second);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> first, params T[] second)
{
return first.Concat(second);
}
public static IEnumerable Prepend(this IEnumerable first, params object[] second)
{
return second.Concat(first.OfType<object>());
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, params T[] second)
{
return second.Concat(first);
}
Elegant (well, except for the non-generic versions). Too bad these methods are not in the BCL.
In my case, I have unchecked "GPU Host" and its worked :)
The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.
Very easy to use, lightweight, impressive application.
let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));
co(function*() {
console.log('Welcome to My Console,');
yield sleep(3000);
console.log('Blah blah blah blah extra-blah');
});
This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function
keyword followed by a *
is called a generator function in modern Javascript. The npm package co
provided a runner function to run a generator.
Essentially generator function provided a way to pause the execution of a function with yield
keyword, at the same time, yield
in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise
from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.
If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
You can change the definition of existing DB column using following sql.
ALTER TABLE mytable modify mycolumn datatype NOT NULL;
Here's a very nice Gist that covers all the possible cases: https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4
Overview:
git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue
I solve this problem by always using the [h]
option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.
I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)
The manual for the memoir
class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.
To pass a string to the view as the Model, you can do:
public ActionResult Index()
{
string myString = "This is my string";
return View((object)myString);
}
You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:
return View("Index", myString);
.. which is a bit more verbose.
Then in your view, just type it as a string:
@model string
<p>Value: @Model</p>
Then you can manipulate Model how you want.
For accessing it from a Layout page, it might be better to create an HtmlExtension for this:
public static string GetThemePath(this HtmlHelper helper)
{
return "/path-to-theme";
}
Then inside your layout page:
<p>Value: @Html.GetThemePath()</p>
Hopefully you can apply this to your own scenario.
Edit: explicit HtmlHelper code:
namespace <root app namespace>
{
public static class Helpers
{
public static string GetThemePath(this HtmlHelper helper)
{
return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
}
}
}
Then in your view:
@{
var path = Html.GetThemePath();
// .. do stuff
}
Or:
<p>Path: @Html.GetThemePath()</p>
Edit 2:
As discussed, the Helper will work if you add a @using
statement to the top of your view, with the namespace pointing to the one that your helper is in.
For me this works perfect
insert into oehr.employees select * from employees where employee_id=99
I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.
One good approach will be to use the answer @Parodo specified
What you're basically doing here is relying on Date#toString()
which already has a fixed pattern. To convert a Java Date
object into another human readable String pattern, you need SimpleDateFormat#format()
.
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse()
. This means that the inputDate
isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z"
. You'll probably need to modify the pattern to match the inputDate
's actual pattern.
Update: Okay, I did a test:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
This correctly prints:
03.01.2010 21:32:27
(I'm on GMT-4)
Update 2: as per your edit, you really got a ParseException
on that. The most suspicious part would then be the timezone of UTC
. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs()
. There must be a UTC
in between.
If you want to use slf4j simple
, you need these jar
files on your classpath:
If you want to use slf4j
and log4j
, you need these jar
files on your classpath:
No more, no less. Using slf4j simple
, you'll get basic logging to your console at INFO
level or higher. Using log4j
, you must configure it accordingly.
For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:
<HorizontalScrollView
android:id="@+id/photo_scroll"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="horizontal"
android:visibility="gone">
<LinearLayout
android:id="@+id/imageview_holder"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="match_parent">
</LinearLayout>
</HorizontalScrollView>
An this works perfectly fine for me. In the activity all I have to do is something like the code below:
LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2);
As I said that works for me, and I hope it helps somebody looking to achieve this as well.
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
You are using .index()
which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0)
will always return 2
, no matter how many times 1.0
occurs in the list.
Use enumerate()
to add indices to your loop instead:
def find(lst, a, b):
result = []
for i, x in enumerate(lst):
if x<a or x>b:
result.append(i)
return result
You can collapse this into a list comprehension:
def find(lst, a, b):
return [i for i, x in enumerate(lst) if x<a or x>b]
Can you believe that the treeview on the image below does not use any JavaScript, but relies only on CSS3? Check out this CSS3 TreeView, which is good with Twitter BootStrap:
You can get more info about this here http://acidmartin.wordpress.com/2011/09/26/css3-treevew-no-javascript/.
The problem that global variables create for the programmer is that it expands the inter-component coupling surface between the various components that are using the global variables. What this means is that as the number of components using a global variable increases, the complexity of the interactions can also increase. This increased coupling usually makes defects easier to inject into the system when making changes and also makes defects harder to diagnose and correct. This increase coupling can also reduce the number of available options when making changes and it can increase the effort required for changes as often one must trace through the various modules that are also using the global variable in order to determine the consequences of changes.
The purpose of encapsulation, which is basically the opposite of using global variables, is to decrease coupling in order to make understanding and changing the source easier and safer and more easily tested. It is much easier to use unit testing when global variables are not used.
For example if you have a simple global integer variable that is being used as an enumerated indicator that various components use as a state machine and you then make a change by adding a new state for a new component, you must then trace through all the other components to ensure that the change will not affect them. An example of a possible problem would be if a switch
statement to test the value of the enumeration global variable with case
statements for each of the current values is being used in various places and it so happens that some of the switch
statements do not have a default
case to handle an unexpected value for the global all of a sudden you have undefined behavior so far as the application is concerned.
On the other hand the use of a shared data area might be used to contain a set of global parameters which are referenced throughout the application. This approach is often used with embedded applications with small memory footprints.
When using global variables in these sort of applications typically the responsibility for writing to the data area is allocated to a single component and all other components see the area as const
and read from it, never writing to it. Taking this approach limits the problems that can develop.
A few problems from global variables which need to be worked around
When the source for a global variable such as a struct is modified, everything using it must be recompiled so that everything using the variable knows its true size and memory template.
If more than one component can modify the global variable you can run into problems with inconsistent data being in the global variable. With a multi-threading application, you will probably need to add some kind of locking or critical region to provide a way so that only one thread at a time can modify the global variable and when a thread is modifying the variable, all changes are complete and committed before other threads can query the variable or modify it.
Debugging a multi-threaded application that uses a global variable can be more difficult. You can run into race conditions that can create defects that are difficult to replicate. With several components communicating through a global variable, especially in a multi-threaded application, being able to know what component is changing the variable when and how it is changing the variable can be very difficult to understand.
Name clash can be a problem with using of global variables. A local variable that has the same name as a global variable can hide the global variable. You also run into the naming convention issue when using the C programming language. A work around is to divide the system up into sub-systems with the global variables for a particular sub-system all beginning with the same first three letters (see this on resolving name space collisions in objective C). C++ provides namespaces and with C you can work around this by creating a globally visible struct whose members are various data items and pointers to data and functions which are provided in a file as static hence with file visibility only so that they can only be referenced through the globally visible struct.
In some cases the original application intent is changed so that global variables that provided the state for a single thread is modified to allow several duplicate threads to run. An example would be a simple application designed for a single user using global variables for state and then a request comes down from management to add a REST interface to allow remote applications to act as virtual users. So now you run into having to duplicate the global variables and their state information so that the single user as well as each of the virtual users from remote applications have their own, unique set of global variables.
Using C++ namespace
and the struct
Technique for C
For the C++ programming language the namespace
directive is a huge help in reducing the chances of a name clash. namespace
along with class
and the various access keywords (private
, protected
, and public
) provide most of the tools you need to encapsulate variables. However the C programming language doesn't provide this directive. This stackoverflow posting, Namespaces in C , provides some techniques for C.
A useful technique is to have a single memory resident data area that is defined as a struct
which has global visibility and within this struct
are pointers to the various global variables and functions that are being exposed. The actual definitions of the global variables are given file scope using the static
keyword. If you then use the const
keyword to indicate which are read only, the compiler can help you to enforce read only access.
Using the struct
technique can also encapsulate the global so that it becomes a kind of package or component that happens to be a global. By having a component of this kind it becomes easier to manage changes that affect the global and the functionality using the global.
However while namespace
or the struct
technique can help manage name clashes, the underlying problems of inter-component coupling which the use of globals introduces especially in a modern multi-threaded application, still exist.
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
See also the http://www.pixelbeat.org/scripts/timeout script the functionality of which has been integrated into newer coreutils
Create a table with the set you want to export and then use the command line utility pg_dump to export to a file:
create table export_table as
select id, name, city
from nyummy.cimory
where city = 'tokyo'
$ pg_dump --table=export_table --data-only --column-inserts my_database > data.sql
--column-inserts
will dump as insert commands with column names.
--data-only
do not dump schema.
As commented below, creating a view in instead of a table will obviate the table creation whenever a new export is necessary.
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
The trailing backslash must be the last character on the line for it to be interpreted as a continuation command. No comments or even whitespace are allowed after it.
You should be able to put comment lines in between your commands
# output MYSQLDUMP file
cat ${MYSQLDUMP} | \
# simplify the line
sed '/created_at/d' | \
# create some newlines
tr ",;" "\n" | \
# use some sed magic
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
# more magic
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
# even more magic
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
# I hate phone numbers in my output
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \
# one more sed call and then send it to the CSV file
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
You can put the above answers into one line like this. And you don't need to write the function.
<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;" />
I made a small library that lets you easily use a throbber without images.
It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.
// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);
// Start the throbber.
throbber.play();
// Pause the throbber.
throbber.pause();
How about:
Supplier<Stream<Integer>> randomIntsStreamSupplier =
() -> (new Random()).ints(0, 2).boxed();
Stream<Integer> tails =
randomIntsStreamSupplier.get().filter(x->x.equals(0));
Stream<Integer> heads =
randomIntsStreamSupplier.get().filter(x->x.equals(1));
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:
Install Android SDK
sudo apt-get install android-sdk
Export environmental variables
export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.