You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();
Your database table structure should have a books table and a chapters table with columns like:
books
chapters
Then to reduce the number of queries use a join table in your search query.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
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.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
One of the easiest way to do it is by using
npx --ignore-existing create-react-app [project name]
This will remove the old cached version of create-react-app and then get the new version to create the project.
Note: Adding the name of the project is important as just ignoring the existing create-react-app version is stale and the changes in your machines global env is temporary and hence later just using npx create-react-app [project name]
will not provide the desired result.
This is likely due to your system's overcommit handling mode.
In the default mode, 0
,
Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slightly more memory in this mode. This is the default.
The exact heuristic used is not well explained here, but this is discussed more on Linux over commit heuristic and on this page.
You can check your current overcommit mode by running
$ cat /proc/sys/vm/overcommit_memory
0
In this case you're allocating
>>> 156816 * 36 * 53806 / 1024.0**3
282.8939827680588
~282 GB, and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.
If (as root) you run:
$ echo 1 > /proc/sys/vm/overcommit_memory
This will enable "always overcommit" mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).
I tested this myself on a machine with 32 GB of RAM. With overcommit mode 0
I also got a MemoryError
, but after changing it back to 1
it works:
>>> import numpy as np
>>> a = np.zeros((156816, 36, 53806), dtype='uint8')
>>> a.nbytes
303755101056
You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.
This code keep clicking "Refresh folder" in the file explorer pane.
function ClickRefresh(){
console.log("Working");
document.querySelector("[icon='colab:folder-refresh']").click()
}
const myjob = setInterval(ClickRefresh, 60000)
This is what it worked for me. The tsconfig.json
has an option noImplicitAny
that it was set to true
, I just simply set it to false
and now I can access properties in objects using strings.
It's not a solution with PowerShell, but I had the same problem except with MINGW64. I got around it by switching to Windows Subsystem for Linux (which I wanted to do anyways) as my terminal, just generally and in VSCode. This post describes it well:
How to configure VS Code (windows) to use Ubuntu App as terminal
In summary:
1) Install Ubuntu from the Windows App Store
2) Change the default bash from CMD -> wslconfig /setdefault Ubuntu
--- For VSCode
3) Restart VSCode
4) In VSCode change "terminal.integrated.shell.windows" to "C:\WINDOWS\System32\bash.exe" (for further details see the post above)
Running smoothly now in VSCode and WSL (Bash on Ubuntu on Windows). Might be at least a temporary solution for you.
Add 3.1.1 in to properties like below than fix issue
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
Just Update Project => right click => Maven=> Update Project
You can remove the 2nd argument type array []
but the fetchBusinesses()
will also be called every update. You can add an IF
statement into the fetchBusinesses()
implementation if you like.
React.useEffect(() => {
fetchBusinesses();
});
The other one is to implement the fetchBusinesses()
function outside your component. Just don't forget to pass any dependency arguments to your fetchBusinesses(dependency)
call, if any.
function fetchBusinesses (fetch) {
return fetch("theURL", { method: "GET" })
.then(res => normalizeResponseErrors(res))
.then(res => res.json())
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
}
function YourComponent (props) {
const { fetch } = props;
React.useEffect(() => {
fetchBusinesses(fetch);
}, [fetch]);
// ...
}
In SnackbarContentWrapper
you need to change
<IconButton
key="close"
aria-label="Close"
color="inherit"
className={classes.close}
onClick={onClose}
>
to
<IconButton
key="close"
aria-label="Close"
color="inherit"
className={classes.close}
onClick={() => onClose}
>
so that it only fires the action when you click.
Instead, you could just curry the handleClose
in SingInContainer
to
const handleClose = () => (reason) => {
if (reason === 'clickaway') {
return;
}
setSnackBarState(false)
};
It's the same.
When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution. My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.
(1) open a new command window, then open a new jupyter notebook. try to save again in the old notebook, this time ,the error is 'fail: forbidden'
(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.
(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list' copy the code after 'token=' and before :: to the box you just saw. You can save this time. If it fails, you can try another token in the list
Here is a React Hooks specific solution for
Warning: Can't perform a React state update on an unmounted component.
You can declare let isMounted = true
inside useEffect
, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:
useEffect(() => {
let isMounted = true; // note this flag denote mount status
someAsyncOperation().then(data => {
if (isMounted) setState(data);
})
return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useEffect(() => {_x000D_
let isMounted = true; // note this mounted flag_x000D_
fetchData();_x000D_
return () => {_x000D_
isMounted = false;_x000D_
}; // use effect cleanup to set flag false, if unmounted_x000D_
_x000D_
// simulate some Web API fetching_x000D_
function fetchData() {_x000D_
setTimeout(() => {_x000D_
// drop "if (isMounted)" to trigger error again_x000D_
if (isMounted) setState("data fetched");_x000D_
}, 4000);_x000D_
}_x000D_
}, []);_x000D_
_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
useAsync
HookWe can encapsulate all the boilerplate into a custom Hook, that just knows, how to deal with and automatically abort async functions in case the component unmounts before:
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isMounted = true;
asyncFn().then(data => {
if (isMounted) onSuccess(data);
});
return () => { isMounted = false };
}, [asyncFn, onSuccess]);
}
// use async operation with automatic abortion on unmount_x000D_
function useAsync(asyncFn, onSuccess) {_x000D_
useEffect(() => {_x000D_
let isMounted = true;_x000D_
asyncFn().then(data => {_x000D_
if (isMounted) onSuccess(data);_x000D_
});_x000D_
return () => {_x000D_
isMounted = false;_x000D_
};_x000D_
}, [asyncFn, onSuccess]);_x000D_
}_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useAsync(delay, setState);_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const delay = () => new Promise(resolve => setTimeout(() => resolve("data fetched"), 4000));_x000D_
_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
For me, the Node package I was trying to use would only work on an older version of Node.
I was able to fix it by using Homebrew to install an older version of Node:
brew unlink node
brew install node@12
echo 'export PATH="/usr/local/opt/node@12/bin:$PATH"' >> ~/.zshrc
In the above commands, you will need to edit the Node version and then export PATH command.
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())
Solution:
Add the below line in your application
tag:
android:usesCleartextTraffic="true"
As shown below:
<application
....
android:usesCleartextTraffic="true"
....>
UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"
No Need to set clear text traffic to true as shown above, instead use the below code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
....
....
</domain-config>
<base-config cleartextTrafficPermitted="false"/>
</network-security-config>
Set the cleartextTrafficPermitted
to true
Hope it helps.
On Mac OS X Catalina the following worked just fine
xcode-select --install
After this, a UI prompt showed up and that complete the install of the tools
If you are using Docker, you may try an image that has Ubuntu with System D already active with this command:
docker run -d --name redis --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro jrei/systemd-ubuntu:18.04
Then you just need to run:
docker exec -it redis /bin/bash
and there you can just install Redis, start it, restart it or whatever you need.
You have a CryptoListPresenter _presenter
but you are never initializing it. You should either be doing that when you declare it or in your initState()
(or another appropriate but called-before-you-need-it method).
One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.
EDIT:
I see diegoveloper beat me to answering this, and that the OP asked a follow up.
@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);
, or
CryptoListPresenter _presenter;
@override
void initState() {
_presenter = new CryptoListPresenter(...);
}
As the error says your router link should match the existing routes configured
It should be just routerLink="/about
"
Define extension: String+Extension.ts
interface String {
toBoolean(): boolean
}
String.prototype.toBoolean = function (): boolean {
switch (this) {
case 'true':
case '1':
case 'on':
case 'yes':
return true
default:
return false
}
}
And import in any file where you want to use it '@/path/to/String+Extension'
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
I had the same issue resolved by add <scope>provided</scope>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>provided</scope>
</dependency>
Source: https://github.com/spring-projects/spring-boot/issues/13796#issuecomment-413313346
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
Jupyter Notebook is a web-based interactive computational environment for creating Jupyter notebook documents. It supports several languages like Python (IPython), Julia, R etc. and is largely used for data analysis, data visualization and further interactive, exploratory computing.
JupyterLab is the next-generation user interface including notebooks. It has a modular structure, where you can open several notebooks or files (e.g. HTML, Text, Markdowns etc) as tabs in the same window. It offers more of an IDE-like experience.
For a beginner I would suggest starting with Jupyter Notebook as it just consists of a filebrowser and an (notebook) editor view. It might be easier to use. If you want more features, switch to JupyterLab. JupyterLab offers much more features and an enhanced interface, which can be extended through extensions: JupyterLab Extensions (GitHub)
Create images
folder in root level of your project.
Drop your image in this folder, it should look like
Go to your pubspec.yaml
file, add assets
header and pay close attention to all the spaces.
flutter:
uses-material-design: true
# add this
assets:
- images/profile.jpg
Tap on Packages get
at the top right corner of the IDE.
Now you can use your image anywhere using
Image.asset("images/profile.jpg")
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
Don't use a button as a link. Instead, use a link styled as a button.
<Link to="/signup" className="btn btn-primary">Sign up</Link>
npx
runs a command of a package without installing it explicitly.
Use cases:
package.json
to execute something without installing these packages as project's dependencies.Syntax:
npx [options] [-p|--package <package>] <command> [command-arg]...
Package is optional:
npx -p uglify-js uglifyjs --output app.min.js app.js common.js
+----------------+ +--------------------------------------------+
package (optional) command, followed by arguments
For example:
Start a HTTP Server : npx http-server
Lint code : npx eslint ./src
# Run uglifyjs command in the package uglify-js
Minify JS : npx -p uglify-js uglifyjs -o app.min.js app.js common.js
Minify CSS : npx clean-css-cli -o style.min.css css/bootstrap.css style.css
Minify HTML : npx html-minifier index-2.html -o index.html --remove-comments --collapse-whitespace
Scan for open ports : npx evilscan 192.168.1.10 --port=10-9999
Cast video to Chromecast : npx castnow http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4
More about command
:
I had the same issue with Angular 7. Just executed the following command and error was solved.
npm install --save-dev @angular-devkit/build-angular
npm install bootstrap --save
and add relevent files into angular.json
file under the style
property for css files and under scripts
for JS files.
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
....
]
I had this problem during migration to Spring Boot. I've found a advice to remove dependencies and it helped. So, I removed dependency for jsp-api Project had. Also, servlet-api dependency has to be removed as well.
compileOnly group: 'javax.servlet.jsp', name: 'jsp-api', version: '2.2'
Update : In angular 7, they are the same as 6
In angular 6
the complete answer found in live example
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
it's because of pipeable/lettable operators
which now angular is able to use tree-shakable
and remove unused imports and optimize the app
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
more in MIGRATION
and Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
and for backward compatability you can use rxjs-compat
I have run into this before and trying a number of things has fixed it for me:
Also, if this is a .net core app running on the full framework, I've found you have to include a global.json file at the root of your project and point it to the SDK you want to use for that project:
{
"sdk": {
"version": "1.0.0-preview2-003121"
}
}
You can try this:
sudo ln -sf $( type -P pip ) /usr/bin/pip
After much research and testing, I have developed a solution for an app I'm currently converting from Android/iOS to Flutter.
With Android and iOS I used a 'Scaling Factor' applied to base font sizes, rendering text sizes that were relative to the screen size.
This article was very helpful: https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a
I created a StatelessWidget to get the font sizes of the Material Design typographical styles. Getting device dimensions using MediaQuery, calculating a scaling factor, then resetting the Material Design text sizes. The Widget can be used to define a custom Material Design Theme.
Emulators used:
set_app_theme.dart (SetAppTheme Widget)
import 'package:flutter/material.dart';
import 'dart:math';
class SetAppTheme extends StatelessWidget {
final Widget child;
SetAppTheme({this.child});
@override
Widget build(BuildContext context) {
final _divisor = 400.0;
final MediaQueryData _mediaQueryData = MediaQuery.of(context);
final _screenWidth = _mediaQueryData.size.width;
final _factorHorizontal = _screenWidth / _divisor;
final _screenHeight = _mediaQueryData.size.height;
final _factorVertical = _screenHeight / _divisor;
final _textScalingFactor = min(_factorVertical, _factorHorizontal);
final _safeAreaHorizontal = _mediaQueryData.padding.left + _mediaQueryData.padding.right;
final _safeFactorHorizontal = (_screenWidth - _safeAreaHorizontal) / _divisor;
final _safeAreaVertical = _mediaQueryData.padding.top + _mediaQueryData.padding.bottom;
final _safeFactorVertical = (_screenHeight - _safeAreaVertical) / _divisor;
final _safeAreaTextScalingFactor = min(_safeFactorHorizontal, _safeFactorHorizontal);
print('Screen Scaling Values:' + '_screenWidth: $_screenWidth');
print('Screen Scaling Values:' + '_factorHorizontal: $_factorHorizontal ');
print('Screen Scaling Values:' + '_screenHeight: $_screenHeight');
print('Screen Scaling Values:' + '_factorVertical: $_factorVertical ');
print('_textScalingFactor: $_textScalingFactor ');
print('Screen Scaling Values:' + '_safeAreaHorizontal: $_safeAreaHorizontal ');
print('Screen Scaling Values:' + '_safeFactorHorizontal: $_safeFactorHorizontal ');
print('Screen Scaling Values:' + '_safeAreaVertical: $_safeAreaVertical ');
print('Screen Scaling Values:' + '_safeFactorVertical: $_safeFactorVertical ');
print('_safeAreaTextScalingFactor: $_safeAreaTextScalingFactor ');
print('Default Material Design Text Themes');
print('display4: ${Theme.of(context).textTheme.display4}');
print('display3: ${Theme.of(context).textTheme.display3}');
print('display2: ${Theme.of(context).textTheme.display2}');
print('display1: ${Theme.of(context).textTheme.display1}');
print('headline: ${Theme.of(context).textTheme.headline}');
print('title: ${Theme.of(context).textTheme.title}');
print('subtitle: ${Theme.of(context).textTheme.subtitle}');
print('body2: ${Theme.of(context).textTheme.body2}');
print('body1: ${Theme.of(context).textTheme.body1}');
print('caption: ${Theme.of(context).textTheme.caption}');
print('button: ${Theme.of(context).textTheme.button}');
TextScalingFactors _textScalingFactors = TextScalingFactors(
display4ScaledSize: (Theme.of(context).textTheme.display4.fontSize * _safeAreaTextScalingFactor),
display3ScaledSize: (Theme.of(context).textTheme.display3.fontSize * _safeAreaTextScalingFactor),
display2ScaledSize: (Theme.of(context).textTheme.display2.fontSize * _safeAreaTextScalingFactor),
display1ScaledSize: (Theme.of(context).textTheme.display1.fontSize * _safeAreaTextScalingFactor),
headlineScaledSize: (Theme.of(context).textTheme.headline.fontSize * _safeAreaTextScalingFactor),
titleScaledSize: (Theme.of(context).textTheme.title.fontSize * _safeAreaTextScalingFactor),
subtitleScaledSize: (Theme.of(context).textTheme.subtitle.fontSize * _safeAreaTextScalingFactor),
body2ScaledSize: (Theme.of(context).textTheme.body2.fontSize * _safeAreaTextScalingFactor),
body1ScaledSize: (Theme.of(context).textTheme.body1.fontSize * _safeAreaTextScalingFactor),
captionScaledSize: (Theme.of(context).textTheme.caption.fontSize * _safeAreaTextScalingFactor),
buttonScaledSize: (Theme.of(context).textTheme.button.fontSize * _safeAreaTextScalingFactor));
return Theme(
child: child,
data: _buildAppTheme(_textScalingFactors),
);
}
}
final ThemeData customTheme = ThemeData(
primarySwatch: appColorSwatch,
// fontFamily: x,
);
final MaterialColor appColorSwatch = MaterialColor(0xFF3787AD, appSwatchColors);
Map<int, Color> appSwatchColors =
{
50 : Color(0xFFE3F5F8),
100 : Color(0xFFB8E4ED),
200 : Color(0xFF8DD3E3),
300 : Color(0xFF6BC1D8),
400 : Color(0xFF56B4D2),
500 : Color(0xFF48A8CD),
600 : Color(0xFF419ABF),
700 : Color(0xFF3787AD),
800 : Color(0xFF337799),
900 : Color(0xFF285877),
};
_buildAppTheme (TextScalingFactors textScalingFactors) {
return customTheme.copyWith(
accentColor: appColorSwatch[300],
buttonTheme: customTheme.buttonTheme.copyWith(buttonColor: Colors.grey[500],),
cardColor: Colors.white,
errorColor: Colors.red,
inputDecorationTheme: InputDecorationTheme(border: OutlineInputBorder(),),
primaryColor: appColorSwatch[700],
primaryIconTheme: customTheme.iconTheme.copyWith(color: appColorSwatch),
scaffoldBackgroundColor: Colors.grey[100],
textSelectionColor: appColorSwatch[300],
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors),
appBarTheme: customTheme.appBarTheme.copyWith(
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors)),
// accentColorBrightness: ,
// accentIconTheme: ,
// accentTextTheme: ,
// appBarTheme: ,
// applyElevationOverlayColor: ,
// backgroundColor: ,
// bannerTheme: ,
// bottomAppBarColor: ,
// bottomAppBarTheme: ,
// bottomSheetTheme: ,
// brightness: ,
// buttonBarTheme: ,
// buttonColor: ,
// canvasColor: ,
// cardTheme: ,
// chipTheme: ,
// colorScheme: ,
// cupertinoOverrideTheme: ,
// cursorColor: ,
// dialogBackgroundColor: ,
// dialogTheme: ,
// disabledColor: ,
// dividerColor: ,
// dividerTheme: ,
// floatingActionButtonTheme: ,
// focusColor: ,
// highlightColor: ,
// hintColor: ,
// hoverColor: ,
// iconTheme: ,
// indicatorColor: ,
// materialTapTargetSize: ,
// pageTransitionsTheme: ,
// platform: ,
// popupMenuTheme: ,
// primaryColorBrightness: ,
// primaryColorDark: ,
// primaryColorLight: ,
// primaryTextTheme: ,
// secondaryHeaderColor: ,
// selectedRowColor: ,
// sliderTheme: ,
// snackBarTheme: ,
// splashColor: ,
// splashFactory: ,
// tabBarTheme: ,
// textSelectionHandleColor: ,
// toggleableActiveColor: ,
// toggleButtonsTheme: ,
// tooltipTheme: ,
// typography: ,
// unselectedWidgetColor: ,
);
}
class TextScalingFactors {
final double display4ScaledSize;
final double display3ScaledSize;
final double display2ScaledSize;
final double display1ScaledSize;
final double headlineScaledSize;
final double titleScaledSize;
final double subtitleScaledSize;
final double body2ScaledSize;
final double body1ScaledSize;
final double captionScaledSize;
final double buttonScaledSize;
TextScalingFactors({
@required this.display4ScaledSize,
@required this.display3ScaledSize,
@required this.display2ScaledSize,
@required this.display1ScaledSize,
@required this.headlineScaledSize,
@required this.titleScaledSize,
@required this.subtitleScaledSize,
@required this.body2ScaledSize,
@required this.body1ScaledSize,
@required this.captionScaledSize,
@required this.buttonScaledSize
});
}
TextTheme _buildAppTextTheme(
TextTheme _customTextTheme,
TextScalingFactors _scaledText) {
return _customTextTheme.copyWith(
display4: _customTextTheme.display4.copyWith(fontSize: _scaledText.display4ScaledSize),
display3: _customTextTheme.display3.copyWith(fontSize: _scaledText.display3ScaledSize),
display2: _customTextTheme.display2.copyWith(fontSize: _scaledText.display2ScaledSize),
display1: _customTextTheme.display1.copyWith(fontSize: _scaledText.display1ScaledSize),
headline: _customTextTheme.headline.copyWith(fontSize: _scaledText.headlineScaledSize),
title: _customTextTheme.title.copyWith(fontSize: _scaledText.titleScaledSize),
subtitle: _customTextTheme.subtitle.copyWith(fontSize: _scaledText.subtitleScaledSize),
body2: _customTextTheme.body2.copyWith(fontSize: _scaledText.body2ScaledSize),
body1: _customTextTheme.body1.copyWith(fontSize: _scaledText.body1ScaledSize),
caption: _customTextTheme.caption.copyWith(fontSize: _scaledText.captionScaledSize),
button: _customTextTheme.button.copyWith(fontSize: _scaledText.buttonScaledSize),
).apply(bodyColor: Colors.black);
}
main.dart (Demo App)
import 'package:flutter/material.dart';
import 'package:scaling/set_app_theme.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SetAppTheme(child: HomePage()),
);
}
}
class HomePage extends StatelessWidget {
final demoText = '0123456789';
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Text Scaling with SetAppTheme',
style: TextStyle(color: Colors.white),),
),
body: SingleChildScrollView(
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display4.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display3.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.title.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.caption.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.button.fontSize,
),
),
],
),
),
),
),
),
);
}
}
To extract Google Drive zip from a Google colab notebook:
import zipfile
from google.colab import drive
drive.mount('/content/drive/')
zip_ref = zipfile.ZipFile("/content/drive/My Drive/ML/DataSet.zip", 'r')
zip_ref.extractall("/tmp")
zip_ref.close()
If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none
Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:
If you found display of [hidden] class is overridden, you need to add this css code to your style:
[hidden] {
display: none !important;
}
You must use some of the C # conversion systems:
string to boolean: True to true
string str = "True";
bool mybool = System.Convert.ToBoolean(str);
boolean to string: true to True
bool mybool = true;
string str = System.Convert.ToString(mybool);
//or
string str = mybool.ToString();
bool.Parse
expects one parameter which in this case is str, even .
Convert.ToBoolean
expects one parameter.
bool.TryParse
expects two parameters, one entry (str) and one out (result).
If TryParse
is true, then the conversion was correct, otherwise an error occurred
string str = "True";
bool MyBool = bool.Parse(str);
//Or
string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
I had the same issue while executing my selenium tests and I removed the selenium dependencies from the ModulePath to ClassPath under Build path in eclipse and it worked!
This error occurred when you are putting JPA dependencies in your spring-boot configuration file like in maven or gradle. The solution is: Spring-Boot Documentation
You have to specify the DB connection string and driver details in application.properties file. This will solve the issue. This might help to someone.
In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.
The method has been renamed to findById(…)
returning an Optional
so that you have to handle absence yourself:
Optional<Foo> result = repository.findById(…);
result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before
Try out df.apply() if you've a small/medium dataframe,
df['c2'] = df.apply(lambda x: 10 if x['c1'] == 'Value' else x['c1'], axis = 1)
Else, follow the slicing techniques mentioned in the above comments if you've got a big dataframe.
The trim() method removes whitespace from both sides of a string.
To remove all the spaces from the string use .replace(/\s/g, "")
this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();
Spring Boot 2.0.*
or aboveIf you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary
, because various auto-configurations down the road expect to be able to get one by type.
If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
return DataSourceBuilder.create().type(BasicDataSource.class).build();
}
firstDataSourceProperties
has to be flagged as@Primary
so that the database initializer feature uses your copy (if you use the initializer).
And your application.propoerties
will look something like this:
app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.
Hope this will help somebody to develop custom checkbox component with custom styles. This solution can use with forms too.
HTML
<label class="lbl">
<input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
*ngIf="isChecked" checked>
<input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
*ngIf="!isChecked" >
<span class="chk-box {{isChecked ? 'chk':''}}"></span>
<span class="lbl-txt" *ngIf="label" >{{label}}</span>
</label>
checkbox.component.ts
import { Component, Input, EventEmitter, Output, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxComponent),
multi: true
};
/** Custom check box */
@Component({
selector: 'app-checkbox',
templateUrl: './checkbox.component.html',
styleUrls: ['./checkbox.component.scss'],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CheckboxComponent implements ControlValueAccessor {
@Input() label: string;
@Input() isChecked = false;
@Input() disabled = false;
@Output() getChange = new EventEmitter();
@Input() className: string;
// get accessor
get value(): any {
return this.isChecked;
}
// set accessor including call the onchange callback
set value(value: any) {
this.isChecked = value;
}
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
writeValue(value: any): void {
if (value !== this.isChecked) {
this.isChecked = value;
}
}
onChange(isChecked) {
this.value = isChecked;
this.getChange.emit(this.isChecked);
this.onChangeCallback(this.value);
}
// From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
// From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
setDisabledState?(isDisabled: boolean): void {
}
}
checkbox.component.scss
@import "../../../assets/scss/_variables";
/* CHECKBOX */
.lbl {
font-size: 12px;
color: #282828;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
cursor: pointer;
&.checked {
font-weight: 600;
}
&.focus {
.chk-box{
border: 1px solid #a8a8a8;
&.chk{
border: none;
}
}
}
input {
display: none;
}
/* checkbox icon */
.chk-box {
display: block;
min-width: 15px;
min-height: 15px;
background: url('/assets/i/checkbox-not-selected.svg');
background-size: 15px 15px;
margin-right: 10px;
}
input:checked+.chk-box {
background: url('/assets/i/checkbox-selected.svg');
background-size: 15px 15px;
}
.lbl-txt {
margin-top: 0px;
}
}
Usage
Outside forms
<app-checkbox [label]="'Example'" [isChecked]="true"></app-checkbox>
Inside forms
<app-checkbox [label]="'Type 0'" formControlName="Type1"></app-checkbox>
I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml
<java.version>7</java.version>
to
<java.version>11</java.version>
Later to realise the property was used with a dash insteal of a dot:
<source>${java-version}</source>
<target>${java-version}</target>
(swearings), I replaced the dot with a dash and the error went away:
<java-version>11</javaversion>
If you are facing this issue on you Mac. Follow these steps
First checking who is owner of this file by using below command
ls -la /usr/local/lib/node_modules
you will find some file like below one of them is below
drwxr-xr-x 3 root wheel 768 May 29 02:21 node_modules
have you notice that above file is own by root, for make changes inside for you need to change owner ship of path.
you can use check who is current user by this command
id -un (in my case user is yamsol)
and then you can change by calling this command (just replace your user name with ownerName)
sudo chown -R ownerName: /usr/local/lib/node_modules
in my case as you know user is "yamsol" i will call this command in this way
sudo chown -R yamsol: /usr/local/lib/node_modules
thats it.
Try this way:
I have a package named plant_seedlings. The package is stored in google drive. What I should do is to copy this package in /usr/local/lib/python3.6/dist-packages/.
!cp /content/drive/ai/plant_seedlings.tar.gz /usr/local/lib/python3.6/dist-packages/
!cd /usr/local/lib/python3.6/dist-packages/ && tar -xzf plant_seedlings.tar.gz
!cd /content
!python -m plant_seedlings
You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.
ng update @angular/cli @angular/core --force
For a full list of options, check the docs: https://angular.io/cli/update
This code works for me:
<script type="application/javascript">
$('#elementID').change(function(event){
var fileName = event.target.files[0].name;
if (event.target.nextElementSibling!=null){
event.target.nextElementSibling.innerText=fileName;
}
});
</script>
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write:
Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
There are many ways to read the files in your colab notebook(**.ipnb), a few are:
Method 1 and 2 worked for me, rest I wasn't able to figure out. If anyone could, as others tried in above post please write an elegant answer. thanks in advance.!
First method:
I wasn't able to mount my google drive, so I installed these libraries
# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
Once the installation & authorization process is finished, you first mount your drive.
!mkdir -p drive
!google-drive-ocamlfuse drive
After installation I was able to mount the google drive, everything in your google drive starts from /content/drive
!ls /content/drive/ML/../../../../path_to_your_folder/
Now you can simply read the file from path_to_your_folder
folder into pandas using the above path.
import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)
you are suppose you use absolute path you received & not using /../..
Second method:
Which is convenient, if your file which you want to read it is present in the current working directory.
If you need to upload any files from your local file system, you could use below code, else just avoid it.!
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
suppose you have below the folder hierarchy in your google drive:
/content/drive/ML/../../../../path_to_your_folder/
Then, you simply need below code to load into pandas.
import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df
I fixed this issue by installing jre
, I have jdk
already installed but jre
was not installed.
I tried to restart my Windows machine and reinstalled the "npm i".
It worked for me.
You're only exporting it in your NgModule, you need to import it too
@NgModule({
imports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
]
exports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
],
declarations: [
SearchComponent,
],
})export class MaterialModule {};
better yet
const modules = [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule
];
@NgModule({
imports: [...modules],
exports: [...modules]
,
})export class MaterialModule {};
You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported
Like BrowserAnimationsModule
Try moving it to MaterialModule, or before it
I resolved this issue by removing android:screenOrientation="portrait"
and added below code into my onCreate
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
while my theme properties are
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowDisablePreview">true</item>
I had this issue and I fixed it using the following steps You need to completely uninstall python3-p using:
sudo apt-get --purge autoremove python3-pip
Then resintall the package with:
sudo apt install python3-pip
To confirm that everything works, run:
pip3 -V
After this you can now use pip3 to manage any python package of your interest. Eg
pip3 install NumPy
Edit file /usr/share/phpmyadmin/libraries/sql.lib.php
See an error on your error
./libraries/sql.lib.php#2038: PMA_isRememberSortingOrder(array)
./libraries/sql.lib.php#1984: PMA_executeQueryAndGetQueryResponse(
go to this line and remove the function call.
It works for me.
To run the spring-boot application, need to follow some step.
Maven setup (ignore if already setup):
a. Install maven from https://maven.apache.org/download.cgi
b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).
c. Set MAVEN_HOME in system variable.
d. Set path for maven
Add Maven Plugin to POM.XML
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Build Spring Boot Project with Maven
maven package
or
mvn install / mvn clean install
Run Spring Boot app using Maven:
mvn spring-boot:run
[optional] Run Spring Boot app with java -jar command
java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
The problem is in the font-weight
.
For Font Awesome 5
you have to use {font-weight:900}
Weird thing for me was that I had the provider:[], but the HTML tag that uses the provider was what was causing the error. I'm referring to the red box below:
It turns out I had two classes in different components with the same "employee-list.component.ts" filename and so the project compiled fine, but the references were all messed up.
You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e
<html-element role="button" />
Just Add HttpClientModule
in 'imports' array of app.module.ts
file.
...
import {HttpClientModule} from '@angular/common/http'; // add this line
@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule, //add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then you can use HttpClient
in your project through constructor injection
import {HttpClient} from '@angular/common/http';
export class Services{
constructor(private http: HttpClient) {}
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
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'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
Set this in HTML:
<div class="modal-body " [formGroup]="Form">
<div class="">
<mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="b" [disabled]="true"> Display 2 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="c" [disabled]="true"> Display 3 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="d" [disabled]="true"> Display 4</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="e" [disabled]="true"> Display 5 </mat-checkbox>
</div>
</div>
Changes in Ts file
this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});
Conditionvalidation in Ur Business logic
if(true){
this.Form.patch(a: true);
}
You need to add sudo . I did the following to get it installed :
sudo apt-get install libsm6 libxrender1 libfontconfig1
and then did that (optional! maybe you won't need it)
sudo python3 -m pip install opencv-contrib-python
FINALLY got it done !
I suggest to use this plugin flutter_easyloading
flutter_easyloading is clean and lightweight Loading widget for Flutter App, easy to use without context, support iOS and Android
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_easyloading: ^2.0.0
Now in your Dart code, you can use:
import 'package:flutter_easyloading/flutter_easyloading.dart';
To use First, initialize FlutterEasyLoading
in MaterialApp
/CupertinoApp
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter EasyLoading',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter EasyLoading'),
builder: EasyLoading.init(),
);
}
}
EasyLoading is a singleton, so you can custom loading style any where like this:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import './custom_animation.dart';
void main() {
runApp(MyApp());
configLoading();
}
void configLoading() {
EasyLoading.instance
..displayDuration = const Duration(milliseconds: 2000)
..indicatorType = EasyLoadingIndicatorType.fadingCircle
..loadingStyle = EasyLoadingStyle.dark
..indicatorSize = 45.0
..radius = 10.0
..progressColor = Colors.yellow
..backgroundColor = Colors.green
..indicatorColor = Colors.yellow
..textColor = Colors.yellow
..maskColor = Colors.blue.withOpacity(0.5)
..userInteractions = true
..customAnimation = CustomAnimation();
}
Then, use per your requirement
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
class TestPage extends StatefulWidget {
@override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
@override
void initState() {
super.initState();
// EasyLoading.show();
}
@override
void deactivate() {
EasyLoading.dismiss();
super.deactivate();
}
void loadData() async {
try {
EasyLoading.show();
Response response = await Dio().get('https://github.com');
print(response);
EasyLoading.dismiss();
} catch (e) {
EasyLoading.showError(e.toString());
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter EasyLoading'),
),
body: Center(
child: FlatButton(
textColor: Colors.blue,
child: Text('loadData'),
onPressed: () {
loadData();
// await Future.delayed(Duration(seconds: 2));
// EasyLoading.show(status: 'loading...');
// await Future.delayed(Duration(seconds: 5));
// EasyLoading.dismiss();
},
),
),
);
}
}
Instead of remotely putting popper js from CDN you can directly install it in your angular project.
Try this.
npm install popper.js --save
This query installs an updated version of popper.js Don't mention any version there, it will work for you.
This fixed it:
rm Gemfile.lock
bundle install
againEDIT: DON'T DO IT IN PRODUCTION!
For production go to this answer: https://stackoverflow.com/posts/54083113/revisions
I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df)
for displaying the DataFrame df
:
from IPython.core.display import display, HTML
def force_show_all(df):
with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
display(HTML(df.to_html()))
# ... now when you're ready to fully display df:
force_show_all(df)
As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.
Add that component to entryComponents in @NgModule of your app's module:
entryComponents:[ConfirmComponent],
as well as Declarations:
declarations: [
AppComponent,
ConfirmComponent
]
The simplest solution I have found so far which works perfectly for small to mid-size CSV files is:
pandas.read_csv(URL)
This may or may not work for reading a text file line by line or binary files.
If you want to hide this warn, you just need to install fsevents as a optional dependency. Just execute:
npm i fsevents@latest -f --save-optional
..And the warn will no longer be a bother.
For some reason Louise's answer didn't work for me I had to:
-Open anaconda prompt and generate the config file for Jupyter: jupyter notebook --generate-config
-Open the newly created config file at: C:\Users\builder\.juptyer\jupyter_notebook_config.py
-Add the following to the file:
import webbrowser
webbrowser.register('chrome', None, webbrowser.GenericBrowser(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'))
c.NotebookApp.browser = 'chrome'
Just figured out the reason when we type "ng serve" INSIDE OUR PROJECT..
for example C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve
could not resolve module C:\Users\EdgeTech1\Desktop\C
results: failed compiled
root cause:
My folder name was C# Project..
Note: I tried to remove the #
in my Project Name, I rename C# Project
to CSharp
instead and I tried to open cmd
prompt again, typed the same thing..
for example:
C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve
and my project compiled successfully.. so as much as possible avoid ASCII characters in naming projects files.
Might be late to the party - also, this answer is for LAMP users who got to this thread from google, like me.
Basically, the problem is PMA is trying to connect to SQL with a user that doesn't exist.
At /etc/phpmyadmin/config-db.php, you will find 2 variables: $dbuser, and $dbpass. Those specify the MySQL user and Password that PMA is trying to connect with.
Now, connect with some username/password that work (or just "root" if you are connecting from localhost), create a new user with global priviliges (e.g - %PMA User% with password %Some Random Password%), then in the above mentioned file set:
$dbuser = %PMA User% ;
$dbpass = %Some Random Password%;
You might also change other stuff there, like the server address ($dbserver), the port ($dbport, which might not be the default one on your machine), and more.
For use with React Router v4 and a functional component anywhere in the dom-tree.
import React from 'react';
import { withRouter } from 'react-router-dom';
const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;
export default withRouter(GoBack);
I faced the same error when I used another class instead of component down the component decorator.
Component class must come just after the component decorator
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
export class SmsgtreconComponent implements OnInit {
After moving TodoItemNode to the top of component decorator it worked
Solution
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
export class SmsgtreconComponent implements OnInit {
This is easy to do using the jupyter-themes
package by Kyle Dunovan. You may be able to install it using conda
. Otherwise, you will need to use pip
.
Install it with conda:
conda install -c conda-forge jupyterthemes
or pip:
pip install jupyterthemes
You can get the list of available themes with:
jt -l
So change your theme with:
jt -t theme-name
To load a theme, finally, reload the page. The docs and source code are here.
I have uninstalled jupyter, notebook and ipython, and installed jupyterlab. It is working for now (with just a few libraries installed and Python 3.6.8.
Something to discard: Uninstalling Python 3.7 completely with his libraries and reverting to 3.6 doesn't fix it, although it improves it, it works intermittently now (but once sth doesn't work properly, things start to get worse and worse, so I did the above).
I had the same issue and it turned out my windows password had changed since I shared my drive with docker.
The fix was to rest my credentials in docker settings -> shared drives -> reset credentials
and then reshare my drive.
To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables
$carousel-control-color:
$carousel-caption-color:
$carousel-indicator-active-bg:
A simple answer is to replace this line:
<script type="text/javascript" src="your_directory/bootstrap.min.js"></script>
for this other:
<script type="text/javascript" src="your_directory/bootstrap.bundle.min.js"></script>
Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises
HTML
<select
ng-model="cboPais"
ng-options="item.strPais for item in geoPaises"
></select>
JavaScript
$http.get(strUrl2).success(function (response) {
if (response.length > 0) {
$scope.geoPaises = response; //Data source
nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
if (nIndex >= 0) {
$scope.cboPais = response[nIndex]; //if index of array was found
} else {
$scope.cboPais = response[0]; //select the first element of array
}
$scope.geo_getDepartamentos();
}
}
This should do the trick retrieving the params from the url:
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
let date = params['startdate'];
console.log(date); // Print the parameter to the console.
});
}
The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).
I faced the same problem , As I'm trying to work on angular project in VS code.
The solution for which this issue resolved is .
2.run the following command in terminal
npm install
Then Run npm audit fix
Then Run npm audit fix --force
now the issue will be resolved.
got the below error
PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to https://registry.npmjs.org/vue failed, reason: unable to get local issuer certificate
npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log
Below command solved the issue:
npm config set strict-ssl false
Gradle (build.gradle):
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
Entity (User.class):
LocalDate dateOfBirth;
Code:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);
When you use the url tag you should use quotes for string literals, for example:
{% url 'products' %}
At the moment product
is treated like a variable and evaluates to ''
in the error message.
you can also do in this way using input-group
<div class="input-group">
<input class="form-control"
placeholder="I can help you to find anything you want!">
<div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>
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),
)
],
));
}
Some version working
<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>
Yes you can run keras models on GPU. Few things you will have to check first.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
for TF > v2.0
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
(Thanks @nbro and @Ferro for pointing this out in the comments)
OR
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
output will be something like this:
[
name: "/cpu:0"device_type: "CPU",
name: "/gpu:0"device_type: "GPU"
]
Once all this is done your model will run on GPU:
To Check if keras(>=2.1.1) is using GPU:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
All the best.
In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start
You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
I really don't understand why Javascript world trying to do thing more complicated. Why not just download and include in html? Trying to have something like Maven in Java? But we have to manually include it in html anyway? So, what is the point? Maybe someday I will understand but not now.
This is how I can get it
then I get this message
[email protected] added 1 package in 1.215s
then where is "add package" ? very informative , right? I found it in my C:\Users\surasin\node_modules\popper.js\dist
Hope this help
Inline
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline
Every class or interface can be used as a type in TypeScript.
const date = new Date();
will already know about the date
type definition as Date
is an internal TypeScript object referenced by the DateConstructor interface.
And for the constructor you used, it is defined as:
interface DateConstructor {
new(): Date;
...
}
To make it more explicit, you can use:
const date: Date = new Date();
You might be missing the type definitions though, the Date
is coming for my example from the ES6 lib, and in my tsconfig.json
I have defined:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"dom"
],
You might adapt these settings to target your wanted version of JavaScript.
The Date is by the way an Interface from lib.es6.d.ts
:
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;
/** Gets the month of a Date object using Universal Coordinated Time (UTC). */
getUTCMonth(): number;
/** Gets the day-of-the-month, using local time. */
getDate(): number;
/** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
getUTCDate(): number;
/** Gets the day of the week, using local time. */
getDay(): number;
/** Gets the day of the week using Universal Coordinated Time (UTC). */
getUTCDay(): number;
/** Gets the hours in a date, using local time. */
getHours(): number;
/** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
getUTCHours(): number;
/** Gets the minutes of a Date object, using local time. */
getMinutes(): number;
/** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
getUTCMinutes(): number;
/** Gets the seconds of a Date object, using local time. */
getSeconds(): number;
/** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
getUTCSeconds(): number;
/** Gets the milliseconds of a Date, using local time. */
getMilliseconds(): number;
/** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
getUTCMilliseconds(): number;
/** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
getTimezoneOffset(): number;
/**
* Sets the date and time value in the Date object.
* @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
*/
setTime(time: number): number;
/**
* Sets the milliseconds value in the Date object using local time.
* @param ms A numeric value equal to the millisecond value.
*/
setMilliseconds(ms: number): number;
/**
* Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
* @param ms A numeric value equal to the millisecond value.
*/
setUTCMilliseconds(ms: number): number;
/**
* Sets the seconds value in the Date object using local time.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setSeconds(sec: number, ms?: number): number;
/**
* Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCSeconds(sec: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using local time.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the hour value in the Date object using local time.
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the hours value in the Date object using Universal Coordinated Time (UTC).
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the numeric day-of-the-month value of the Date object using local time.
* @param date A numeric value equal to the day of the month.
*/
setDate(date: number): number;
/**
* Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
* @param date A numeric value equal to the day of the month.
*/
setUTCDate(date: number): number;
/**
* Sets the month value in the Date object using local time.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
*/
setMonth(month: number, date?: number): number;
/**
* Sets the month value in the Date object using Universal Coordinated Time (UTC).
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
*/
setUTCMonth(month: number, date?: number): number;
/**
* Sets the year of the Date object using local time.
* @param year A numeric value for the year.
* @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
* @param date A numeric value equal for the day of the month.
*/
setFullYear(year: number, month?: number, date?: number): number;
/**
* Sets the year value in the Date object using Universal Coordinated Time (UTC).
* @param year A numeric value equal to the year.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
* @param date A numeric value equal to the day of the month.
*/
setUTCFullYear(year: number, month?: number, date?: number): number;
/** Returns a date converted to a string using Universal Coordinated Time (UTC). */
toUTCString(): string;
/** Returns a date as a string value in ISO format. */
toISOString(): string;
/** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
toJSON(key?: any): string;
}
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
I had the same issue . Its a bug in Xcode 9.1. There is a trick to make it work for now. Lock your phone. Run the code. Xcode will ask to unlock the iPhone.
There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.
In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.
With pure JavaScript:
console.log(window.location.href)
Using Angular:
this.router.url
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'The href is: {{href}}'
/*
Other component settings
*/
})
export class Component {
public href: string = "";
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview
Go got XAMPP->mysql->bin->my.ini
open the file with an editor and add 'skip-grant-tables' after mysql.
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div
= document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i <
a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
_x000D_
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">home</a>
<a href="#base">contact</a>
</div>
</div>
_x000D_
I came across this problem because my cols exceeded the row grid length (> 12)
A solution using 100% Bootstrap 4:
Since the rows in Bootstrap are already display: flex
You just need to add flex-fill
to the Col, and h-100
to the container and any children.
Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo
<div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 hidden-md-down flex-fill" id="yellow">
XXXX
</div>
<div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Form Goes Here
</div>
<div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Another form
</div>
</div>
</div>
There are two syntax errors in your ternary conditional:
if
. Check the correct syntax here.You are missing a parenthesis in your code. If you format it like this:
{(this.props.schema.collectionName.length < 0 ?
(<Expandable></Expandable>)
: (<h1>hejsan</h1>)
)}
Hope this works!
Execute one of the following:
flutter upgrade
flutter pub get
flutter packages get
Whenever slicing (a:n
) can be used, it can be replaced by fancy indexing (e.g. [a,b,c,...,n]
). Fancy indexing is nothing more than listing explicitly all the index values instead of specifying only the limits.
Whenever fancy indexing can be used, it can be replaced by a list of Boolean values (a mask) the same size than the index. The value will be True
for index values that would have been included in the fancy index, and False
for the values that would have been excluded. It's another way of listing some index values, but which can be easily automated in NumPy and Pandas, e.g by a logical comparison (like in your case).
The second replacement possibility is the one used in your example. In:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
the mask
iris_data['class'] == 'versicolor'
is a replacement for a long and silly fancy index which would be list of row numbers where class
column (a Series) has the value versicolor
.
Whether a Boolean mask appears within a .iloc
or .loc
(e.g. df.loc[mask]
) indexer or directly as the index (e.g. df[mask]
) depends on wether a slice is allowed as a direct index. Such cases are shown in the following indexer cheat-sheet:
More correct create DTO for API queries, for example entityDTO:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityDto> getAll() { return entityService.getAllEntities(); }
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getOneParameterMap() { return ResponseEntity.status(HttpStatus.CREATED).body( Collections.singletonMap("key", "value")); }
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getSomeParameters() { return ResponseEntity.status(HttpStatus.OK).body(Map.of( "key-1", "value-1", "key-2", "value-2", "key-3", "value-3")); }
In my case the imports of real routes in app.component.spec.ts
were causing these error messages. Solution was to import RouterTestingModule
instead.
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [RouterTestingModule]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
console.log(fixture);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
Pipes in Angular 2+ are a great way to transform and format data right from your templates.
Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.
List of Built-in Pipes from API List Examples
{{ user.name | uppercase }}
Example of Angular version 4.4.7. ng version
Custom Pipes which accepts multiple arguments.
HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS « transform(json: any[], args: any[]) : any[] { ... }
Filtering the content using a Pipe « json-filter-by.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]) : any[] {
var searchText = args[0];
var jsonKey = args[1];
// json = undefined, args = (2) [undefined, "name"]
if(searchText == null || searchText == 'undefined') return json;
if(jsonKey == null || jsonKey == 'undefined') return json;
// Copy all objects of original array into new Array.
var returnObjects = json;
json.forEach( function ( filterObjectEntery ) {
if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
console.log('Search key is available in JSON object.');
if ( typeof filterObjectEntery[jsonKey] != "undefined" &&
filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
} else {
// object didn't match a filter value so remove it from array via filter
returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
}
} else {
console.log('Search key is not available in JSON object.');
}
})
return returnObjects;
}
}
Add to @NgModule
« Add JsonFilterByPipe
to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy
. If you add to module then it is available to all the component's of that module.
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule, ReactiveFormsModule,
],
providers: [ StudentDetailsService ],
declarations: [
UsersComponent, UserComponent,
JsonFilterByPipe,
],
exports : [UsersComponent, UserComponent]
})
export class UsersModule {
// ...
}
File Name: users.component.ts
and StudentDetailsService
is created from this link.
import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: [ './users.component.css' ],
providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy {
students: MyStudents[];
selectedStudent: MyStudents;
constructor(private studentService: StudentDetailsService) { }
ngOnInit(): void {
this.loadAllUsers();
}
ngOnDestroy(): void {
// ONDestroy to prevent memory leaks
}
loadAllUsers(): void {
this.studentService.getStudentsList().then(students => this.students = students);
}
onSelect(student: MyStudents): void {
this.selectedStudent = student;
}
}
File Name: users.component.html
<div>
<br />
<div class="form-group">
<div class="col-md-6" >
Filter by Name:
<input type="text" [(ngModel)]="searchText"
class="form-control" placeholder="Search By Category" />
</div>
</div>
<h2>Present are Students</h2>
<ul class="students">
<li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
<a *ngIf="student" routerLink="/users/update/{{student.id}}">
<span class="badge">{{student.id}}</span> {{student.name | uppercase}}
</a>
</li>
</ul>
</div>
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
If you run your playbook with ansible-playbook -vvv
you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).
I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this
# fails
- name: Add all instance public IPs to host group
add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
loop: "{{ ec2.instances }}"
but that fails too.
So this is not an answer. Just some debugging help and things not to try.
Worked by lowering the spring boot starter parent to 1.5.13
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
I faced same issue on Linux when I installed docker using yum (yum install docker).
Resolution: download docker binary from official site: docker install, unpack and follow the installation steps.
In my case, Android Studio 3.0.1, I fixed the issue with the following two steps.
Step 1: Change Gradle plugin version in project-level build.gradle
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
Step 2: Change gradle version
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
Thank you Hero Editor example, where I found the correct definition:
When I generate app routing module:
ng generate module app-routing --flat --module=app
and update the app-routing.ts file to add:
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
Here are the full example:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
and add AppRoutingModule into app.module.ts imports:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [...],
bootstrap: [AppComponent]
})
I found the solution.
Variable value should be C:\Users\dipanwita.neogy\Anaconda3\Scripts
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
I use the following piece of CSS and JavaScript. It uses an extra class dropdown-submenu
. I tested it with Bootstrap 4 beta.
It supports multi level sub menus.
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {_x000D_
if (!$(this).next().hasClass('show')) {_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
}_x000D_
var $subMenu = $(this).next('.dropdown-menu');_x000D_
$subMenu.toggleClass('show');_x000D_
_x000D_
_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass('show');_x000D_
});_x000D_
_x000D_
_x000D_
return false;_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu a::after {_x000D_
transform: rotate(-90deg);_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: .8em;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
margin-left: .1rem;_x000D_
margin-right: .1rem;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
Using the code example below will return to you the bitmap :
BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))
After that you all know what you have to do.
I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.
create json folder in resources as subfolder then add json file in folder then you can use this code :
import com.fasterxml.jackson.core.type.TypeReference;
InputStream is = TypeReference.class.getResourceAsStream("/json/fcmgoogletoken.json");
this works in Docker.
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
Since Bootstrap 3 doesn't have a style for checkboxes I found a custom made that goes really well with Bootstrap style.
.checkbox label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="">_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled checkbox -->_x000D_
<div class="checkbox disabled">_x000D_
<label>_x000D_
<input type="checkbox" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 13%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled radio -->_x000D_
<div class="radio disabled">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
You can choose your own icon between the ones from Bootstrap or Font Awesome by changing [icon name]
with your icon.
<span class="cr"><i class="cr-icon [icon name]"></i>
For example:
glyphicon glyphicon-remove
for Bootstrap, orfa fa-bullseye
for Font Awesome.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-remove"></i></span>_x000D_
Bootstrap - Custom icon checkbox_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio checked by default_x000D_
</label>_x000D_
</div>_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio_x000D_
</label>_x000D_
</div>
_x000D_
try:
this.navItems = this.http.get("data/navItems.json");
Since Django 2.x, on_delete
is required.
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
Creating an array or tuple of keys from an interface with safety compile-time checks requires a bit of creativity. Types are erased at run-time and object types (unordered, named) cannot be converted to tuple types (ordered, unnamed) without resorting to non-supported techniques.
The here proposed variants all consider/trigger a compile error in case of duplicate or missing tuple items given a reference object type like IMyTable
. For example declaring an array type of (keyof IMyTable)[]
cannot catch these errors.
In addition, they don't require a specific library (last variant uses ts-morph
, which I would consider a generic compiler wrapper), emit a tuple type as opposed to an object (only first solution creates an array) or wide array type (compare to these answers) and lastly don't need classes.
// Record type ensures, we have no double or missing keys, values can be neglected
function createKeys(keyRecord: Record<keyof IMyTable, any>): (keyof IMyTable)[] {
return Object.keys(keyRecord) as any
}
const keys = createKeys({ isDeleted: 1, createdAt: 1, title: 1, id: 1 })
// const keys: ("id" | "title" | "createdAt" | "isDeleted")[]
+
easiest +-
manual with auto-completion -
array, no tuple
If you don't like creating a record, take a look at this alternative with Set
and assertion types.
function createKeys<T extends readonly (keyof IMyTable)[] | [keyof IMyTable]>(
t: T & CheckMissing<T, IMyTable> & CheckDuplicate<T>): T {
return t
}
+
tuple +-
manual with auto-completion +-
more advanced, complex types
createKeys
does compile-time checks by merging the function parameter type with additional assertion types, that emit an error for not suitable input. (keyof IMyTable)[] | [keyof IMyTable]
is a "black magic" way to force inference of a tuple instead of an array from the callee side. Alternatively, you can use const assertions / as const
from caller side.
CheckMissing
checks, if T
misses keys from U
:
type CheckMissing<T extends readonly any[], U extends Record<string, any>> = {
[K in keyof U]: K extends T[number] ? never : K
}[keyof U] extends never ? T : T & "Error: missing keys"
type T1 = CheckMissing<["p1"], {p1:any, p2:any}> //["p1"] & "Error: missing keys"
type T2 = CheckMissing<["p1", "p2"], { p1: any, p2: any }> // ["p1", "p2"]
Note: T & "Error: missing keys"
is just for nice IDE errors. You could also write never
. CheckDuplicates
checks double tuple items:
type CheckDuplicate<T extends readonly any[]> = {
[P1 in keyof T]: "_flag_" extends
{ [P2 in keyof T]: P2 extends P1 ? never :
T[P2] extends T[P1] ? "_flag_" : never }[keyof T] ?
[T[P1], "Error: duplicate"] : T[P1]
}
type T3 = CheckDuplicate<[1, 2, 3]> // [1, 2, 3]
type T4 = CheckDuplicate<[1, 2, 1]>
// [[1, "Error: duplicate"], 2, [1, "Error: duplicate"]]
Note: More infos on unique item checks in tuples are in this post. With TS 4.1, we also can name missing keys in the error string - take a look at this Playground.
With version 4.1, TypeScript officially supports conditional recursive types, which can be potentially used here as well. Though, the type computation is expensive due to combinatory complexity - performance degrades massively for more than 5-6 items. I list this alternative for completeness (Playground):
type Prepend<T, U extends any[]> = [T, ...U] // TS 4.0 variadic tuples
type Keys<T extends Record<string, any>> = Keys_<T, []>
type Keys_<T extends Record<string, any>, U extends PropertyKey[]> =
{
[P in keyof T]: {} extends Omit<T, P> ? [P] : Prepend<P, Keys_<Omit<T, P>, U>>
}[keyof T]
const t1: Keys<IMyTable> = ["createdAt", "isDeleted", "id", "title"] // ?
+
tuple +-
manual with auto-completion +
no helper function --
performance
ts-morph is chosen here, as it is a tad simpler wrapper alternative to the original TS compiler API. Of course, you can also use the compiler API directly. Let's look at the generator code:
// ./src/mybuildstep.ts
import {Project, VariableDeclarationKind, InterfaceDeclaration } from "ts-morph";
const project = new Project();
// source file with IMyTable interface
const sourceFile = project.addSourceFileAtPath("./src/IMyTable.ts");
// target file to write the keys string array to
const destFile = project.createSourceFile("./src/generated/IMyTable-keys.ts", "", {
overwrite: true // overwrite if exists
});
function createKeys(node: InterfaceDeclaration) {
const allKeys = node.getProperties().map(p => p.getName());
destFile.addVariableStatement({
declarationKind: VariableDeclarationKind.Const,
declarations: [{
name: "keys",
initializer: writer =>
writer.write(`${JSON.stringify(allKeys)} as const`)
}]
});
}
createKeys(sourceFile.getInterface("IMyTable")!);
destFile.saveSync(); // flush all changes and write to disk
After we compile and run this file with tsc && node dist/mybuildstep.js
, a file ./src/generated/IMyTable-keys.ts
with following content is generated:
// ./src/generated/IMyTable-keys.ts
const keys = ["id","title","createdAt","isDeleted"] as const;
+
auto-generating solution +
scalable for multiple properties +
no helper function +
tuple -
extra build-step -
needs familiarity with compiler API
There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:
const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;
You can check at runtime if the value is valid and if not throw an error, i.e.:
function isToDoDto(obj: any): obj is IToDoDto {
return typeof obj.description === "string" && typeof obj.status === "boolean";
}
@Post()
addToDo(@Response() res, @Request() req) {
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
const toDo = req.body as IToDoDto;
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
As @huyz pointed out, there's no need for the type assertion because isToDoDto
is a type guard, so this should be enough:
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
this.toDoService.addToDo(req.body);
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
Use restart: always in your docker compose file.
Docker-compose up -d
will launch container from images again. Use docker-compose start
to start the stopped containers, it never launches new containers from images.
nginx:
restart: always
image: nginx
ports:
- "80:80"
- "443:443" links:
- other_container:other_container
Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.
The more secure option would be to add allowedHosts to your Webpack config like this:
module.exports = {
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
The array contains all allowed host, you can also specify subdomians. check out more here
IN Angular 4. This error is considered as ng serve run time cache issue.
case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.
case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.
if ( params.build_deploy == '1' ) {
println "build_deploy ? ${params.build_deploy}"
jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
string(name:'environment', value: "${params.environment}"),
string(name:'branch_name', value: "${params.branch_name}"),
string(name:'service_name', value: "${params.service_name}"),
]
println jobB.getResult()
}
In my condition when I got an exception " Unable to start embedded Tomcat servlet container",
I opened the debug mode of spring boot by adding debug=true
in the application.properties,
and then rerun the code ,and it told me that java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String
Thus, we know that probably I'm using a servlet API of lower version, and it conflicts with spring boot version.
I went to my pom.xml, and found one of my dependencies is using servlet2.5, and I excluded it.
Now it works. Hope it helps.
Run the following command in your project i.e npm install [email protected] --save
After installing the above dependency run the following npm command which will install the bootstrap module npm install --save @ng-bootstrap/ng-bootstrap
Check this out for the reference - https://github.com/ng-bootstrap/ng-bootstrap
Add the following import into app.module import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; and add NgbModule to the imports
In your stye.css @import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
In my case in Angular-5, service file was not imported from which i was accessing the method and subscribing the data.After importing service file it worked fine.
Removed and added back in the table using Scaffold-DbContext and the error went away
npm install font-awesome --save
add ~/ before path
@import "~/font-awesome/scss/font-awesome.scss";
Update 2019 - Bootstrap v4.1+
Here's a much more simple way to change the navbar background color.
Just use .navbar-dark
instead of .navbar-light
and add your custom background color class like .bg-company-red
.navbar-dark
will make all your links white.
HTML
<nav class="navbar navbar-dark bg-company-red">
CSS style...
.bg-company-red {
background-color: darkred !important;
}
See http://getbootstrap.com/docs/4.1/components/navbar/#color-schemes for official documentation.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Removing print statements can also fix the problem.
Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.
/
starts from the root only, to get the relative path we should use ./
or ../
The error for me was:
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:percent:26.0.2] AndroidManifest.xml:25:13-35
is also present at [com.android.support:support-v4:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:23:9-25:38 to override.
The solution for me was in my project Gradle file I needed to bump my com.google.gms:google-services version.
I was using version 3.1.1:
classpath 'com.google.gms:google-services:3.1.1
And the error resolved after I bumped it to version 3.2.1:
classpath 'com.google.gms:google-services:3.2.1
I had just upgraded all my libraries to the latest including v27.1.1 of all the support libraries and v15.0.0 of all the Firebase libraries when I saw the error.
After going through so many links and threads and getting frustrated over and over again, I went to the basics and boom! it helped. I simply did:
npm install
I don't know, but it might help someone :)
In case, if you need a no jquery solution
<label class="custom-file">
<input type="file" id="myfile" class="custom-file-input" onchange="this.nextElementSibling.innerText = this.files[0].name">
<span class="custom-file-control"></span>
</label>
img
in the center of its parent.img
is an inline element, text-center
aligns inline elements in the center of its container should the container be a block
element. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col text-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
mx-auto
centers block
elements. In order to so, change display
of the img from inline
to block
with d-block
class. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
d-flex
and justify-content-center
on its parent. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col d-flex justify-content-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Although it's a long time after this question is being asked since I was searching so much for the same problem and couldn't find the extant solutions helpful, I write what fixed my trouble for anyone with the same issue:
The point is, Jupyter should be installed in your virtual environment, meaning, after activating the tensorflow
environment, run the following in the command prompt (in tensorflow
virtual environment):
conda install jupyter
jupyter notebook
and then the jupyter will pop up.
Hope this helps for item #2: a) You can sort by total bill then reset the index to this column b) Use palette="Blue" to use this color to scale your chart from light blue to dark blue (if dark blue to light blue then use palette="Blues_d")
import pandas as pd
import seaborn as sns
%matplotlib inline
df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',')
groupedvalues=df.groupby('day').sum().reset_index()
groupedvalues=groupedvalues.sort_values('total_bill').reset_index()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette="Blues")
for i in range(100):
try:
#Your code here
break
except:
continue
This one worked for me.
Adding this configuration in application.properties file to fixed this issue easily.
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
You're going to want to use the Redirect
component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed
prop and then renders based on that props.
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
Now your Route
s can look something like this
<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />
If you're still confused, I wrote this post that may help - Protected routes and authentication with React Router v4
For some ASP.NET projects import
and export
may not be used at all in your Typescripts.
The question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so:
<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>
For those who are experiencing same problem after controlling there is no suspicious java process which allocate the port, there is no red square on eclipse to terminate any process and also there is no change even you try different port for your spring boot application.
might sound stupid but; restarting eclipse works. :)
pathMatch = 'full'
results in a route hit when the remaining, unmatched segments of the URL match is the prefix path
pathMatch = 'prefix'
tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.
Ref: https://angular.io/guide/router#set-up-redirects
pathMatch: 'full'
means, that the whole URL path needs to match and is consumed by the route matching algorithm.
pathMatch: 'prefix'
means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.
In my case none of the above solutions didn't help:
Root cause: incompatible version of gcc
Solution:
1. sudo apt install --reinstall gcc
2. sudo apt-get --purge -y remove 'nvidia*'
3 sudo apt install nvidia-driver-450
4. sudo reboot
System: AWS EC2 18.04 instance
Solution source: https://forums.developer.nvidia.com/t/nvidia-smi-has-failed-in-ubuntu-18-04/68288/4
Bootstrap 3
You can create or just override default bootstrap modal-lg
by doing below:
.modal-lg {
max-width: 80%;
}
If not working just add !important
so it would look like below
.modal-lg {
max-width: 80% !important;
}
Now call the modal-lg
.
<div class="modal-dialog modal-lg" role="document">
<!-- some modal content --->
</div
For Bootstrap 4 refer to @kitsu.eb answer. Also note that using bootstrap 4 utilities might break the responsiveness.
Anyone who is still stuck - follow the instructions on this page.
Basically:
Follow the steps as initially described by AWS.
source activate python3
Don't cut and paste anything. Instead open a new terminal window without closing the first one.
In the new window enter enter the SSH command as described in the above link.
Open a web browser and go to http://127.0.0.1:8157
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):
RouterModule.forRoot([{ path: "", component: LoginComponent}])
It's quite simple, really. I got this issue when I started coding React, and the problem is almost always because the import:
import React, { memo } from 'react';
You can use destructuring this because react lib has a property as memo, but you can not destructuring something like this
import { user } from 'assets/images/icons/Profile.svg';
because it's not a object.
Hope it helps!
In Command prompt go to project folder and execute following:
ng g s servicename
jupyter kernelspec remove
now exists, see #7934.
So you can just.
# List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
# Remove it
jupyter kernelspec remove <kernel_name>
That's it.
you can find if one has been initialized by comparing the references with the default instance:
GRPCContainer container = myGrpcResponseBean.getContainer();
if (container.getDefaultInstanceForType() != container) {
...
}
just insert class navbar-dark
or navbar-light
in the nav element:
<nav class="navbar navbar-dark navbar-expand-md">
<button class="navbar-toggler">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
You just have to use class="row-eq-height"
with your class="row"
to get equal height columns for previous bootstrap versions.
but with bootstrap 4 this comes natively.
check this link --http://getbootstrap.com.vn/examples/equal-height-columns/
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col d-flex justify-content-center">_x000D_
CenterContent_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Enable 'flex' for the column as we want & use justify-content-center
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
The easiest way to do it using only Angular 2/4 template with no coding:
<nav class="navbar navbar-default" aria-expanded="false">
<div class="container-wrapper">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
<ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
</ul>
</div>
</div>
</nav>
Static files should be served from resources, not from controller.
Spring Boot will automatically add static web resources located within any of the following directories:
/META-INF/resources/ /resources/ /static/ /public/
refs:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/
Or rather easily:
mvn spring-boot:run -Dspring-boot.run.profiles={profile_name}
You need something to center your form into. But because you didn't specify a height for your html and body, it would just wrap content - and not the viewport. In other words, there was no room where to center the item in.
html, body {
height: 100%;
}
.container, .row.justify-content-center.align-items-center {
height: 100%;
min-height: 100%;
}
It just simple just force all v7 and v4 libraries to use the library version you have set just before your dependencies.
configurations.all {
// To resolve the conflict for com.android.databinding
// dependency on support-v4:21.0.3
resolutionStrategy.force 'com.android.support:support-v4:28.0.0'
resolutionStrategy.force 'com.android.support:support-v7:28.0.0'
}
You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>
# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()
If you want to preserve all existing sheets, you can replace above code between begin and end with:
# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
df = xlsx.parse(sheet_name=sheet, index_col=0)
df.to_excel(writer, sheet_name=sheet)
Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;
Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<POJO>>() {
});
List<POJO> pojoObjList = responseEntity.getBody();
Happy Coding :)
first()
if:If there are zero emissions and you are not explicitly handling it (with catchError
) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.
You're safer off using take(1)
for the most part provided that:
take(1)
not emitting anything if the source completes without an emission.first(x => x > 10)
)Note: You can use a predicate with take(1)
like this: .pipe( filter(x => x > 10), take(1) )
. There is no error with this if nothing is ever greater than 10.
single()
If you want to be even stricter, and disallow two emissions you can use single()
which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.
Tip: Single
can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single
to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError()
to guarantee good behavior.
first()
instead of take(1)
?aka. How can first
potentially cause more errors?
If you have an observable that takes something from a service and then pipes it through first()
you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null)
or NEVER
then any downstream first()
operators would start throwing errors.
Now I realize that might be exactly what you want - hence why this is just a tip. The operator first
appealed to me because it sounded slightly less 'clumsy' than take(1)
but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.
Consider also .pipe(defaultIfEmpty(42), first())
if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first
would always receive a value.
Note that defaultIfEmpty
is only triggered if the stream is empty, not if the value of what is emitted is null
.
I was also facing same issue .
root@*******:/root >mysql -uroot -password
mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I found ROOT FS was also full and then I killed below lock session .
root@**********:/var/lib/mysql >ls -ltr
total 0
-rw------- 1 mysql mysql 0 Sep 9 06:41 mysql.sock.lock
Finally Issue solved .
The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
Since unpaidMembers
is a dictionary it always returns two values when called with .items()
- (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..]
.
use .my-auto
(bootsrap4) css class on yor div
"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript
and took 83ms of runtime
are alerting you there's probably an opportunity to speed up your script.
("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)
None of the above works for me. I find that running the following sorts this issue after error (It just clears all the instances of progress bars in the background):
from tqdm import tqdm
# blah blah your code errored
tqdm._instances.clear()
Neither of the top solutions worked for me.
This works perfectly, keeps submenus open while browsing, add uses the native Bootstrap javascript.
// Mouse over
$('body').on('mouseover', '.dropdown', function(e) {
$(this).children('.dropdown-toggle').dropdown('show');
});
// Mouse leave
$('body').on('mouseleave', '.dropdown', function(e) {
$(this).children('.dropdown-toggle').dropdown('hide');
});
In the %run
magic documentation you can find:
-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.
Therefore, supplying -i
does the trick:
%run -i 'script.py'
The "correct" way to do it
Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x
variable come from? and what is the f
function?).
I'd like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you're constantly editing the other file, then autoreload
comes to your help.
Your example would look like this:
script.py
import matplotlib.pyplot as plt
def myplot(f, x):
"""
:param f: function to plot
:type f: callable
:param x: values for x
:type x: list or ndarray
Plots the function f(x).
"""
# yes, you can pass functions around as if
# they were ordinary variables (they are)
plt.plot(x, f(x))
plt.xlabel("Eje $x$",fontsize=16)
plt.ylabel("$f(x)$",fontsize=16)
plt.title("Funcion $f(x)$")
Jupyter console
In [1]: import numpy as np
In [2]: %load_ext autoreload
In [3]: %autoreload 1
In [4]: %aimport script
In [5]: def f(x):
: return np.exp(-x ** 2)
:
:
In [6]: x = np.linspace(-1, 3, 100)
In [7]: script.myplot(f, x)
In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File: [...]\script.py
Type: function
Use bases if you just want to get the parents, use __mro__
(as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).
Bases (and first getting the class for an existing object):
>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)
For mro in recent Python versions:
>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)
Obviously, when you already have a class definition, you can just call __mro__
on that directly:
>>> class A(): pass
>>> A.__mro__
(__main__.A, object)
The question mark is the conditional operator. The code means that if f==r then 1 is returned, otherwise, return 0. The code could be rewritten as
int qempty()
{
if(f==r)
return 1;
else
return 0;
}
which is probably not the cleanest way to do it, but hopefully helps your understanding.
From: https://developer.android.com/tools/support-library/setup.html#libs-with-res
Adding libraries with resources To add a Support Library with resources (such as v7 appcompat for action bar) to your application project:
Using Eclipse
Create a library project based on the support library code:
Make sure you have downloaded the Android Support Library using the SDK Manager.
Create a library project and ensure the required JAR files are included in the project's build path:
Select File > Import.
Select Existing Android Code Into Workspace and click Next.
Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to /extras/android/support/v7/appcompat/.
Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat.
In the new library project, expand the libs/ folder, right-click each .jar file and select Build
Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path.
Right-click the library project folder and select Build Path > Configure Build Path.
In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files.
Uncheck Android Dependencies.
Click OK to complete the changes.
You now have a library project for your selected Support Library that you can use with one or more application projects.
Add the library to your application project:
In the Project Explorer, right-click your project and select Properties.
In the category panel on the left side of the dialog, select Android.
In the Library pane, click the Add button.
Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat.
In the properties window, click OK.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:
mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'
If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:
import timeit
mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'
timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000)
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
As of jQuery 1.5, there is a headers
hash you can pass in as follows:
$.ajax({
url: "/test",
headers: {"X-Test-Header": "test-value"}
});
From http://api.jquery.com/jQuery.ajax:
headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
U+2304 DOWN ARROWHEAD, in HTML as ⌄
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
Something to extend print function for loops
x = 0
while x <=5:
x = x + 1
with open('outputEis.txt', 'a') as f:
print(x, file=f)
f.close()
There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.
There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello "world""
), and even then, there are almost always better options (like title='Hello "word"'
or title="Hello “word”"
.
If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like "
to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
I dont understand why nobody mention the easiest way....just split the large file with http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ and after just execute vie mySQL admin the seperated generated files starting from the one with Structure
This is a bug in Firefox:
https://bugzilla.mozilla.org/show_bug.cgi?id=356558
Try this workaround:
<iframe src="webpage2.html?var=xxx" id="theframe"></iframe>
<script>
var _theframe = document.getElementById("theframe");
_theframe.contentWindow.location.href = _theframe.src;
</script>
You could also use this:
ini_alter('date.timezone','Asia/Calcutta');
You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.
I had done these things before I figured out this:
date_default_timezone_set("Asia/Calcutta");
- did not workini_alter()
- IT WORKEDdate_default_timezone_set("Asia/Calcutta");
- IT WORKEDFor me the init_alter()
method got it all working.
I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion
In AndroidManifest.xml
, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
in application
tag.
Individual activities can override the default by setting their own theme attributes.
public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}
Rake::Task['reklamer:orville'].invoke
or
Rake::Task['reklamer:orville'].invoke(args)
Linux Pipes
First In First Out (FIFO) interproccess communication mechanism.
Unnamed Pipes
On the command line, represented by a "|" between two commands.
Named Pipes
A FIFO special file. Once created, you can use the pipe just like a normal file(open, close, write, read, etc).
To create a named pipe, called "myPipe", from the command line (man page):
mkfifo myPipe
To create a named pipe from c, where "pathname" is the name you would like the pipe to have and "mode" contains the permissions you want the pipe to have (man page):
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01
to 9999-12-31
.
DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00
to 9999-12-31 23:59:59
.
TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01
UTC to 2038-01-19 03:14:07
UTC.
TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59
to 838:59:59
. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
If you want to use them like that, define the function with the variable names as normal:
def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name
Now you can use **
when you call the function:
data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(**data)
and it will work as you want.
P.S. Don't use reserved words such as class
.(e.g., use klass
instead)
You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
expression.
(1) If all you need is the difference between two instants in seconds, the very simple time.time()
does the job.
(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:
gmtime()
returns a time tuple in UTC but mktime()
expects a time tuple in local time.
I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31
>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time
You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow()
which won't jump by an hour when DST goes on/off and may give you more precision than time.time()
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
Also, you can see the build dependencies in the file setup.cfg
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
The best way is to use:
$("#yourid option:selected").text();
Depending on the requirement, you could also use this way:
var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
They changed print
in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.
Here's the docs from Python 3.0.
Maybe it helps someone too:)
I'm not allowed to post images, so here goes extra link to my blog. Sorry.
IIS webpage by using IP address
In IIS Management : Choose Site, then Bindings.
Add
Object class has toString method. All other classes extending it overrides the toString method so in for arrays also toString is overrided in this way. So if you want your output in your way you need to create your own method by which you will get your desired result.
str="";
for (Integer i:arr){
str+=i.toString();
}
Hope this helps
refer Why does the toString method in java not seem to work for an array
[0]=> string(141)
means that $message is an array, not string, and $message[0] is a string with 141 characters in length.
As mentioned before, the easiest way it to use rotation
available since API 11:
android:rotation="90" // in XML layout
view.rotation = 90f // programatically
You can also change pivot of rotation, which is by default set to center of the view. This needs to be changed programatically:
// top left
view.pivotX = 0f
view.pivotY = 0f
// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()
...
In Activity's onCreate()
or Fragment's onCreateView(...)
width and height are equal to 0, because the view wasn't measured yet. You can access it simply by using doOnPreDraw
extension from Android KTX, i.e.:
view.apply {
doOnPreDraw {
pivotX = width.toFloat()
pivotY = height.toFloat()
}
}
You can use [DisplayMatrics][1]
and determine the screen density. Something like this:
int pixelsValue = 5; // margin in pixels
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(pixelsValue * d);
As I remember it's better to use flooring for offsets and rounding for widths.
As a note, depending upon the property you may be able to set it to auto.
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
Edit : See jme's answer for the best way with Python3.
Using pathlib, you have the following solution :
Let's say we want to check if son
is a descendant of parent
, and both are Path
objects.
We can get a list of the parts in the path with list(parent.parts)
.
Then, we just check that the begining of the son is equal to the list of segments of the parent.
>>> lparent = list(parent.parts)
>>> lson = list(son.parts)
>>> if lson[:len(lparent)] == lparent:
>>> ... #parent is a parent of son :)
If you want to get the remaining part, you can just do
>>> ''.join(lson[len(lparent):])
It's a string, but you can of course use it as a constructor of an other Path object.
ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
// To dismiss the dialog
progress.dismiss();
OR
ProgressDialog.show(this, "Loading", "Wait while loading...");
By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
Another way to generate the serialVersionUID is to use >Analyze >Run Inspection by Name
from the context menu ( or the keyboard short cut, which is ctrl+alt+shift+i by default) and then type "Serializable class without 'serialVersionUID'" (or simply type "serialVersionUID" and the type ahead function will find it for you.
You will then get a context menu where you can choose where to run the inspections on (e.g. all from a specific module, whole project, one file, ...)
With this approach you don't even have to set the general inspection rules to anything.
I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.
Dim d As DateTime = Now
Debug.WriteLine(d.ToLongDateString)
Debug.WriteLine(d.ToShortDateString)
Debug.WriteLine(d.ToString("d"))
Debug.WriteLine(d.ToString("yyyy-MM-dd"))
Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10
Note that these results will vary depending on the culture settings on your computer.
I managed to use a one-line Ruby script for that purpose (although it had to go in a separate file). First, run these commands once on each client machine you'll be pushing docs from:
gem install github-markup
gem install commonmarker
Next, install this script in your client image, and call it render-readme-for-javadoc.rb
:
require 'github/markup'
puts GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, File.read('README.md'))
Finally, invoke it like this:
ruby ./render-readme-for-javadoc.rb >> project/src/main/javadoc/overview.html
ETA: This won't help you with StackOverflow-flavor Markdown, which seems to be failing on this answer.
hack but works - (tested on chrome and mobile)
just add no break spaces till it breaks - you might have to limit the tooltip size depending on the amount of content but for small text messages this works:
etc
Tried everything above and this is the only thing that worked for me -
I've found out the problem.
I'm using a Windows computer which has Python 2 installed previously. After Python 3 is installed (without setting the path, I successfully check the version of pip3 - but the python executable file still points to the Python2)
Then I set the path to the python3 executable file (remove all python2 paths) then start a new command prompt, try to reinstall Tensorflow. It works!
I think this problem could happend on MAC OS too since there is a default python which is on the MAC system.
Using this way You will do a endless Loop on Your JS. to do a better way you can use the following
var on_submit_function = function(evt){
evt.preventDefault(); //The form wouln't be submitted Yet.
(...yourcode...)
$(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
$(this).submit();
}
$('form').on('submit', on_submit_function); //Registering on submit.
I hope it helps! Thanks!
Imports System.Data
Imports System.Data.SqlClient
Public Class Form2
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")
'you need to provide password for sql server
myconnection.Open()
mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myconnection.Close()
End Sub
End Class
Try this one:
p.pos_fixed {
position:fixed;
top:30px;
right:5px;
}
Just use this for the closing tag:
@:</tr>
And leave your if/else as is.
Seems like the if statement doesn't wanna' work.
It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.
The best date utility I've used is date-fns for a few reasons:
Date
format.Package manager:
"date-fns": "^1.30.1"
Code:
import { addDays, subDays } from 'date-fns'
let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)
Simple and awesome.
Here's a pretty ggplot2 solution:
library(ggplot2)
library(scales) # makes pretty labels on the x-axis
breaks=c(0,1,2,3,4,5,25)
ggplot(mydata,aes(x = V3)) +
geom_histogram(breaks = log10(breaks)) +
scale_x_log10(
breaks = breaks,
labels = scales::trans_format("log10", scales::math_format(10^.x))
)
Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10
in PHP
$set=array('A','B','C','D');
function permutate($set) {
$b=array();
foreach($set as $key=>$value) {
if(count($set)==1) {
$b[]=$set[$key];
}
else {
$subset=$set;
unset($subset[$key]);
$x=permutate($subset);
foreach($x as $key1=>$value1) {
$b[]=$value.' '.$value1;
}
}
}
return $b;
}
$x=permutate($set);
var_export($x);
All error codes are on "CFNetwork Errors Codes References" on the documentation (link)
A small extraction for CFURL and CFURLConnection Errors:
kCFURLErrorUnknown = -998,
kCFURLErrorCancelled = -999,
kCFURLErrorBadURL = -1000,
kCFURLErrorTimedOut = -1001,
kCFURLErrorUnsupportedURL = -1002,
kCFURLErrorCannotFindHost = -1003,
kCFURLErrorCannotConnectToHost = -1004,
kCFURLErrorNetworkConnectionLost = -1005,
kCFURLErrorDNSLookupFailed = -1006,
kCFURLErrorHTTPTooManyRedirects = -1007,
kCFURLErrorResourceUnavailable = -1008,
kCFURLErrorNotConnectedToInternet = -1009,
kCFURLErrorRedirectToNonExistentLocation = -1010,
kCFURLErrorBadServerResponse = -1011,
kCFURLErrorUserCancelledAuthentication = -1012,
kCFURLErrorUserAuthenticationRequired = -1013,
kCFURLErrorZeroByteResource = -1014,
kCFURLErrorCannotDecodeRawData = -1015,
kCFURLErrorCannotDecodeContentData = -1016,
kCFURLErrorCannotParseResponse = -1017,
kCFURLErrorInternationalRoamingOff = -1018,
kCFURLErrorCallIsActive = -1019,
kCFURLErrorDataNotAllowed = -1020,
kCFURLErrorRequestBodyStreamExhausted = -1021,
kCFURLErrorFileDoesNotExist = -1100,
kCFURLErrorFileIsDirectory = -1101,
kCFURLErrorNoPermissionsToReadFile = -1102,
kCFURLErrorDataLengthExceedsMaximum = -1103,
If possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.
To set the @value
field you can use Springs ReflectionTestUtils
- it has a method setField
to set private fields.
@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)
I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.
In Python 2.7.3:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.
You can call generic methods with types only known at execution time, but you have to use reflection:
// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
.MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });
Ick.
Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?
If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.
You can center a box both vertically and horizontally, using the following technique :
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
If you use this technique, just add your table (along with any other content you want to go with it) to the content box.
body {_x000D_
margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
position : absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
display: inline-block;_x000D_
background: #fff;_x000D_
padding : 20px;_x000D_
border : 1px solid #000;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
<div class="inner-container">_x000D_
<div class="centered-content">_x000D_
<em>Data :</em>_x000D_
<table>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Age</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Tom</td>_x000D_
<td>15</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Anne</td>_x000D_
<td>15</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Gina</td>_x000D_
<td>34</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
Either of the first two would be acceptable to me. I would avoid the last one because it is relatively easy to introduce a bug by putting a space between the quotes. This particular bug would be difficult to find by observation. Assuming no typos, all are semantically equivalent.
[EDIT]
Also, you might want to always use either string
or String
for consistency, but that's just me.
Just define your and your close tag in same line.
<textarea class="form-control"
id="newText"
rows="6"
placeholder="Your placeholder here..."
required
name="newText"></textarea>
Just specifying the uri endpoint worked for me, bower 1.3.9
"dependencies": {
"jquery.cookie": "latest",
"everestjs": "http://www.everestjs.net/static/st.v2.js"
}
Running bower install
, I received following output:
bower new version for http://www.everestjs.net/static/st.v2.js#*
bower resolve http://www.everestjs.net/static/st.v2.js#*
bower download http://www.everestjs.net/static/st.v2.js
You could also try updating bower
npm update -g bower
According to documentation: the following types of urls are supported:
http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)
I use both <strong> and <b>, actually, for exactly the reasons mentioned in this thread of responses. There are times when bold-facing some text simply looks better, but it isn't, necessarily, semantically more important than the rest of the sentence. Here's an example from a page I'm working on right now:
"Retrieves <strong>all</strong> books about <b>lacrosse</b>."
In that sentence, the word "all" is very important, and "lacrosse" less so--I merely wanted it bold because it represents a search term, so I wanted some visual separation. If you're viewing the page with a screen reader, I really don't think it needs to go out of the way to emphasize the word "lacrosse".
I would tend to imagine that most web developers use one of the other, but both are fine--<b> is most definitely not deprecated, as some people have claimed. For me, it's just a fine line between visual appeal and meaning.
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
If column datatype is text you should use DataLength function like:
select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc
You could use some CSS and with the idea of kbrimington it should do the trick.
The CSS could be like this.
img {
width: 75px;
height: auto;
}
I got it from here: another post
Add to pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
In your edit action, store the requesting url in the session hash, which is available across multiple requests:
session[:return_to] ||= request.referer
Then redirect to it in your update action, after a successful save:
redirect_to session.delete(:return_to)
I found easiest solution.
@XmlElement(name="attribute")
public String[] getAttributes(){
return attributes.keySet().toArray(new String[1]);
}
}
Now it will generate in you xml output like this:
<attribute>key1<attribute>
...
<attribute>keyN<attribute>
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
For code mirror divs refer to the manual, these sections might be useful to you:
http://codemirror.net/demo/fullscreen.html
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
theme: "night",
extraKeys: {
"F11": function(cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc": function(cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
}
}
});
And also take a look at:
http://codemirror.net/demo/resize.html
Also a comment:
Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.
Tried multiple solutions but the below sequence works for me.
Virtual Box: 5.2.34 Vagrant: 2.2.5 Mac OSX: 10.14.6
First Allow access to oracle inc:
Go to System Preferences > Security & Privacy Then hit the "Allow" button to let Oracle (VirtualBox) load.
Then restart VBox by this command:
sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart
Now try Vagrant up again.
No you can't they are different. When the app was deployed your controller mappings would be borked for example.
Why do you want to anyway, a controller is not a service, and vice versa.
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
You are missimg @ModelAttribute
annotation for UserProfessionalForm professionalForm
parameter in forgotPassword
method.
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("professional", professionalForm);
return "Your Professional Details Updated";
}
mine uses a single regex to look for cases where trimming is necessary, and uses that regex's results to determine desired substring bounds:
var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
var match= illmatch.exec(me)
if(match && (match[1].length || match[2].length)){
me= me.substring(match[1].length, p.length-match[2].length)
}
return me
}
the one design decision that went into this was using a substring to perform the final capture. s/\?:// (make the middle term capturing) and and the replacement fragment becomes:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
there's two performance bets I made in these impls:
does the substring implementation copy the original string's data? if so, in the first, when a string needs to be trimmed there is a double traversal, first in the regex (which may, hopefully be partial), and second in the substring extraction. hopefully a substring implementation only references the original string, so operations like substring can be nearly free. cross fingers
how good is the capture in the regex impl? the middle term, the output value, could potentially be very long. i wasn't ready to bank that all regex impls' capturing wouldn't balk at a couple hundred KB input capture, but i also did not test (too many runtimes, sorry!). the second ALWAYS runs a capture; if your engine can do this without taking a hit, perhaps using some of the above string-roping-techniques, for sure USE IT!
If you have some form data for example sent to home#action, now you want to redirect them to house#act while keeping the parameters, you can do this
redirect_to act_house_path(request.parameters)
For just a boolean match result or for a count of occurrences, you could use:
use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
my $count=map {m/^$str$/i} @foo;
if ($count) {
print "I found '$str' $count time(s) in '$patterns'\n";
} else {
print "I could not find '$str' in the pattern list\n"
};
}
Output:
I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.
If you want change background color on button click, you should use JavaScript function and change a style in the HTML page.
function chBackcolor(color) {
document.body.style.background = color;
}
It is a function in JavaScript for change color, and you will be call this function in your event, for example :
<input type="button" onclick="chBackcolor('red');">
I recommend to use jQuery for this.
If you want it only for some seconds, you can use setTimeout
function:
window.setTimeout("chBackColor()",10000);
The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.
Best way is to use NuGet package manager.
Just update the below MVC package and it should work.
You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:
as a stored mysql function:
CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT)
RETURNS decimal(10,7)
DETERMINISTIC
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF -
(s & 0x7FFFFFFF))) / 600000, s / 600000)
and back
CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7))
RETURNS int(10)
DETERMINISTIC
RETURN s * 600000
That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.
through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.
in php those 2 functions look like
function LatitudeSmallToFloat($LatitudeSmall){
if(($LatitudeSmall>0)&&($LatitudeSmall>>31))
$LatitudeSmall=-(0x7FFFFFFF-($LatitudeSmall&0x7FFFFFFF))-1;
return (float)$LatitudeSmall/(float)600000;
}
and back again:
function LatitudeFloatToSmall($LatitudeFloat){
$Latitude=round((float)$LatitudeFloat*(float)600000);
if($Latitude<0) $Latitude+=0xFFFFFFFF;
return $Latitude;
}
This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.
Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:
Create Table: CREATE TABLE `Locations` (
`lat` int(10) unsigned NOT NULL,
`lon` int(10) unsigned NOT NULL,
`location` text,
PRIMARY KEY (`lat`,`lon`) USING BTREE,
KEY `index_location` (`locationText`(30))
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY KEY ()
PARTITIONS 100 */
On one project where we had 4 environments (development, test, staging and production) we developed a system where the application selected the appropriate configuration based on the machine name it was deployed to.
This worked for us because:
It worked well for us in this instance, but probably wouldn't work everywhere.
awk "NR != `wc -l < text.file`" text.file |> text.file
This snippet does the trick.
Actually, the default directory where the mongod instance stores its data is
/data/db
on Linux and OS X,
\data\db
on Windows
To check the same, you can look for dbPath settings in mongodb configuration file.
/etc/mongod.conf
, if you have used package manager to install MongoDB.
Run the following command to check the specified directory:
grep dbpath /etc/mongodb.conf
<install directory>/bin/mongod.cfg
. Open mongod.cfg file and check for dbPath option./usr/local/etc/mongod.conf
when installing from MongoDB’s official Homebrew tap.The default mongod.conf configuration file included with package manager installations uses the following platform-specific default values for storage.dbPath
:
+--------------------------+-----------------+------------------------+
| Platform | Package Manager | Default storage.dbPath |
+--------------------------+-----------------+------------------------+
| RHEL / CentOS and Amazon | yum | /var/lib/mongo |
| SUSE | zypper | /var/lib/mongo |
| Ubuntu and Debian | apt | /var/lib/mongodb |
| macOS | brew | /usr/local/var/mongodb |
+--------------------------+-----------------+------------------------+
The storage.dbPath
setting in the configuration file is available only for mongod
.
The Linux package init scripts do not expect storage.dbPath
to change from the defaults. If you use the Linux packages and change storage.dbPath
, you will have to use your own init scripts and disable the built-in scripts.
What you could do is copy the code from tkinter.py
into a file called mytkinter.py
, then do this code:
import tkinter, mytkinter
root = tkinter.Tk()
window = mytkinter.Tk()
button = mytkinter.Button(window, text="Search", width = 7,
command=cmd)
button2 = tkinter.Button(root, text="Search", width = 7,
command=cmdtwo)
And you have two windows which don't collide!
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
You can use the filter_var()
function, which gives you a lot of handy validation and sanitization options.
filter_var($email, FILTER_VALIDATE_EMAIL)
Available in PHP >= 5.2.0
If you don't want to change your code that relied on your function, just do:
function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
Note: For other uses (where you need Regex), the deprecated ereg
function family (POSIX Regex Functions) should be replaced by the preg
family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.
Update 1: As pointed out by @binaryLV:
PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using
strlen()
beforefilter_var()
. I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.
This bug has already been fixed.
Update 2: This method will of course validate bazmega@kapa
as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]
. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var()
with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('/@.+\./', $email);
}
As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
Looks like Users that are added in your Country object, are not already present in the DB. You need to use cascade to make sure that when Country is persisted, all User which are not there in data but are associated with Country also get persisted.
Below code should help:
@ManyToOne (cascade = CascadeType.ALL)
@JoinColumn (name = "countryId")
private Country country;
Multiple commands can be put in parenthesis and spread over numerous lines; so something like echo hi && echo hello
can be put like this:
( echo hi
echo hello )
Also variables can help:
set AFILEPATH="C:\SOME\LONG\PATH\TO\A\FILE"
if exist %AFILEPATH% (
start "" /b %AFILEPATH% -option C:\PATH\TO\SETTING...
) else (
...
Also I noticed with carets (^
) that the if
conditionals liked them to follow only if a space was present:
if exist ^
I had the same issue. Fixed by adding a pom.xml in parent folder with <modules>
listed.
Came across the question myself today. I think the reason that your code returns 'None' (exactly what I got by using the same method) is that
a.sort()
is calling the sort function to mutate the list a. In my understanding, this is a modification command. To see the result you have to use print(a).
My solution, as I tried to keep everything in pandas:
pd.Series(df['A'].unique()).sort_values()
If you're using .Net 3.5, you can make cleaner code using:
foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
//dostuff
}
I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection)
is probably not the same as LargeCollection.Intersect(LookupCollection)
... the latter is probably much slower.
This assumes LookupCollection is a HashSet
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
this command posted by Daniel works like charm
C:\xampp\mysql\bin>mysql -u {DB_USER} -p {DB_NAME} < path/to/file/ab.sql
just put the db username and db name without those backets
**NOTE: Make sure your database file is reside inside the htdocs folder, else u'll get an Access denied error
If the file is coming off the disk and as others have stated, use the BaseName
and Extension
properties:
PS C:\> dir *.xlsx | select BaseName,Extension
BaseName Extension
-------- ---------
StackOverflow.com Test Config .xlsx
If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension
and GetExtension
static methods from the System.IO.Path class:
PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx
Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do
>>> x = "a (b) c (d) e"
>>> re.search(r"\((.*?)\)", x).group(1)
'b'
you don't need to pass any regular expression there. this works just fine..
(function($) {
$(document).ready(function() {
$('#data').click(function(e) {
e.preventDefault();
$.each($("#keywords").val().split("\n"), function(e, element) {
alert(element);
});
});
});
})(jQuery);
The issue is caused by this:
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
If the assertion fails, it will throw an error. This error will cause done()
never to get called, because the code errored out before it. That's what causes the timeout.
The "Unhandled promise rejection" is also caused by the failed assertion, because if an error is thrown in a catch()
handler, and there isn't a subsequent catch()
handler, the error will get swallowed (as explained in this article). The UnhandledPromiseRejectionWarning
warning is alerting you to this fact.
In general, if you want to test promise-based code in Mocha, you should rely on the fact that Mocha itself can handle promises already. You shouldn't use done()
, but instead, return a promise from your test. Mocha will then catch any errors itself.
Like this:
it('should transition with the correct event', () => {
...
return new Promise((resolve, reject) => {
...
}).then((state) => {
assert(state.action === 'DONE', 'should change state');
})
.catch((error) => {
assert.isNotOk(error,'Promise error');
});
});
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
Try this
INSERT INTO dbo.DB1.TempTable
(COLUMNS)
SELECT COLUMNS_IN_SAME_ORDER FROM dbo.DB2.TempTable
This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.
You can now do this without a third party library or a widget. It's built into TextView in API level 26. Add android:autoSizeTextType="uniform"
to your TextView
and set height to it. That's all. Use app:autoSizeTextType="uniform"
for backward compatibility
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:autoSizeTextType="uniform" />
You can also use TextViewCompat
for compatibility.
Solution using str_pad:
str_pad($digit,2,'0',STR_PAD_LEFT);
Benchmark on php 5.3
Result str_pad : 0.286863088608
Result sprintf : 0.234171152115
Code:
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
str_pad(9,2,'0',STR_PAD_LEFT);
str_pad(15,2,'0',STR_PAD_LEFT);
str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
sprintf("%02d", 9);
sprintf("%02d", 15);
sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";
Having a default structure of folders generated by Vue CLI such as src/assets
you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png">
as well (works automatically without any changes on deployment too).
def check_duplicates(my_list):
seen = {}
for item in my_list:
if seen.get(item):
return True
seen[item] = True
return False
import binascii
binascii.a2b_hex(hex_string)
Thats the way I did it.
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
for (int j = 0; j < adapterView.getChildCount(); j++)
adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
});
Perhaps you might want to save the current selected element in a global variable using the index i.
If (condition, condition_is_true, condition_is_false)
It will look like this in longer version:
If (condition_is_true) Then
Else (condition_is_false)
End If
$('.time-picker').timepicker({
showMeridian: false
});
This will work.
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
An alternative solution is described on Separate sentence to one word per line, by applying display:table-caption;
to the element
(I am developer of SSMSBoost add-in for SSMS)
We have recently added support for this syntax into our SSMSBoost add-in.
--#region [Optional Name]
--#endregion
It has also an option to automatically "recognize" regions when opening scripts.
The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked
category allows suppression of compiler warnings generated as a result of unchecked type casts.
MSDN has an article Working With Large Value Types, which tries to explain how the import parts work, but it can get a bit confusing since it does 2 things simultaneously.
Here I am providing a simplified version, broken into 2 parts. Assume the following simple table:
CREATE TABLE [Thumbnail](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Data] [varbinary](max) NULL
CONSTRAINT [PK_Thumbnail] PRIMARY KEY CLUSTERED
(
[Id] ASC
) ) ON [PRIMARY]
If you run (in SSMS):
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
it will show, that the result looks like a table with one column named BulkColumn
. That's why you can use it in INSERT like:
INSERT [Thumbnail] ( Data )
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
The rest is just fitting it into an insert with more columns, which your table may or may not have. If you name the result of that select FOO
then you can use SELECT Foo.BulkColumn
and as
after that constants for other fields in your table.
The part that can get more tricky is how to export that data back into a file so you can check that it's still OK. If you run it on cmd line:
bcp "select Data from B2B.dbo.Thumbnail where Id=1"
queryout D:\T\TestImage1_out2.dds -T -L 1
It's going to start whining for 4 additional "params" and will give misleading defaults (which will result in a changed file). You can accept the first one, set the 2nd to 0 and then assept 3rd and 4th, or to be explicit:
Enter the file storage type of field Data [varbinary(max)]:
Enter prefix-length of field Data [8]: 0
Enter length of field Data [0]:
Enter field terminator [none]:
Then it will ask:
Do you want to save this format information in a file? [Y/n] y
Host filename [bcp.fmt]: C:\Test\bcp_2.fmt
Next time you have to run it add -f C:\Test\bcp_2.fmt
and it will stop whining :-)
Saves a lot of time and grief.
misread the question, corrected. Try:
var myNumber = 100,
myarr = (function arr(i){return i ? arr(i-1).concat(i) : [i]}(myNumber));
Just for fun, if you extend Array
like this:
Array.prototype.mapx = function(callback){
return String(this).split(',').map(callback);
}
You could use:
var myNum = 100,
myarr = new Array(myNum).mapx(function(el,i){return i+1;});
You can use gravity with aligning top and bottom.
android:gravity="center_vertical"
android:layout_alignTop="@id/place_category_icon"
android:layout_alignBottom="@id/place_category_icon"
If you get this issue, then either
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
Scenario:
Windows 10 with Visual Studio 2017 (FRESH installation).
'C' project (ERROR like -> cannot open source file: 'stdio.h', 'windows.h', etc.).
Resolve:
Run 'Visual Studio Installer'.
Click button 'Modify'.
Select 'Desktop development with C++'.
From "Installation details"(usually on the right-sidebar) select:
4.1. Windows 10 SDK(10.0.17134.0).
Click button 'Modify', to apply changes.
The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.
(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)
In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.
For example, lets say you have the following query:
SELECT emp_id FROM employees WHERE months_of_service = 6;
(The months_of_service
column has a NOT NULL constraint on it and an ordinary index on it.)
There are two basic plans the optimiser might choose here:
months_of_service=6
).months_of_service=6
(this results in a set of ROWIDs), then access the table based on the ROWIDs returned.Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.
The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.
The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.
As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.
If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".
The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.
One can catch that you may change it through windows registry key
(SQLEXPRESS instance):
"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2
... and restart service
Try this approach using the newer str.format
syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old %
syntax (useful for older versions of Python that don't support str.format
):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
string name= "abc";
IList<string> strList = new List<string>() { "abc", "def", "ghi", "jkl", "mno" };
if (strList.Contains(name))
{
Console.WriteLine("Got It");
}
///////////////// OR ////////////////////////
IList<int> num = new List<int>();
num.Add(10);
num.Add(20);
num.Add(30);
num.Add(40);
Console.WriteLine(num.Count); // to count the total numbers in the list
if(num.Contains(20)) {
Console.WriteLine("Got It"); // if condition to find the number from list
}
I was able to get all my node processes to die directly from the Git Bash shell on Windows 10 by typing taskkill -F -IM node.exe
- this ends all the node processes on my computer at once. I found I could also use taskkill //F //IM node.exe
. Not sure why both -
and //
work in this context. Hope this helps!
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:
When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:
Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.
In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company
with the value 'ABC123'
and the field address
with the value '123 Street'
, in the exact order:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
If you have Perl installed, you could use ack, available at http://beyondgrep.com/.
matplotlib
is somewhat different from when the original answer was postedmatplotlib.pyplot.text
matplotlib.axes.Axes.text
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')
# or
fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')
import matplotlib.pyplot as plt
# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.axis('off')
plt.show()
According to the exception, Hibernate wants to write to the table "person", yet in your hbm.xml you define that there is a table "Person", are you sure the correct table exists in your database-schema?
All browsers support Javascript window object. It defines the window of the browser.
The global objects and functions become part of the window object automatically.
All global variables are window objects properties and all global functions are its methods.
The whole HTML document is a window property too.
So you can use window.location object to get all url related attributes.
Javascript
console.log(window.location.host); //returns host_x000D_
console.log(window.location.hostname); //returns hostname_x000D_
console.log(window.location.pathname); //return path_x000D_
console.log(window.location.href); //returns full current url_x000D_
console.log(window.location.port); //returns the port_x000D_
console.log(window.location.protocol) //returns the protocol
_x000D_
JQuery
console.log("host = "+$(location).attr('host'));_x000D_
console.log("hostname = "+$(location).attr('hostname'));_x000D_
console.log("pathname = "+$(location).attr('pathname')); _x000D_
console.log("href = "+$(location).attr('href')); _x000D_
console.log("port = "+$(location).attr('port')); _x000D_
console.log("protocol = "+$(location).attr('protocol'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
I know this posting is old, but I had the same problem, WAMP would not go online (green) while SKYPE was running. I simply closed SKYPE, ran WAMP and then reloaded SKYPE. I have not verified this, but I think SKYPE port corrected to allow for WAMP settings. At least I have not experienced any problems doing it this way
Suppose I want to increase the driver memory in runtime using Spark Session:
s2 = SparkSession.builder.config("spark.driver.memory", "29g").getOrCreate()
Now I want to view the updated settings:
s2.conf.get("spark.driver.memory")
To get all the settings, you can make use of spark.sparkContext._conf.getAll()
Hope this helps
pgrep -f youAppFile.py | xargs kill -9
pgrep
returns the PID of the specific file will only kill the specific application.
The following works for me:
form_for @user, :url => {:action => "YourActionName"}
code extracted from this link ;
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(currentLocale);
amountOut = numberFormatter.format(amount);
System.out.println(amountOut + " " +
currentLocale.toString());
The output from this example shows how the format of the same number varies with Locale:
345 987,246 fr_FR
345.987,246 de_DE
345,987.246 en_US
You can write the query as below:
SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';
it will solve your problem.
I solved this exception by changing the target sdk
version from 19 onwards kitkat version AndroidManifest.xml.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
Why not try http://phpjs.org/functions/md5/?
Unfortunately performance is limited with any emulated script, however this can render real md5 hash. Although I would advice against using md5 for passwords, as it is a fast-rendered hash.
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
I had a similar issue following Firebase's online guide found here.
The section heading "Initialize multiple apps" is misleading as the first example under this heading actually demonstrates how to initialize a single, default app. Here's said example:
// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);
console.log(defaultApp.name); // "[DEFAULT]"
// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();
// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();
If you are migrating from the previous 2.x SDK you will have to update the way you access the database as shown above, or you will get the, No Firebase App '[DEFAULT]'
error.
Google has better documentation at the following:
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
Reasons have been given in other answers; here is another.
std::map (balanced binary tree) operations are amortized O(log n) and worst case O(log n). std::unordered_map (hash table) operations are amortized O(1) and worst case O(n).
How this plays out in practice is that the hash table "hiccups" every once in a while with an O(n) operation, which may or may not be something your application can tolerate. If it can't tolerate it, you'd prefer std::map over std::unordered_map.
To add to what others have stated:
I usually like to use the 'dest' parameter to specify a variable name and then use 'globals().update()' to put those variables in the global namespace.
Usage:
$ python script.py -i "Hello, World!"
Code:
...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
m2eclipse has moved from sonatype to eclipse.
The correct update site is http://download.eclipse.org/technology/m2e/releases/
If this is not working, one possibility is you have an older version of Eclipse (< 3.6). The other - if you see timeout related errors - could be that you are behind a proxy server.
It could also be done without a visual client with the following small script.
$ cat ~/bin/pdel
#!/bin/sh
#Todo: add error handling
( p4 -c $1 client -o | perl -pne 's/\blocked\s//' | p4 -c $1 client -i ) && p4 client -d $1
One of the good things about handle.exe
is that you can run it as a subprocess and parse the output.
We do this in our deployment script - works like a charm.
Simple and straight forward:
Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
fileName = Path.GetFileName(uri.LocalPath);
I make it simple, if the layout is same i just put the intent it.
My code like this:
public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCertificate, btnSeminarKit;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_menu);
initClick();
}
private void initClick() {
btnCertificate = (Button) findViewById(R.id.btn_Certificate);
btnCertificate.setOnClickListener(this);
btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
btnSeminarKit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_Certificate:
break;
case R.id.btn_SeminarKit:
break;
}
Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
startActivity(intent);
}
}
I encountered a similar problem only with a nested img in my anchor:
<a href="some/link">
<img src="some/src">
</a>
When I applied
@media print {
a[href]:after {
content: none !important;
}
}
I lost my img and the entire anchor width for some reason, so instead I used:
@media print {
a[href]:after {
visibility: hidden;
}
}
which worked perfectly.
Bonus tip: inspect print preview
Go to Control Panel -> Programs -> Programs and features
Go to Windows Features and disable Internet Explorer 11
Then click on Display installed updates
Search for Internet explorer
Right-click on Internet Explorer 11 -> Uninstall
Do the same with Internet Explorer 10
I think it will be okay.
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
I tried the solution of the answer given by @okanda but it didn't work for me.
However it worked perfectly when I did it for several folders like mentioned in this thread: https://github.com/angular/angular-cli/issues/9676#issuecomment-464857493
sudo chown -R $USER /usr/local/lib/node_modules/
sudo chown -R $USER /usr/local/bin/
sudo chown -R $USER /usr/local/share/
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
I can't see hotkey for macbook for use vim in standard terminal. Hope it will help someone. For macOS users (tested on macbook pro 2018):
fn + ? - move to beginning line
fn + ? - move to end line
fn + ? - move page up
fn + ? - move page down
fn + g - move the cursor to the beginning of the document
fn + shift + g - move the cursor to the end of the document
For the last two commands sometime needs to tap twice.
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
String
A simple regex. See: How to check if a string contains only digits in Java. Use javax.constraints.Pattern.
Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.
In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:
function myFunc(requiredArg, optionalArg = 'defaultValue') {
// do stuff
}
More about them in this article on MDN.
This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.
EDIT (2019-06-12):
Default parameters are now widely supported by modern browsers.
All versions of Internet Explorer do not support this feature. However, Chrome, Firefox, and Edge currently support it.
To get the full SHA:
$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537
To get the shortened version:
$ git rev-parse --short HEAD
cbf1b9a
parser.print_help()
parser.exit()
The parser.exit
method also accept a status
(returncode), and a message
value (include a trailing newline yourself!).
an opinionated example, :)
#!/usr/bin/env python3
""" Example argparser based python file
"""
import argparse
ARGP = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')
def main(argp=None):
if argp is None:
argp = ARGP.parse_args() # pragma: no cover
if 'soemthing_went_wrong' and not argp.example:
ARGP.print_help()
ARGP.exit(status=64, message="\nSomething went wrong, --example condition was not set\n")
if __name__ == '__main__':
main() # pragma: no cover
Example calls:
$ python3 ~/helloworld.py; echo $? usage: helloworld.py [-h] [--example] Example argparser based python file optional arguments: -h, --help show this help message and exit --example Example Argument Something went wrong, --example condition was not set 64 $ python3 ~/helloworld.py --example; echo $? 0
Try:
document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";
@scanlegentil I like this.
A little improvement would be:
$Depth = 2
$Path = "."
$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host
As mentioned, this would only scan the specified depth, so this modification is an improvement:
$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2 # How many levels deep to scan
$Path = "." # starting path
For ($i=$StartLevel; $i -le $Depth; $i++) {
$Levels = "\*" * $i
(Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
Select FullName
}
Late answer, another idea, but very short.
table { margin-top: 20px; display: inline-block; overflow: auto; }
th div { margin-top: -20px; position: absolute; }
Note that it is possible to display table as inline-block due to anonymous table objects:
"missing" [in HTML table tree structure] elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself.
/* scrolltable rules */_x000D_
table { margin-top: 20px; display: inline-block; overflow: auto; }_x000D_
th div { margin-top: -20px; position: absolute; }_x000D_
_x000D_
/* design */_x000D_
table { border-collapse: collapse; }_x000D_
tr:nth-child(even) { background: #EEE; }
_x000D_
<table style="height: 150px">_x000D_
<tr> <th><div>first</div> <th><div>second</div>_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo foo foo foo foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar bar bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
<tr> <td>foo <td>bar_x000D_
</table>
_x000D_
You need to create a directory on a remote server. Then use "git init" command to set it as a repository. This should be done for each new project you have (each new folder)
Assuming you have already setup and used git using ssh keys, I wrote a small Python script, which when executed from a working directory will set up a remote and initialize the directory as a git repo. Of course, you will have to edit script (only once) to tell it server and Root path for all repositories.
Check here - https://github.com/skbobade/ocgi
You can use the Enumerable.Where extension method:
var matches = myList.Where(p => p.Name == nameToExtract);
Returns an IEnumerable<SampleClass>
. Assuming you want a filtered List
, simply call .ToList()
on the above.
By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:
var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));
This question is really multiple questions in one. They are different ways of styling something. Here are links to the questions within this question:
font-family
of an <option>
element:
font-size
of an <option>
element:
background-color
of an <option>
element:
font-weight
of an <option>
element:
color
of an <option>
element:
use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html
div#thing
{
position: absolute;
width:400px;
right: 0;
left: 0;
margin: auto;
}
1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.
An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)
You can use:
ls -lrt filename |awk '{print "%02d",$7}'
This will display the date in 2 digits.
If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.
Hope this meets the expectation.
I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.
Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).
As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".
And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
Presumably you're passing the arguments in on the command line as follows:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
... and then accessing them in the script thusly:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:
Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
... and access:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
These answers are totally my opinion
Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.
Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.
As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.
between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.
Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
Use pgrep - available on many platforms:
kill -9 `pgrep -f cps_build`
pgrep -f will return all PIDs with coincidence "cps_build"
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
in mysql if you take VARCHAR
then change it to TEXT
bcoz its size is 65,535
and if you can already take TEXT
the change it with LONGTEXT
only if u need more then 65,535
.
total size of LONGTEXT
is 4,294,967,295
characters
Very short answer :
Different databases have different uses. I'm not a database expert. Rule of thumb:
Short answer:
Let's consider two example scenarios:
Scenario 1:
You are building an online store/website, and you want to be able to:
You want to be able to find data for a particular user, change its name... basically perform INSERT, UPDATE, DELETE operations on user data. Same with products, etc.
You want to be able to make transactions, possibly involving a user buying a product (that's a relation). Then OLTP is probably a good fit.
Scenario 2:
You have an online store/website, and you want to compute things like
This falls into the analytics/business intelligence domain, and therefore OLAP is probably more suited.
If you think in terms of "It would be nice to know how/what/how much"..., and that involves all "objects" of one or more kind (ex. all the users and most of the products to know the total spent) then OLAP is probably better suited.
Longer answer:
Of course things are not so simple. That's why we have to use short tags like OLTP
and OLAP
in the first place. Each database should be evaluated independently in the end.
So what could be the fundamental difference between OLAP and OLTP?
Well, databases have to store data somewhere. It shouldn't be surprising that the way the data is stored heavily reflects the possible use of said data. Data is usually stored on a hard drive. Let's think of a hard drive as a really wide sheet of paper, where we can read and write things. There are two ways to organize our reads and writes so that they can be efficient and fast.
One way is to make a book that is a bit like a phone book. On each page of the book, we store the information regarding a particular user. Now that's nice, we can find the information for a particular user very easily! Just jump to the page! We can even have a special page at the beginning to tell us on which page the users are if we want. But on the other hand, if we want to find, say, how much money all of our users spent then we would have to read every page, i.e. the whole book! That would be a row-based book/database (OLTP). The optional page at the beginning would be the index.
Another way to use our big sheet of paper is to make an accounting book. I'm no accountant, but let's imagine that we would have a page for "expenditures", "purchases"... That's nice because now we can query things like "give me the total revenue" very quickly (just read the "purchases" page). We can also ask for more involved things like "give me the top ten products sold" and still have acceptable performance. But now consider how painful it would be to find the expenditures for a particular user. You would have to go through the whole list of everyone's expenditures and filter the ones of that particular user, then sum them. Which basically amounts to "read the whole book" again. That would be a column-based database (OLAP).
It follows that:
OLTP
databases are meant to be used to do many small transactions, and usually serve as a "single source of truth".
OLAP
databases on the other hand are more suited for analytics, data mining, fewer queries but they are usually bigger (they operate on more data).
It's a bit more involved than that of course and that's a 20 000 feet overview of how databases differ, but it allows me not to get lost in a sea of acronyms.
Speaking of acronyms:
To read a bit further, here are some relevant links which heavily inspired my answer:
Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g
$getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");
foreach($getvidids->result() as $key=>$myids)
{
$vidid[$key] = $myids->videoid; // better methodology to retrieve and store multiple records in arrays in loop
}
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
The easiest way to block these temporarily for testing purposes is to open up the inspect page in chrome by right-clicking anywhere on the page and clicking inspect or by pressing Ctrl+Shift+j
and then going to the networking tab and then reloading the page which will send all the requests your page is supposed to make including that annoying favicon.ico. You can now simply right click the favicon.ico request and click "Block request URL".
All of the above answers are for devs who control the app source code. If you are a sysadmin, who's figuring our load-balancer or proxying configuration and is annoyed by this favicon.ico shenanigans, this simple trick does a better job. This answer is for Chrome, but I think there should be a similar alternative which you would figure out for Firefox/Opera/Tor/any other browser :)
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
Starting with Python 3.8 you can use the environment variable PYTHONPYCACHEPREFIX
to define a cache directory for Python.
From the Python docs:
If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in pycache directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.
Example
If you add the following line to your ./profile
in Linux:
export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/"
Python won't create the annoying __pycache__
directories in your project directory, instead it will put all of them under ~/.cache/cpython/
Your .htaccess should run just fine; it depends on four different Apache modules (one per each <IfModule>
directive). I guess one of the following:
your Apache server doesn't have either mod_filter, mod_deflate, mod_headers and/or mod_setenvif modules installed and running. If you can access the server config, please check /etc/apache2/httpd.conf
(and the related Apache config files); otherwise, you can see which modules are loaded via phpinfo()
, under the apache2handler section (see attached image); (EDIT) OR, you can open a terminal window and issue the command sudo apachectl -M
that will list the loaded modules;
if you get an http 500 internal server error, your server may not be allowed to use .htaccess files;
you are trying to load a PHP file that sends its own headers (overwriting Apache'sheaders), thus "confusing" the browser.
In any case, you should double-check your server config and error logs to see what's going wrong. Just to be sure, try to use the fastest way suggested here in Apache docs:
AddOutputFilterByType DEFLATE text/html text/plain text/xml
and then try to load a large textfile (preferably, clean your cache first).
(EDIT) If the needed modules are there (in the Apache modules dir) but aren't loaded, just edit /etc/apache2/httpd.conf and add a LoadModule directive for each one of them.
If the needed modules aren't there (neither loaded, nor in the Apache modules directory), I fear that the only option is reinstalling Apache (a complete version).
Why not just remove that attribute?
elem.removeAttribute('disabled')
elem.removeAttr('disabled')
Here is here I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode()
to return null
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
In Node.js 8 you can promisify object methods on the fly using this npm module:
https://www.npmjs.com/package/doasync
It uses util.promisify and Proxies so that your objects stay unchanged. Memoization is also done with the use of WeakMaps). Here are some examples:
With objects:
const fs = require('fs');
const doAsync = require('doasync');
doAsync(fs).readFile('package.json', 'utf8')
.then(result => {
console.dir(JSON.parse(result), {colors: true});
});
With functions:
doAsync(request)('http://www.google.com')
.then(({body}) => {
console.log(body);
// ...
});
You can even use native call
and apply
to bind some context:
doAsync(myFunc).apply(context, params)
.then(result => { /*...*/ });
npm config set registry http://registry.npmjs.org/
above code solved my issue :)
Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.
Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.
Finally, delete the old package.
or Look into this post
Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made. In order to reset before a given commit you thus have to select its parent.
Depending on what you want to do with the changes choose hard, which will get rid of them locally. Or choose soft which will undo the commit but will leave your working directory with the changes in your discarded commit.
Are you sure you need to use sed? How about:
tr -d "\""
I was looking for same answer and finally I found this link. You can find explained three different ways how to add bootstrap css into your angular 2 project. It helped me.
Here is the link: http://codingthesmartway.com/using-bootstrap-with-angular/