You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n
, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n
on input, and conversely on output.
From the C99 standard (the N869 draft document), §7.19.2/2,
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.
And in §7.19.3/2
Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.
About use of fseek
, in §7.19.9.2/4:
For a text stream, either
offset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
About use of ftell
, in §17.19.9.4:
The
ftell
function obtains the current value of the file position indicator for the stream pointed to bystream
. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by thefseek
function for returning the file position indicator for the stream to its position at the time of theftell
call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
I think that’s the most important, but there are some more details.
You can use Jquery's on method and listen for the scroll
event.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.
You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle
documentation just tells you the basics of using IDLE itself, and its idlelib
library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.
Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal
is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)
Learning to read the termcap
entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.
Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.
But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses
. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
This error also comes when you run the command
node filename.ts
and not
node filename.js
To simply put, with node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node
When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.
ga('create', 'UA-XXXXX-Y', {
cookieFlags: 'max-age=7200;secure;samesite=none'
});
Also more info in this blog post
For me it was due to full disk space.
My application (server) was running on docker. Cleared some space and it started working.
For those can not create PHP session and working with live domain at local. You should delete live sites secure cookie first.
Full answer ; https://stackoverflow.com/a/64073275/1067434
Delete node_modules
rm -r node_modules
install packages again
npm install
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
When using Object.keys
, the following works:
Object.keys(this)
.forEach(key => {
console.log(this[key as keyof MyClass]);
});
You can convert class component to hooks,but Material v4 has a withStyles HOC. https://material-ui.com/styles/basics/#higher-order-component-api Using this HOC you can keep your code unchanged.
I used withStyles
instead of makeStyle
EX :
import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";
const useStyles = theme => ({
root: {
flexGrow: 1,
},
});
class App extends Component {
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
Test
</div>
)
}
}
export default withStyles(useStyles)(App)
I had the same issue and the base
environment was in C:\ProgramData\Anaconda3
. This is the case, when Anaconda is installed for all users
.
As a solution, I re-installed Anaconda just for me
and now the base
environment is in \AppData\Local\Continuum\anaconda3
. This now can be updated via conda update
without admin privileges.
cd ios && rm Podfile.lock && pod install
worked for me.
I had the same issue in Travis and solved by adding:
addons:
chrome: stable
to my .travis.yml
file.
In my case I already had a Conda environment activated, but I still wanted local Python modules to be available for autocomplete, peeking definition, etc.
I tried many solutions such as adding a list of Python paths etc., but what finally solved it for me was to create a symbolic link from Conda's lib/python{your version}/site-packages
to my local module.
All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint
the issue will be fixed.
Kasperd asked in a comment of the accepted answer:
The Java and C examples use quite different register names. Are both example using the AMD64 ISA?
xor edx, edx
xor eax, eax
.L2:
mov ecx, edx
imul ecx, edx
add edx, 1
lea eax, [rax+rcx*2]
cmp edx, 1000000000
jne .L2
I don't have enough reputation to answer this in the comments, but these are the same ISA. It's worth pointing out that the GCC version uses 32-bit integer logic and the JVM compiled version uses 64-bit integer logic internally.
R8 to R15 are just new X86_64 registers. EAX to EDX are the lower parts of the RAX to RDX general purpose registers. The important part in the answer is that the GCC version is not unrolled. It simply executes one round of the loop per actual machine code loop. While the JVM version has 16 rounds of the loop in one physical loop (based on rustyx answer, I did not reinterpret the assembly). This is one of the reasons why there are more registers being used since the loop body is actually 16 times longer.
Incase anybody is looking for a TypeScript version of usePrevious:
In a .tsx
module:
import { useEffect, useRef } from "react";
const usePrevious = <T extends unknown>(value: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
Or in a .ts
module:
import { useEffect, useRef } from "react";
const usePrevious = <T>(value: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
I've found great solution and explanation at this GitHub comment. The trick:
make SDKROOT=`xcrun --show-sdk-path` MACOSX_DEPLOYMENT_TARGET=
Did the job.
This is the most simple solution if you just need to refresh the entire page
refreshPage() {
window.location.reload();
}
Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
Comment This Line in gradle.properties
android.useAndroidX=true
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
I recommend this for Python 3: Please install it this way with pip
pip3 install opencv-python
This will download and install the latest version of OpenCV.
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
I solve this issue set my settings in vscode.
Regards
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
my problem was just network connection. using VPN solved the issue.
Go to > Control Panel\User Accounts\Credential Manager
> Manage Windows Credentials
and remove all generic credentials involving Git. This way you're resetting all the credentials; After this, when you clone, you'll be newly and securely asked your username and password instead of Authentication error. Similar logic can be applied for Mac users.
Hope it helps.
You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
getInstance().getInstanceId()
is also now deprecated and FirebaseMessaging
is being used now.
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
} else {
Timber.e(task.exception)
}
}
I get this error whenever I use np.concatenate
the wrong way:
>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index
The correct way is to input the two arrays as a tuple:
>>> np.concatenate((a, a))
array([[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.]])
Perhaps this is happening because, even if Tesseract is correctly installed, you have not installed your language, as was my case. Fortunately this is very easy to fix, and I did not even need to mess with tesseract_cmd
.
sudo apt-get install tesseract-ocr -y
sudo apt-get install tesseract-ocr-spa -y
tesseract --list-langs
Note that in the second line we have specified -spa
for Spanish.
If installation has been successful, you should get a list of your available languages, like:
List of available languages (3):
eng
osd
spa
I found this at this blog post (Spanish). There is also a post for installation of Spanish language in Windows (not as easy apparently).
Note: since the question uses lang = 'eng'
, it is likely this is not the answer in that specific case. But the same error may happen in this other situation, which is why I posted the answer here.
I had this error and as I'm on shared hosting I don't have access to the php.ini so wasn't sure how I could fix it, the host didn't seem to have a clue either. In the end I emptied my browser cache and reloaded phpmyadmin and it came back!
In my case using latest versions of following dependencies
solved my issue:
'com.google.android.gms:play-services-analytics:16.0.1'
'com.google.android.gms:play-services-tagmanager:16.0.1'
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.
This will install an apk directly on the device connected from the aab.
You can use npm uninstall <package-name>
will remove it from your package.json file and from node_modules.
If you do ng help
command, you will see that there is no ng remove/delete
supported command. So, basically you cannot revert the ng add
behavior yet.
I had this same issue, which led me here. In particular, for local development, I wanted to be able to do mysql -u root -p
without sudo
. I don't want to create a new user. I want to use root
from a local PHP web app.
The error message is misleading, as there was nothing wrong with the default 'root'@'%'
user privileges.
Instead, as several people mentioned in the other answers, the solution was simply to set bind-address=0.0.0.0
instead of bind-address=127.0.0.1
in my /etc/mysql/mysql.conf.d/mysqld.cnf
config. No changes were otherwise required.
It's working for me (PHP 5.6 + PDO / MySQL Server 8.0 / Windows 7 64bits)
Edit the file C:\ProgramData\MySQL\MySQL Server 8.0\my.ini
:
default_authentication_plugin=mysql_native_password
Reset MySQL service on Windows, and in the MySQL Shell...
ALTER USER my_user@'%' IDENTIFIED WITH mysql_native_password BY 'password';
This is working i Angular 8 without setTimeout:
import {AfterContentChecked, Directive, ElementRef} from '@angular/core';
@Directive({
selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
constructor(private element: ElementRef<HTMLInputElement>) {}
ngAfterContentChecked(): void {
this.element.nativeElement.focus();
}
}
Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.
More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks
UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:
<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
<input type="text tabIndex="0">
</div>
We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.
This works with my IP camera:
import cv2
#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")
while True:
#print('About to start the Read command')
ret, frame = cap.read()
#print('About to show frame of Video.')
cv2.imshow("Capturing",frame)
#print('Running..')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I found the Stream URL in the Camera's Setup screen:
Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)
If you are using the official mysql docker container, there is a simple solution:
Add the following line to your docker-compose service:
command: --default-authentication-plugin=mysql_native_password
Example configuration:
mysql:
image: mysql:8
networks:
- net_internal
volumes:
- mysql_data:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=db
command: --default-authentication-plugin=mysql_native_password
I've seen this issue when PYTHONPATH
was set to include the built-in site-packages
directory. Since Python looks there automatically it is unnecessary and can be removed.
I fixed this problem upgrading to latest version
sudo pip install --upgrade pip
My version: pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
With a button
bool _paused = false;
CupertinoButton(
child: _paused ? Text('Play') : Text('Pause'),
color: Colors.blue,
onPressed: () {
setState(() {
_paused = !_paused;
});
},
),
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>Children ({this.props.children.length}):</div>_x000D_
{this.props.children}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>First <code>Example</code>:</div>_x000D_
<Example>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
</Example>_x000D_
<div>Second <code>Example</code> with different children:</div>_x000D_
<Example>_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</Example>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Widget/>,_x000D_
document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
children
is a special property of React components which contains any child elements defined within the component, e.g. the divs
inside Example
above. {this.props.children}
includes those children in the rendered result.
...what are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.
I had the same issue and I fixed it this way:
mywork
.myWork
. Let us call the class HelloWorld
.Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.
You should use Java 8 to solve this, based on the Android documentation you can do this by
clicking File > Project Structure
and change Source Compatibility
and Target Compatibility
.
and you can also configure it directly in the app-level build.gradle
file:
android {
...
// Configure only for each module that uses Java 8
// language features (either in its source code or
// through dependencies).
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
You can set also blank condition, in place of set null
var isDisable=true;
RaisedButton(
padding: const EdgeInsets.all(20),
textColor: Colors.white,
color: Colors.green,
onPressed: isDisable
? () => (){} : myClickingData(),
child: Text('Button'),
)
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.
To append a name/value name/value pair to a Headers object (headers), run these steps:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headers’s guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
To fill a Headers object headers with a given object object, run these steps:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
The delete(name) method steps are:
- If name is not a name, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
The get(name) method steps are:
- If name is not a name, then throw a TypeError.
- Return the result of getting name from this’s header list.
The has(name) method steps are:
- If name is not a name, then throw a TypeError.
The set(name, value) method steps are:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
To extract a body and a
Content-Type
value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.
In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method isGET
orHEAD
, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...
The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.
In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.
To remove complete conda environment :
conda remove --name YOUR_CONDA_ENV_NAME --all
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
If you have already installed and set-up your emulator, but facing the issue during running your app, You can try these steps to fix this issue.
Steps:
Note - If it's still not working, Try again the 4th step By Wiping your data.
Hope this works 4 you ;)
Nothing worked for me until I updated my kotlin plugin dependency.
Try this:
1. Invalidate cahce and restart.
2. Sync project (at least try to)
3. Go File -> Project Structure -> Suggestions
4. If there is an update regarding Kotlin, update it.
Hope it will help someone.
The problem for me seems to have been how the user has been setup on my local machine to. Using the command
git push -u origin master
was causing the error. Removing the switch -u
to have
git push origin master
solved it for me. It can be scary to imagine how user setup can result in an error related to LibreSSL.
file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
any_string = "Hello\nWorld"
file.write(any_string)
file.close()
To fix that issue, I searched where is my docker and docker-compose installed. In my case, docker
was installed in /usr/bin/docker
and docker-compose
was installed in /usr/local/bin/docker-compose
path. Then, I write this in my terminal:
To docker:
sudo chmod +x /usr/bin/docker
To docker-compose
:
sudo chmod +x /usr/local/bin/docker-compose
Now I don't need write in my commands docker the word sudo
/***********************************************************************/
ERRATA:
The best solution of this issue was commented by @mkasberg. I quote comment:
That might work, you might run into issues down the road. Also, it's a security vulnerability. You'd be better off just adding yourself to the docker group, as the docs say. sudo groupadd docker, sudo usermod -aG docker $USER.
Docs:
https://docs.docker.com/install/linux/linux-postinstall/
Thanks a lot!
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
I am not sure if you are using IoC and Dependency Injection to resolve your DbContext where ever it might be used. If you do and you are using native IoC from .NET Core (or any other IoC-Container) and you are getting this error, make sure to register your DbContext as Transient. Do
services.AddTransient<MyContext>();
OR
services.AddDbContext<MyContext>(ServiceLifetime.Transient);
instead of
services.AddDbContext<MyContext>();
AddDbContext adds the context as scoped, which might cause troubles when working with multiple threads.
Also async / await operations can cause this behaviour, when using async lambda expressions.
Adding it as transient also has its downsides. You will not be able to make changes to some entity over multiple classes that are using the context because each class will get its own instance of your DbContext.
The simple explanation for that is, that the DbContext
implementation is not thread-safe. You can read more about this here
There are a few important rules to install Tensorflow:
You have to install Python x64. It doesn't work on 32b and it gives the same error as yours.
It doesn't support Python versions later than 3.8 and Python 3.8 requires TensorFlow 2.2 or later.
For example, you can install Python3.8.6-64bit and it works like a charm.
This error message might possibly indicate something else.
In my case I defined another Docker-Image elsewhere from which the current Docker inherited its settings (docker-compos.yml
):
FROM my_own_image:latest
The error message I got:
qohelet$ docker-compose up
Building web
Step 1/22 : FROM my_own_image:latest
ERROR: Service 'web' failed to build: pull access denied for my_own_image, repository does not exist or may require 'docker login'
Due to a reinstall the previous Docker were gone and I couldn't build my docker using docker-compose up
with this command:
sudo docker build -t my_own_image:latest -f MyOwnImage.Dockerfile .
In your specific case you might have defined your own php-docker.
replace "150x150" with 720x720 and remove /vp/ from the link.it should work.
Below solution is a clean work around.It does not compromises security because we are using same strict firewall.
The Steps for fixing is as below:
STEP 1 : Create a Class overriding StrictHttpFirewall as below.
package com.biz.brains.project.security.firewall;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;
public class CustomStrictHttpFirewall implements HttpFirewall {
private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());
private static final String ENCODED_PERCENT = "%25";
private static final String PERCENT = "%";
private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));
private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));
private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));
private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));
private Set<String> encodedUrlBlacklist = new HashSet<String>();
private Set<String> decodedUrlBlacklist = new HashSet<String>();
private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();
public CustomStrictHttpFirewall() {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
this.decodedUrlBlacklist.add(PERCENT);
}
public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
}
public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
if (allowedHttpMethods == null) {
throw new IllegalArgumentException("allowedHttpMethods cannot be null");
}
if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
} else {
this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
}
}
public void setAllowSemicolon(boolean allowSemicolon) {
if (allowSemicolon) {
urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
} else {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
}
}
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
if (allowUrlEncodedSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
}
}
public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
if (allowUrlEncodedPeriod) {
this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
} else {
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
}
}
public void setAllowBackSlash(boolean allowBackSlash) {
if (allowBackSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
}
}
public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
if (allowUrlEncodedPercent) {
this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
this.decodedUrlBlacklist.remove(PERCENT);
} else {
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.decodedUrlBlacklist.add(PERCENT);
}
}
private void urlBlacklistsAddAll(Collection<String> values) {
this.encodedUrlBlacklist.addAll(values);
this.decodedUrlBlacklist.addAll(values);
}
private void urlBlacklistsRemoveAll(Collection<String> values) {
this.encodedUrlBlacklist.removeAll(values);
this.decodedUrlBlacklist.removeAll(values);
}
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
rejectForbiddenHttpMethod(request);
rejectedBlacklistedUrls(request);
if (!isNormalized(request)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
}
String requestUri = request.getRequestURI();
if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
request.setAttribute("isNormalized", new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
}
return new FirewalledRequest(request) {
@Override
public void reset() {
}
};
}
private void rejectForbiddenHttpMethod(HttpServletRequest request) {
if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
return;
}
if (!this.allowedHttpMethods.contains(request.getMethod())) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the HTTP method \"" +
request.getMethod() +
"\" was not included within the whitelist " +
this.allowedHttpMethods));
}
}
private void rejectedBlacklistedUrls(HttpServletRequest request) {
for (String forbidden : this.encodedUrlBlacklist) {
if (encodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
for (String forbidden : this.decodedUrlBlacklist) {
if (decodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
private static Set<String> createDefaultAllowedHttpMethods() {
Set<String> result = new HashSet<>();
result.add(HttpMethod.DELETE.name());
result.add(HttpMethod.GET.name());
result.add(HttpMethod.HEAD.name());
result.add(HttpMethod.OPTIONS.name());
result.add(HttpMethod.PATCH.name());
result.add(HttpMethod.POST.name());
result.add(HttpMethod.PUT.name());
return result;
}
private static boolean isNormalized(HttpServletRequest request) {
if (!isNormalized(request.getRequestURI())) {
return false;
}
if (!isNormalized(request.getContextPath())) {
return false;
}
if (!isNormalized(request.getServletPath())) {
return false;
}
if (!isNormalized(request.getPathInfo())) {
return false;
}
return true;
}
private static boolean encodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getContextPath(), value)) {
return true;
}
return valueContains(request.getRequestURI(), value);
}
private static boolean decodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getServletPath(), value)) {
return true;
}
if (valueContains(request.getPathInfo(), value)) {
return true;
}
return false;
}
private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
int length = uri.length();
for (int i = 0; i < length; i++) {
char c = uri.charAt(i);
if (c < '\u0020' || c > '\u007e') {
return false;
}
}
return true;
}
private static boolean valueContains(String value, String contains) {
return value != null && value.contains(contains);
}
private static boolean isNormalized(String path) {
if (path == null) {
return true;
}
if (path.indexOf("//") > -1) {
return false;
}
for (int j = path.length(); j > 0;) {
int i = path.lastIndexOf('/', j - 1);
int gap = j - i;
if (gap == 2 && path.charAt(i + 1) == '.') {
// ".", "/./" or "/."
return false;
} else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
return false;
}
j = i;
}
return true;
}
}
STEP 2 : Create a FirewalledResponse class
package com.biz.brains.project.security.firewall;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
class FirewalledResponse extends HttpServletResponseWrapper {
private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
private static final String LOCATION_HEADER = "Location";
private static final String SET_COOKIE_HEADER = "Set-Cookie";
public FirewalledResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendRedirect(String location) throws IOException {
// TODO: implement pluggable validation, instead of simple blacklisting.
// SEC-1790. Prevent redirects containing CRLF
validateCrlf(LOCATION_HEADER, location);
super.sendRedirect(location);
}
@Override
public void setHeader(String name, String value) {
validateCrlf(name, value);
super.setHeader(name, value);
}
@Override
public void addHeader(String name, String value) {
validateCrlf(name, value);
super.addHeader(name, value);
}
@Override
public void addCookie(Cookie cookie) {
if (cookie != null) {
validateCrlf(SET_COOKIE_HEADER, cookie.getName());
validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
}
super.addCookie(cookie);
}
void validateCrlf(String name, String value) {
if (hasCrlf(name) || hasCrlf(value)) {
throw new IllegalArgumentException(
"Invalid characters (CR/LF) in header " + name);
}
}
private boolean hasCrlf(String value) {
return value != null && CR_OR_LF.matcher(value).find();
}
}
STEP 3: Create a custom Filter to suppress the RejectedException
package com.biz.brains.project.security.filter;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
if(Objects.nonNull(requestRejectedException)) {
throw requestRejectedException;
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
} catch (RequestRejectedException requestRejectedException) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
log
.error(
"request_rejected: remote={}, user_agent={}, request_url={}",
httpServletRequest.getRemoteHost(),
httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
httpServletRequest.getRequestURL(),
requestRejectedException
);
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
STEP 4: Add the custom filter to spring filter chain in security configuration
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new RequestRejectedExceptionFilter(),
ChannelProcessingFilter.class);
}
Now using above fix, we can handle RequestRejectedException
with Error 404 page.
I believe this has been answered in some sections already, just test with gmail for your "MAIL_HOST" instead and don't forget to clear cache. Setup like below: Firstly, you need to setup 2 step verification here google security. An App Password link will appear and you can get your App Password to insert into below "MAIL_PASSWORD". More info on getting App Password here
MAIL_DRIVER=smtp
[email protected]
MAIL_FROM_NAME=DomainName
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=YOUR_GMAIL_CREATED_APP_PASSWORD
MAIL_ENCRYPTION=tls
Clear cache with:
php artisan config:cache
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
This works for me: For Python 3
pip3 install xlrd --user
For Python2
pip install xlrd --user
You can use another shell to execute the same command:
Error I get when i execute:
[jenkins@localhost jenkins_data]$ docker exec -it mysqldb \bin\bash
OCI runtime exec failed: exec failed: container_linux.go:345: starting container process caused "exec: \"binsh\": executable file not found in $PATH": unknown
Solution: When I execute it with below command, using bash shell it works:
[jenkins@localhost jenkins_data]$ docker exec -it mysqldb bash
root@<container-ID>:/#
I got the same "Could not get any response" issue because of wrong parameter in header. I fixed it by removing parameter HOST out of header.
PS: Unfortunately, I was pushed to install the other software to get this information. It should be great to get this error message from Postman instead of getting general nonsense.
urllib
is a standard python library (built-in) so you don't have to install it. just import it if you need to use request
by:
import urllib.request
if it's not work maybe you compiled python in wrong way, so be kind and give us more details.
You can post axios data by using FormData() like:
var bodyFormData = new FormData();
And then add the fields to the form you want to send:
bodyFormData.append('userName', 'Fred');
If you are uploading images, you may want to use .append
bodyFormData.append('image', imageFile);
And then you can use axios post method (You can amend it accordingly)
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Related GitHub issue:
Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
If the requested resource of the server is using Flask. Install Flask-CORS.
Use the following Code:-
../css/main.css
Note: The "../" is shorthand for "The containing directory", or "Up one directory".
If you don't know the previous folder this will be very helpful..
try this :
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
targetSdkVersion 26
}
}
compile 'com.android.support:appcompat-v7:25.1.0'
It has worked for me
When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.
What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true
and -o yaml
options:
kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -
The command above will not raise an error if the resource already exists (and will update the resource if needed).
This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).
Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:
df['column_name'].astype(np.float).astype("Int32")
NB: You have to go through numpy float first and then to nullable Int32, for some reason.
The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
Please make sure both JDK and jre are on same version for example if you have JRE version 1.8.0_201 then JDK version should be 1.8.0_201 version.
I usually just add the following custom CSS, the W3School example prepended with cursor-
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount()
in a React class.
For you edit, you may want to try something like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
Try to add this in gradle
android {
defaultConfig {
multiDexEnabled true
}
}
Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.
npm install popper.js@^1.12.3 --save
npm install [email protected] --save
npm install [email protected] --save
For Bootstrap 4.1
npm install popper.js@^1.14.3 --save
npm install [email protected] --save
npm install [email protected] --save
In my case by making build, from Build> Build apks, it worked.
fsevents
is dealt differently in mac and other linux system. Linux system ignores fsevents
whereas mac install it. As the above error message states that fsevents
is optional and it is skipped in installation process.
You can run npm install --no-optional
command in linux system to avoid above warning.
Further information
For me the issue was with @Component Selector path was pointing to wrong path. After changing it solved the issue.
@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html',
providers: [ToolbarService, GroupService, FilterService, PageService, ExcelExportService, PdfExportService]
})
I'm not sure if it could be this simple but I had the same issue, changing "mat-input" to "matInput" in the input field resolved the problem. In your case I see "matinput" and it's causing my app to throw the same error.
<input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false">
"matinput"
"matInput"
You could try the following:
import matplotlib.pyplot as plt
import numpy as np
def plot_figures(figures, nrows = 1, ncols=1):
"""Plot a dictionary of figures.
Parameters
----------
figures : <title, figure> dictionary
ncols : number of columns of subplots wanted in the display
nrows : number of rows of subplots wanted in the figure
"""
fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
for ind,title in zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
axeslist.ravel()[ind].set_title(title)
axeslist.ravel()[ind].set_axis_off()
plt.tight_layout() # optional
# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}
# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)
plt.show()
However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.
I hope this helps.
I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.
let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}
In Windows 64, if you did this sequence correctly:
Anaconda prompt:
conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow
Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:
conda install spyder
This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.
Always prefer to install these libraries with "conda install" instead of "pip".
I also received this error when I named one of my component inputs 'formControl'. Probably it's reserved for something else. If you want to pass FormControl object between components, use it like that:
@Input() control: FormControl;
not like this:
@Input() formControl: FormControl;
Weird - but working :)
And this is less
@primarycolor: #ffffff;
@width: 800px;
body{
width: @width;
color: @primarycolor;
.content{
width: @width;
background:@primarycolor;
}
}
Your installation is wrong; you are using a very old compiler version (1.0.3.0).
tsc --version
should return a version of 2.5.2.
Check where that old compiler is located using: which tsc
(or where tsc
) and remove it.
Try uninstalling the "global" typescript
npm uninstall -g typescript
Installing as part of a local dev dependency of your project
npm install typescript --save-dev
Execute it from the root of your project
./node_modules/.bin/tsc
<div class="col-md-12">
<p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
<button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
Ver Pedido
</button>
</p>
</div>
It can be installed with one command for N++ installer version:
choco install notepadplusplus-nppPluginManager
When using maven project.
check pom.xml file
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>9</java.version>
</properties>
if you have jdk 8 installed in your machine,
change java.version
property from 9
to 8
I had the same problem, and @ingyhere 's answer solved my problem .
follow his instructions told in his answer here.
git config --global core.compression 0
git clone --depth 1 <repo_URI>
# cd to your newly created directory
git fetch --unshallow
git pull --all
JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern
// filename: MyComponent.js
function MyComponent() {
return <div />;
}
as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here
Simple command to check keras version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'
When you are creating the router, you can specify the linkExactActiveClass
as a property to set the class that will be used for the active router link.
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes,
linkActiveClass: "active", // active class for non-exact links.
linkExactActiveClass: "active" // active class for *exact* links.
})
This is documented here.
Having watched my Windows Defender Virus Scanner start hogging the CPU while running my script, I suspect this is the actual cause, but as I don't have the ability to tweak those settings as I'm in a commercial domain.
As my script fails while doing npm install
, I simply tried this instead
npm install --verbose
which allowed it to run perfectly. It probably doesn't fix the underlying issue, but it allowed my install to download and extract all dependencies to my local cache at least once and therefore, everything worked a lot smoother.
I presume this command slows the writes/read to the disk by a fraction of a second, while its writing to the Command prompt and this gives the virus checker, just enough time to finish its work, without creating a deadlock on the files.
UPDATE: for rxjs > v5.5
As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json()
method anymore.
import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
export interface Order {
// Properties
}
interface ResponseOrders {
results: Order[];
}
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get<ResponseOrders >(this.baseUrl,{
params
}).pipe(
map(res => res.results || []),
catchError(error => _throwError(error.message || error))
);
}
Notice that you could easily transform the returned Observable
to a Promise
by simply invoking toPromise()
.
ORIGINAL ANSWER:
In your case, you can
Assumming that your backend returns something like:
{results: [{},{}]}
in JSON format, where every {} is a serialized object, you would need the following:
// Somewhere in your src folder
export interface Order {
// Properties
}
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Order } from 'somewhere_in_src';
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get(this.baseUrl,{
params
})
.map(res => res.results as Order[] || []);
// in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
}
}
I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:
https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90
And to consume you just need to call it like:
// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]
First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.
My problem started when I started using axios
with my custom instance. In my case, it was a very specific problem when we use a baseURL in axios
instance and then try to make GET
or POST
calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.
In general, the pre-flight OPTIONS
request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.
videoView can't open this video Online video
Create file res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
New in the AndroidManifest.xml file under application:
android:networkSecurityConfig="@xml/network_security_config"
https://techprogrammingideas.blogspot.com/2021/02/android-code-for-displaying-video-with.html
https://youtu.be/90hWWAqfdUU
Trust me, this will work for you:
npm config set registry http://registry.npmjs.org/
I had to:
Delete node_modules
Uninstall/reinstall node
npm install [email protected]
worked fine after forcing it to the right sass version, according to the version said to be working with the right node.
NodeJS Minimum node-sass version Node Module
Node 12 4.12+ 72
Node 11 4.10+ 67
Node 10 4.9+ 64
Node 8 4.5.3+ 57
There was lots of other errors that seemed to be caused by the wrong sass version defined.
I discovered the joy of anaconda: https://www.continuum.io/downloads
C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1)
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
voila, a virtual environment is created.
Read carefully the warning message :
The POM for org.raml:jaxrs-code-generator:jar:2.0.0 is missing, no dependency information available
The problem is not the jar, but the pom.xml that is missing.
The pom.xml lists the required dependencies for this jar that Maven will pull during the build and overall the packaging of your application.
So, you may really need it.
Note that this problem may of course occur for other Maven dependencies and the ideas to solve that is always the same.
The Mule website documents very well that in addition to some information related to.
1) Quick workaround : looking for in the internet the pom.xml
of the artifact
Googling the artifact id, the group id and its version gives generally
interesting results : maven repository links to download it.
In the case of the org.raml:jaxrs-code-generator:jar:2.0.0
dependency, you can download the pom.xml
from the Maven mule repository :
2) Clean workaround for a single Maven project : adding the repository declaration in your pom.
In your case, add the Maven mule repositories :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
...
<repositories>
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>mulesoft-snapshots</id>
<name>MuleSoft Snapshot Repository</name>
<url>http://repository.mulesoft.org/snapshots/</url>
<layout>default</layout>
</repository>
</repositories>
...
</project>
3) Clean workaround for any Maven projects : add the repository declaration in your settings.xml
<profile>
<repositories>
...
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>mulesoft-snapshots</id>
<name>MuleSoft Snapshot Repository</name>
<url>http://repository.mulesoft.org/snapshots/</url>
<layout>default</layout>
</repository>
...
</repositories>
</profile>
Note that in some rare cases, the pom.xml
declaring the dependencies is nowhere. So, you have to identify yourself whether the artifact requires dependencies.
I had that problem. And I found this solve. In Android Studio, Open File menu, and go to Project Structure, In Module app, go to dependencies tab and you can add 'com.google.android.gms:play-services:x.x.x' by clicking on + button.
I deleted any existing popper directories, then ran
npm install --save popper.js angular-popper
The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.
example:
return posts.map((post, index) =>
<div key={index}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);
Try this, to call your code in ngOnInit()
someMethod() // emitted method call from output
{
// Your code
}
ngOnInit(){
someMethod(); // call here your error will be gone
}
You can use this command and the video duration is still unaltered.
ffmpeg -i input.mp4 -r 24 output.mp4
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
Right code will be :
Notification.Builder notification=new Notification.Builder(this)
with dependency 26.0.1 and new updated dependencies such as 28.0.0.
Some users use this code in the form of this :
Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.
So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.
Try this code...It will sure work
Just use special `
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
You can see more examples here.
This question has been asked before. Please see this question.
Using the accepted answer and adapting it to your problem you get:
SELECT tt.*
FROM myTable tt
INNER JOIN
(SELECT ID, MAX(Date) AS MaxDateTime
FROM myTable
GROUP BY ID) groupedtt
ON tt.ID = groupedtt.ID
AND tt.Date = groupedtt.MaxDateTime
[SOLVED] Simple one command to fix this issue.
yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm
It's possible to set the center aligned view as an anchor for other views. In the example below "@+id/stat_2" centered horizontally in parent and it serves as an anchor for other views in this layout.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/stat_1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:gravity="center"
android:maxLines="1"
android:text="10"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintEnd_toStartOf="@+id/divider_1" />
<TextView
android:id="@+id/stat_detail_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Streak"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_1"
app:layout_constraintStart_toStartOf="@+id/stat_1"
app:layout_constraintEnd_toEndOf="@+id/stat_1" />
<View
android:id="@+id/divider_1"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginEnd="16dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintEnd_toStartOf="@+id/stat_2"
app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2" />
<TextView
android:id="@+id/stat_2"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="1"
android:text="243"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<TextView
android:id="@+id/stat_detail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Calories Burned"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_2"
app:layout_constraintStart_toStartOf="@+id/stat_2"
app:layout_constraintEnd_toEndOf="@+id/stat_2" />
<View
android:id="@+id/divider_2"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:background="#ccc"
app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2"
app:layout_constraintStart_toEndOf="@+id/stat_2"
app:layout_constraintTop_toTopOf="@+id/stat_2" />
<TextView
android:id="@+id/stat_3"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:gravity="center"
android:maxLines="1"
android:text="3200"
android:textColor="#777"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="@+id/stat_2"
app:layout_constraintStart_toEndOf="@+id/divider_2" />
<TextView
android:id="@+id/stat_detail_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Steps"
android:textColor="#777"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/stat_3"
app:layout_constraintStart_toStartOf="@+id/stat_3"
app:layout_constraintEnd_toEndOf="@+id/stat_3" />
</android.support.constraint.ConstraintLayout>
Here's how it works on smallest smartphone (3.7 480x800 Nexus One) vs largest smartphone (5.5 1440x2560 Pixel XL)
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
First install pylint-django using following command
$ pip install pylint-django
Then run the second command as follows:
$ pylint test_file.py --load-plugins pylint_django
--load-plugins pylint_django is necessary for correctly review a code of django
This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.
<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all
If ESLint is running in the terminal but not inside VSCode, it is probably
because the extension is unable to detect both the local and the global
node_modules
folders.
To verify, press Ctrl+Shift+U in VSCode to open
the Output
panel after opening a JavaScript file with a known eslint
issue.
If it shows Failed to load the ESLint library for the document {documentName}.js
-or- if the Problems
tab shows an error or a warning that
refers to eslint
, then VSCode is having a problem trying to detect the path.
If yes, then set it manually by configuring the eslint.nodePath
in the VSCode
settings (settings.json
). Give it the full path (for example, like
"eslint.nodePath": "C:\\Program Files\\nodejs",
) -- using environment variables
is currently not supported.
This option has been documented at the ESLint extension page.
To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");
To use the EF core SqlServer provider and compile the above code install the EF SqlServer package
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
After compilation before running the code do the following for the first time
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update
To run the code
dotnet run
routerLink
directive as used like this:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
is just a wrapper around imperative navigation using router
and its navigateByUrl method:
router.navigateByUrl('/inbox/33/messages/44')
as can be seen from the sources:
export class RouterLink {
...
@HostListener('click')
onClick(): boolean {
...
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
So wherever you need to navigate a user to another route, just inject the router
and use navigateByUrl
method:
class MyComponent {
constructor(router: Router) {
this.router.navigateByUrl(...);
}
}
There's another method on the router that you can use - navigate:
router.navigate(['/inbox/33/messages/44'])
Using
router.navigateByUrl
is similar to changing the location bar directly–we are providing the “whole” new URL. Whereasrouter.navigate
creates a new URL by applying an array of passed-in commands, a patch, to the current URL.To see the difference clearly, imagine that the current URL is
'/inbox/11/messages/22(popup:compose)'
.With this URL, calling
router.navigateByUrl('/inbox/33/messages/44')
will result in'/inbox/33/messages/44'
. But calling it withrouter.navigate(['/inbox/33/messages/44'])
will result in'/inbox/33/messages/44(popup:compose)'
.
Read more in the official docs.
(change)
event bound to classical input change event.
https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">
(ngModelChange)
is the @Output
of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code, (ngModelChange)
emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
// do something with new value
}
Basically, it seems like there is no big difference between two, but ngModel
events gains the power when you use [ngValue]
.
<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
<option *ngFor="let currentData of allData" [ngValue]="currentData">
{{data.name}}
</option>
</select>
dataChanged(newObj) {
// here comes the object as parameter
}
assume you try the same thing without "ngModel
things"
<select (change)="changed($event)">
<option *ngFor="let currentData of allData" [value]="currentData.id">
{{data.name}}
</option>
</select>
changed(e){
// event comes as parameter, you'll have to find selectedData manually
// by using e.target.data
}
You can either return a response as String
as suggested by @vagaasen or you can use ResponseEntity
Object provided by Spring as below. By this way you can also return Http status code
which is more helpful in webservice call.
@RestController
@RequestMapping("/api")
public class MyRestController
{
@GetMapping(path = "/hello", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> sayHello()
{
//Get data from service layer into entityList.
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("aa", "bb");
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
}
<section [ngClass]="{'class1': expression1, 'class2': expression2,
'class3': expression3}">
Don't forget to add single quotes around class names.
Turns out this could also be caused by BuildEvents. For me I was referencing $(SolutionDir) there. With a regular build this variable has value, but running dotnet * commands is done at project level apparently. $(SolutionDir) comes out like Undefined in verbose mode (-v). This seems like a bug to me.
Python can do unexpected things when new objects are defined from existing ones. You stated in a comment above that your dataframe is defined along the lines of df = df_all.loc[df_all['issueid']==specific_id,:]
. In this case, df
is really just a stand-in for the rows stored in the df_all
object: a new object is NOT created in memory.
To avoid these issues altogether, I often have to remind myself to use the copy
module, which explicitly forces objects to be copied in memory so that methods called on the new objects are not applied to the source object. I had the same problem as you, and avoided it using the deepcopy
function.
In your case, this should get rid of the warning message:
from copy import deepcopy
df = deepcopy(df_all.loc[df_all['issueid']==specific_id,:])
df['industry'] = 'yyy'
EDIT: Also see David M.'s excellent comment below!
df = df_all.loc[df_all['issueid']==specific_id,:].copy()
df['industry'] = 'yyy'
In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):
kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*
sudo apt-get autoremove
sudo rm -rf ~/.kube
And restart the computer.
when you setup the java home variable try to target path till JDK instead of java. setup path like: C:\Program Files\Java\jdk1.8.0_231
if you make path like C:\Program Files\Java it will run java but it will not run maven.
configurations.all {_x000D_
resolutionStrategy.force_x000D_
//"com.android.support:appcompat-v7:25.3.1"_x000D_
//here put the library that made the error with the version you want to use_x000D_
}
_x000D_
add this to gradle (project) inside allprojects
Check your OpenCV version
import cv2
cv2.__version__
If your are running Python v3.x and OpenCV v4 and above:
pip install opencv-contrib-python
Try running your program again. This should now work.
You can do this by changing the gradle file.
build.gradle > change
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
gradle-wrapper.properties > update
distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip
That 2GB
limit you see is the total memory of the VM in which docker runs.
If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:
But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.
See this for Mac:
https://docs.docker.com/docker-for-mac/#memory
MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.
For Windows:
https://docs.docker.com/docker-for-windows/#advanced
Memory - Change the amount of memory the Docker for Windows Linux VM uses
Appart from setting maven source url to your gradle, I would suggest to add both design and appcompat libraries. Currently the latest version is 26.1.0
maven {
url "https://maven.google.com"
}
...
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
Is there a problem with this formulation?
I don't see any.
Is there a better way?
I'd collapse the two statements into one:
const Colors = Object.freeze({
RED: Symbol("red"),
BLUE: Symbol("blue"),
GREEN: Symbol("green")
});
If you don't like the boilerplate, like the repeated Symbol
calls, you can of course also write a helper function makeEnum
that creates the same thing from a list of names.
Deleted the package-lock.json file & then ran
npm install
Zookeeper is required for running Kafka. zookeeper is must. still if you want to see topic list without zookeeper then you need kafka monitoring tool such as Kafka Monitor Tool, kafka-manager etc.
There are 2 solutions for this, but it return all columns separately:
import functools
dfs = [df1, df2, df3]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
date a_x b_x a_y b_y c_x a b c_y
0 May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
0_a 0_b 1_a 1_b 1_c 2_a 2_b 2_c
date
May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
I believe TLSV1_ALERT_PROTOCOL_VERSION
is alerting you that the server doesn't want to talk TLS v1.0 to you. Try to specify TLS v1.2 only by sticking in these lines:
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# Create HTTPS connection
c = HTTPSConnection("0.0.0.0", context=context)
Note, you may need sufficiently new versions of Python (2.7.9+ perhaps?) and possibly OpenSSL (I have "OpenSSL 1.0.2k 26 Jan 2017" and the above seems to work, YMMV)
Another thing that you should check is the Target Framework of any referenced projects to make sure that the calling project is using the same or later version of the framework.
I had this issue, I tried all of the previously suggested answers and then on a hunch checked the frameworks. One of projects being referenced was targeting 4.6.1 when the calling project was only 4.5.2.
Spring sets the default content-type to octet-stream
when the response is missing that field. All you need to do is to add a message converter to fix this.
calling select
will result is lazy
evaluation: for example:
val df1 = df.select("col1")
val df2 = df1.filter("col1 == 3")
both above statements create lazy path that will be executed when you call action on that df
, such as show
, collect
etc.
val df3 = df2.collect()
use .explain
at the end of your transformation to follow its plan
here is more detailed info Transformations and Actions
Simply you can use this code for solve it:
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
appDb.daoAccess().someJobes();//replace with your code
}
});
Or in lambda you can use this code:
Executors.newSingleThreadExecutor().execute(() -> appDb.daoAccess().someJobes());
You can replace appDb.daoAccess().someJobes()
with your own code;
Move the queue to self instead of as an argument to your functions package
and send
Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager
and InjectionManagerFactory
. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory
. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2
others are talking about.
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.26</version>
</dependency>
The CDI dependency is
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
<version>2.26</version>
</dependency>
This (jersey-cdi2-se) should only be used for SE environments and not EE environments.
Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManager
s, though others have made attempts at implementing one for Guice.
This worked for me
pip install django-csvimport --upgrade
are you importing it in your app.module.ts
like so and remove the directives bit:-
@NgModule({
bootstrap: [AppComponent],
imports: [MyComponentModule],// or whatever the name of the module is that declares your component.
declarations: [AppComponent],
providers: []
})
export class AppModule {}
Your MyComponentModule
should be like this:-
@NgModule({
imports: [],
exports: [MyComponentComponent],
declarations: [MyComponentComponent],
providers: [],
})
export class MyComponentModule {
}
It's complicated.
First of all, in this code
const p = new Promise((resolve) => {
resolve(4);
});
the type of p
is inferred as Promise<{}>
. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p
should be Promise<number>
.
Then, Promise<{}>
is compatible with Promise<number>
, because basically the only property a promise has is then
method, and then
is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1
.
But the purpose of async
is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2
because {}
is obvioulsy not compatible with number
.
So the async
behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:
const whatever2 = async (): Promise<number> => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
In React 16.8+, using functional components, you would do
import React from 'react';
import { Button, Linking } from 'react-native';
const ExternalLinkBtn = (props) => {
return <Button
title={props.title}
onPress={() => {
Linking.openURL(props.url)
.catch(err => {
console.error("Failed opening page because: ", err)
alert('Failed to open page')
})}}
/>
}
export default function exampleUse() {
return (
<View>
<ExternalLinkBtn title="Example Link" url="https://example.com" />
</View>
)
}
The other answers didn't work for me so here I share my solution in case it might help somebody else:
My problem was that I was configuring the Podfile of my XCode-Project for the wrong platform. Changing "platform :ios" at the beginning of my Podfile to "platform :macos" worked for me to get rid of the error.
ECMAScript 6 introduced the let
statement. You can use it in a for
statement.
var ids:string = [];
for(let result of this.results){
ids.push(result.Id);
}
I installed the 8.1 SDK's version:
https://developer.microsoft.com/en-us/windows/downloads/sdk-archive
It used 1GB (a little more) in the installation.
Update October, 9. There's a https error: the sdksetup link is https://go.microsoft.com/fwlink/p/?LinkId=323507
"Save link as" should help.
For default exports you should use:
import * as fs from 'fs';
Or in case the module has named exports:
import {fs} from 'fs';
Example:
//module1.js
export function function1() {
console.log('f1')
}
export function function2() {
console.log('f2')
}
export default function1;
And then:
import defaultExport, { function1, function2 } from './module1'
defaultExport(); // This calls function1
function1();
function2();
Additionally, you should use Webpack or something similar to be able to use ES6 import
your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if
as a top-level step in declarative, so you need to wrap it in a script
step. here's a working declarative version:
pipeline {
agent any
stages {
stage('test') {
steps {
sh 'echo hello'
}
}
stage('test1') {
steps {
sh 'echo $TEST'
}
}
stage('test3') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
}
}
you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!
For your case, add the following code to vscode's settings.json
.
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]
For the other who got troubles with pip packages, you can go with
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]
You should replace python3.7
above with your python version.
For me in Java 11 and gradle this is what worked out:
plugins {
id 'java'
}
dependencies {
runtimeOnly 'javax.xml.bind:jaxb-api:2.3.1'
}
I came here with similar error:
System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'
After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
int Id { get; set; }
// ...
Should be this..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
public int Id { get; set; } // must be public!
// ...
I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent]
from decorator.
import {myDirective} from './myDirective';
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]
IMPORTANT DISCLAIMER: Information provided below is for educational purposes only! Extending a trial period of Visual Studio Community 2017 might be ILLEGAL!
So let's get started.
Registry key of interest: HKEY_CLASSES_ROOT\Licenses\5C505A59-E312-4B89-9508-E162F8150517\08878
. I assume the 08878
subkey may differ from installation to installation (why not, isn't?). I have tested only on my own one. So check other subkeys if you can not match proper values described below. Binary value stored in that key is encrypted with CryptProtectData
. So decrypt it first with CryptUnprotectData
. Bytes of interest (little-endian):
[-16]
and [-15]
is a year of expiration;[-14]
and [-13]
is a month of expiration;[-12]
and [-11]
is a day of expiration.Increasing these values (preferable the year :) ) WILL extend your trial period and get rid of a blocking screen! I know nothing of such a tool that allows to edit encrypted registry values, so my small program in C++
and Windows API
looks like:
RegGetValue
CryptUnprotectData
Data.pbData[Data.cbData-16]++;
CryptProtectData
RegSetValue
Actual language doesn't matter if you have access to registry and crypto functions in your language. I'm just fluent in C++
. Sorry, I do not publish a ready-to-use code for ethical reason.
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>
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.
mode: 'no-cors'
won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.
What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin
is in a response, then browsers will relax that blocking and allow your code to access the response.
But if a site sends no Access-Control-Allow-Origin
in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors'
(in fact that’ll ensure your frontend code can’t access the response contents).
However, one thing that will work: if you send your request through a CORS proxy.
You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/
.
Prefix your request URL with your proxy URL; for example:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:
https://example.com
.https://example.com
.Access-Control-Allow-Origin
header to the response.The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends back the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight successful.
I can hit this endpoint,
http://catfacts-api.appspot.com/api/facts?number=99
via Postman
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin
response header.
http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin
response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin
response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin
response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin
header added is what the browser sees, so the browser lets your frontend code actually access the response.
So I am trying to pass in an object, to my Fetch which will disable CORS
You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.
But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.
No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.
You most likely never want to use mode: 'no-cors'
in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors'
actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.
As far as the cases when you would want to consider using mode: 'no-cors'
, see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:
In the limited case when you’re using JavaScript to put content from another origin into a <script>
, <link rel=stylesheet>
, <img>
, <video>
, <audio>
, <object>
, <embed>
, or <iframe>
element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href
or src
attribute for the element.
When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.
But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.
I have also tried to pass in the object
{ mode: 'opaque'}
There is no mode: 'opaque'
request mode — opaque
is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors
mode.
But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.
if your intention is send the full array from the html to the controller, can use this:
from the blade.php:
<input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}">
in controller
public function Get(Request $req) {
$quotation = array('quotation' => json_decode($req->quotation));
//or
return view('quotation')->with('quotation',json_decode($req->quotation))
}
I would suggest launching Jupyter lab/notebook from your base environment and selecting the right kernel.
How to add conda environment to jupyter lab should contains the info needed to add the kernel to your base environment.
Disclaimer : I asked the question in the topic I linked, but I feel it answers your problem too.
in your CFG file please change the hibernate dialect
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
The accepted answer is good, but it does NOT solve the problem when we need our component to reflect changes in URL.
Say, your component's code is something like:
export const Customer = (props) => {
const history = useHistory();
...
}
And you change URL:
const handleGoToPrev = () => {
history.push(`/app/customer/${prevId}`);
}
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import store from '../store/store';
export const PrivateRoute = ({ component: Component, ...rest }) => {
let isLoggedIn = !!store.getState().data.user;
return (
<Route {...rest} render={props => isLoggedIn
? (
<Component key={props.match.params.id || 'empty'} {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
} />
)
}
<PrivateRoute exact path="/app/customer/:id" component={Customer} />
As I have noticed this error occurs under two circumstances,
so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)
Hope this helps.
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
var tokne= response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
I had a similar situation. On top of what you did, I wanted to center my columns in the container while not allowing empty columns to for them left or right:
.grid {
display: grid;
grid-gap: 10px;
justify-content: center;
grid-template-columns: repeat(auto-fit, minmax(200px, auto));
}
As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.7 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/bin/python3.7 2 manual mode
Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Issue: It's because either you are not stopping your application or the application is already somehow running on the same port somehow.
Solution, Before starting it another time, the earlier application needs to be killed and the port needs to be freed up.
Depending on your platform you can run the below commands to stop the application,
on windows
netstat -anp | find "your application port number"` --> find PID
taskkill /F /PID
on Linux,
netstat -ntpl | grep "your application port number"
kill pid // pid you will get from previous command
on Mac OS
lsof -n -iTCP:"port number"
kill pid //pid you will get from previous command
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
How to post file using an object in memory (like a JSON object):
import axios from 'axios';
import * as FormData from 'form-data'
async function sendData(jsonData){
// const payload = JSON.stringify({ hello: 'world'});
const payload = JSON.stringify(jsonData);
const bufferObject = Buffer.from(payload, 'utf-8');
const file = new FormData();
file.append('upload_file', bufferObject, "b.json");
const response = await axios.post(
lovelyURL,
file,
headers: file.getHeaders()
).toPromise();
console.log(response?.data);
}
<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>
To add then template we just have to bind it to a template explicitly.
<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div>
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>
I had to install the NVIDIA 367.57 driver and CUDA 7.5 with Tensorflow on the g2.2xlarge Ubuntu 14.04LTS instance. e.g. nvidia-graphics-drivers-367_367.57.orig.tar
Now the GRID K520 GPU is working while I train tensorflow models:
ubuntu@ip-10-0-1-70:~$ nvidia-smi
Sat Apr 1 18:03:32 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57 Driver Version: 367.57 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GRID K520 Off | 0000:00:03.0 Off | N/A |
| N/A 39C P8 43W / 125W | 3800MiB / 4036MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 2254 C python 3798MiB |
+-----------------------------------------------------------------------------+
ubuntu@ip-10-0-1-70:~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery$ ./deviceQuery
./deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "GRID K520"
CUDA Driver Version / Runtime Version 8.0 / 7.0
CUDA Capability Major/Minor version number: 3.0
Total amount of global memory: 4036 MBytes (4232052736 bytes)
( 8) Multiprocessors, (192) CUDA Cores/MP: 1536 CUDA Cores
GPU Max Clock rate: 797 MHz (0.80 GHz)
Memory Clock rate: 2500 Mhz
Memory Bus Width: 256-bit
L2 Cache Size: 524288 bytes
Maximum Texture Dimension Size (x,y,z) 1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
Maximum Layered 1D Texture Size, (num) layers 1D=(16384), 2048 layers
Maximum Layered 2D Texture Size, (num) layers 2D=(16384, 16384), 2048 layers
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 49152 bytes
Total number of registers available per block: 65536
Warp size: 32
Maximum number of threads per multiprocessor: 2048
Maximum number of threads per block: 1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)
Maximum memory pitch: 2147483647 bytes
Texture alignment: 512 bytes
Concurrent copy and kernel execution: Yes with 2 copy engine(s)
Run time limit on kernels: No
Integrated GPU sharing Host Memory: No
Support host page-locked memory mapping: Yes
Alignment requirement for Surfaces: Yes
Device has ECC support: Disabled
Device supports Unified Addressing (UVA): Yes
Device PCI Domain ID / Bus ID / location ID: 0 / 0 / 3
Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 7.0, NumDevs = 1, Device0 = GRID K520
Result = PASS
Numpy arrays do not have an append method. Use the Numpy append function instead:
import numpy as np
array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely
For example, if array_1 and array_2 have the following values:
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
If you call np.append without specifying an axis value, like so:
array_3 = np.append(array_1, array_2)
array_3 will have the following value:
array([1, 2, 3, 4])
Else, if you call np.append with an axis value of 0, like so:
array_3 = np.append(array_1, array_2, axis=0)
array_3 will have the following value:
array([[1, 2],
[3, 4]])
More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
if you used vue-cli and webpack when you created your project.
you can use just
npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.
UPD Today I avoid Docker Swarm, secrets, and configs. I'd run it with docker-compose
and the .env
file. As long as I don't need autoscaling. If I do, I'd probably choose k8s. And database passwords, root account or not... Do they really matter when you're running a single database in a container not connected to the outside world?.. I'd like to know what you think about it, but Stack Overflow is probably not well suited for this sort of communication.
Mongo image can be affected by MONGO_INITDB_DATABASE
variable, but it won't create the database. This variable determines current database when running /docker-entrypoint-initdb.d/*
scripts. Since you can't use environment variables in scripts executed by Mongo, I went with a shell script:
docker-swarm.yml
:
version: '3.1'
secrets:
mongo-root-passwd:
file: mongo-root-passwd
mongo-user-passwd:
file: mongo-user-passwd
services:
mongo:
image: mongo:3.2
environment:
MONGO_INITDB_ROOT_USERNAME: $MONGO_ROOT_USER
MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/mongo-root-passwd
MONGO_INITDB_USERNAME: $MONGO_USER
MONGO_INITDB_PASSWORD_FILE: /run/secrets/mongo-user-passwd
MONGO_INITDB_DATABASE: $MONGO_DB
volumes:
- ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
secrets:
- mongo-root-passwd
- mongo-user-passwd
init-mongo.sh
:
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
var admin = db.getSiblingDB('admin');
admin.auth(rootUser, rootPassword);
var user = '$MONGO_INITDB_USERNAME';
var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});
EOF
Alternatively, you can store init-mongo.sh
in configs (docker config create
) and mount it with:
configs:
init-mongo.sh:
external: true
...
services:
mongo:
...
configs:
- source: init-mongo.sh
target: /docker-entrypoint-initdb.d/init-mongo.sh
And secrets can be not stored in a file.
I was facing the same issue, in my case in order to resolved
James023 already stated the correct answer. Just formatting it
if you have not configured jupyter_notebook_config.py file already
Step1: generate the file by typing this line in console
jupyter notebook --generate-config
Step2: edit the values
gedit /home/koushik/.jupyter/jupyter_notebook_config.py
( add the following two line anywhere because the default values are commented anyway)
c.NotebookApp.allow_origin = '*'
#allow all origins
c.NotebookApp.ip = '0.0.0.0'
# listen on all IPs
Step3: once you closed the gedit, in case your port is blocked
sudo ufw allow 8888
# enable your tcp:8888 port, which is ur default jupyter port
Step4: set a password
jupyter notebook password
# it will prompt for password
Step5: start jupyter
jupyter notebook
and connect like http://xxx.xxx.xxx.xxx:8888/login?
Customizing CORS for Angular 5 and Spring Security (Cookie base solution)
On the Angular side required adding option flag withCredentials: true
for Cookie transport:
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(url, { withCredentials: true });
}
On Java server-side required adding CorsConfigurationSource
for configuration CORS policy:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// This Origin header you can see that in Network tab
configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowedHeaders(Arrays.asList("content-type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Method configure(HttpSecurity http)
by default will use corsConfigurationSource
for http.cors()
Old question, but there's an easier way.
sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])
This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Found another way. Set AutoFilter for all columns (important or you will misalign data) by selecting the header row > 'Data' tab > Sort and filter - 'Filter'. Use drop-down in first data column, untick 'Select all' and select only '(Blanks)' option > [OK]. Highlight rows (now all together) > right click > 'Delete row'. Head back to the drop-down > 'Select all'. Presto :)
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.
For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.
Upcasting (using (Employee)someInstance
) is generally easy as the compiler can tell you at compile time if a type is derived from another.
Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.
To test if an employee is a manager:
Employee m = new Manager();
Employee e = new Employee();
if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");
You can also use this
Employee someEmployee = e as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (e) is a manager");
Employee someEmployee = m as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (m) is a manager");
sudo apt install libssl-dev
works on ubuntu 18.04.
Shorter version:
import inspect
def f1(): f2()
def f2():
print 'caller name:', inspect.stack()[1][3]
f1()
(with thanks to @Alex, and Stefaan Lippen)
.loc
and .iloc
are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc
allows label-based indexing, while .iloc
allows position-based indexing.
If you get confused by .loc
and .iloc
, keep in mind that .iloc
is based on the index (starting with i) position, while .loc
is based on the label (starting with l).
.loc
.loc
is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).
iloc
.iloc
does the lookup based on index position, i.e., pandas
behaves similarly to a Python list. pandas
will raise an IndexError
if there is no index at that location.
The following examples are presented to illustrate the differences between .iloc
and .loc
. Let's consider the following series:
>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.iloc
Examples
>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993 9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.loc
Examples
>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990 11
1993 9
Name: Magic Numbers, dtype: int64
Because s
has string index values, .loc
will fail when
indexing with an integer:
>>> s.loc[0]
Traceback (most recent call last):
...
KeyError: 0
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
Comparing non-primitives (aka Objects) in Java with ==
compares their reference instead of their values. Long
is a class and thus Long
values are Objects.
The problem is that the Java Developers wanted people to use Long
like they used long
to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long
-values will be changed to Long
-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.
So to be safe and to have predictable results always use .equals()
to compare objects and do not rely on autoboxing in this case:
Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }
This is marked as a duplicate for printing a byte[]. Note: for a byte array there are additional methods which may be appropriate.
You can print it as a String if it contains ISO-8859-1 chars.
String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);
or if it contains a UTF-8 string
String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);
or if you want print it as hexadecimal.
String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);
or if you want print it as base64.
String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);
or if you want to print an array of signed byte values
String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
bytes2[i] = Byte.parseByte(split[i]);
or if you want to print an array of unsigned byte values
String s = Arrays.toString(
IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.
First WebClient
is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
Like @Lo Juego said, read the article
a, a:active, a:focus {
outline: none;
}
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
I am using Springboot 2.0.6 and for some reason, the app yml changes did not work. And also I had more requirements.
I tried creating ObjectMapper and marking it as Primary but spring boot complained that I already have jacksonObjectMapper as marked Primary!!
So this is what I did. I made changes to the internal mapper.
My Serializer and Deserializer are special - they deal with 'dd/MM/YYYY'; and while de-serializing - it tries its best to use 3-4 popular format to make sure I have some LocalDate.
@Autowired
ObjectMapper mapper;
@PostConstruct
public ObjectMapper configureMapper() {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
return mapper;
}
Here's another option that's longer but may be more readable:
Boolean(Number("0")); // false
Boolean(Number("1")); // true
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
Admittedly, I haven't tried any of the solutions listed above but I was (eventually) jumping for joy when I tried jschr's Bootstrap-modal project in Bootstrap 3 (linked to in the top answer). The js was giving me trouble so I abandoned it (maybe mine was a unique issue or it works fine for Bootstrap 2) but the CSS files on their own seem to do the trick in Android's native 2.3.4 browser.
In my case, I've resorted so far to using (sub-optimal) user-agent detection before using the overrides to allow expected behaviour in modern phones.
For example, if you wanted all Android phones ver 3.x and below only to use the full set of hacks you could add a class "oldPhoneModalNeeded" to the body after user agent detection using javascript and then modify jschr's Bootstrap-modal CSS properties to always have .oldPhoneModalNeeded as an ancestor.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
You can use the markup below, but note that if you set the textAllCaps
to true
the underline effect would be removed.
<resource>
<string name="my_string_value">I am <u>underlined</u>.</string>
</resources>
Note
Using textAllCaps with a string (login_change_settings) that contains markup; the markup will be dropped by the caps conversion
The textAllCaps text transform will end up calling toString on the CharSequence, which has the net effect of removing any markup such as . This check looks for usages of strings containing markup that also specify textAllCaps=true.
You'll need to loop through your array elements, create a new DOM node for each and append it to your object.
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}?
the key point is finding the right path where your grunt was installed.
I installed grunt through npm, but my grunt path was /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin/grunt
. So after I added /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin
to ~/.bash_profile
,and source ~/.bash_profile
, It worked.
So the steps are as followings:
1. find the path where your grunt was installed(when you installed grunt, it told you. if you don't remember, you can install it one more time)
2. vi ~/.bash_profile
3. export PATH=$PATH:/your/path/where/grunt/was/installed
4. source ~/.bash_profile
You can refer http://www.hongkiat.com/blog/grunt-command-not-found/
Found the solution!
I had something similar:
It took a while to figure this out. Have tried:
1. Reinstalling the whole VS2019 web development environment
2. Deleting `%userprofile%\Documents\IISExpress`
3. Deleting projects' `.vs` folders
4. Removing `IIExpress 10` from `Programms` in Win10
5. Changing projects' settings/properties
The main problem was a registry entry Start
located at
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP
So, changing value of a key Start
from 4
to 3
and rebooting fixed the issue.
One of possible reason I would recall is running the Laragon which required changing this value to 4
to start an Nginx
web server.
The command
clause does work as @Karthik says above.
As a simple example, the following service will have a -inMemory
added to its ENTRYPOINT
when docker-compose up
is run.
version: '2'
services:
local-dynamo:
build: local-dynamo
image: spud/dynamo
command: -inMemory
As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.
The content code is \00d7.
Example
div:after{
display: inline-block;
content: "\00d7"; /* This will render the 'X' */
}
You can then style and position the pseudo selector in any way you want. Hope this helps someone :).
My favourite recipe to switch back and forth between windows:
function! SwitchPrevWin()
let l:winnr_index = winnr()
if l:winnr_index > 1
let l:winnr_index -= 1
else
"set winnr_index to max window open
let l:winnr_index = winnr('$')
endif
exe l:winnr_index . "wincmd w"
endfunction
nmap <M-z> :call SwitchPrevWin()
imap <M-z> <ESC>:call SwitchPrevWin()
nmap <C-z> :wincmd w
imap <C-z> <ESC>:wincmd w
This is probably a configuration error. If you insist on using PHP mail
function, you will have to edit php.ini
.
If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.
Successfully installed it on OSX using homebrew:
brew install sip
brew install pyqt
which (currently) installs PyQt4. Anaconda is the main python on the machine (OSX 10.8.5).
All you need is a test version of HttpMessageHandler
class which you pass to HttpClient
ctor. The main point is that your test HttpMessageHandler
class will have a HttpRequestHandler
delegate that the callers can set and simply handle the HttpRequest
the way they want.
public class FakeHttpMessageHandler : HttpMessageHandler
{
public Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> HttpRequestHandler { get; set; } =
(r, c) =>
new HttpResponseMessage
{
ReasonPhrase = r.RequestUri.AbsoluteUri,
StatusCode = HttpStatusCode.OK
};
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(HttpRequestHandler(request, cancellationToken));
}
}
You can use an instance of this class to create a concrete HttpClient instance. Via the HttpRequestHandler delegate you have full control over outgoing http requests from HttpClient.
You can always install Cygwin to run a Unix shell under Windows. I used Cygwin extensively with Window XP.
From matplotlib version 2.1 onwards, you may use a figure legend. Instead of ax.legend()
, which produces a legend with the handles from the axes ax
, one can create a figure legend
fig.legend(loc="upper right")
which will gather all handles from all subplots in the figure. Since it is a figure legend, it will be placed at the corner of the figure, and the loc
argument is relative to the figure.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, '-', label = 'Quantity 1')
ax2 = ax.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')
fig.legend(loc="upper right")
ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")
plt.show()
In order to place the legend back into the axes, one would supply a bbox_to_anchor
and a bbox_transform
. The latter would be the axes transform of the axes the legend should reside in. The former may be the coordinates of the edge defined by loc
given in axes coordinates.
fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
Using JavaScriptSerializer() is less strict than the generic solution offered : public static T Deserialize(string json)
That might come handy when passing json to the server that does not match exactly the Object definition you are trying to convert to.
Best practices :
Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.
Not putting a link to your favicon can slow down the page load.
In a django project, suppose the path to your favicon is :
myapp/static/icons/favicon.png
in your django templates (preferably in the base template), add this line to head of the page :
<link rel="shortcut icon" href="{% static 'icons/favicon.png' %}">
Note :
We suppose, the static settings are well configured in settings.py.
The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.
So you have either closed the socket before calling write()
or you have corrupted the value of 'sockfd' somewhere in your code.
It would be useful to trace all calls to close()
, and the value of 'sockfd' prior to the write()
calls.
Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror()
is invalid, as it may disturb the value of errno
. Indeed it may have done so in this case, and the real underlying error may be different.
If anybody is interested in using regex with CLR here is a solution. The function below (C# .net 4.5) returns a 1 if the pattern is matched and a 0 if the pattern is not matched. I use it to tag lines in sub queries. The SQLfunction attribute tells sql server that this method is the actual UDF that SQL server will use. Save the file as a dll in a place where you can access it from management studio.
// default using statements above
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;
namespace CLR_Functions
{
public class myFunctions
{
[SqlFunction]
public static SqlInt16 RegexContain(SqlString text, SqlString pattern)
{
SqlInt16 returnVal = 0;
try
{
string myText = text.ToString();
string myPattern = pattern.ToString();
MatchCollection mc = Regex.Matches(myText, myPattern);
if (mc.Count > 0)
{
returnVal = 1;
}
}
catch
{
returnVal = 0;
}
return returnVal;
}
}
}
In management studio import the dll file via programability -- assemblies -- new assembly
Then run this query:
CREATE FUNCTION RegexContain(@text NVARCHAR(50), @pattern NVARCHAR(50))
RETURNS smallint
AS
EXTERNAL NAME CLR_Functions.[CLR_Functions.myFunctions].RegexContain
Then you should have complete access to the function via the database you stored the assembly in.
Then use in queries like so:
SELECT *
FROM
(
SELECT
DailyLog.Date,
DailyLog.Researcher,
DailyLog.team,
DailyLog.field,
DailyLog.EntityID,
DailyLog.[From],
DailyLog.[To],
dbo.RegexContain(Researcher, '[\p{L}\s]+') as 'is null values'
FROM [DailyOps].[dbo].[DailyLog]
) AS a
WHERE a.[is null values] = 0
You don't want to do that. It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can't access it to call Iterator.remove
.
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Instead write your code:
List<String> names = ....
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
// Do something
it.remove();
}
Note that the code calls Iterator.remove
, not List.remove
.
Addendum:
Even if you are removing an element that has not been iterated over yet, you still don't want to modify the collection and then use the Iterator
. It might modify the collection in a way that is surprising and affects future operations on the Iterator
.
Not remembering how i've installed yarn the command that worked for me was:
yarn policies set-version
This command updates the current yarn version to the latest stable.
From the documentation:
Note that this command also is the preferred way to upgrade Yarn - it will work no matter how you originally installed it, which might sometimes prove difficult to figure out otherwise.
A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async
The defer and async attributes must not be specified if the src attribute is not present.
There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:
The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
For those using Redux Pattern
I added in the file-saver as @Hector Cuevas named in his answer. Using Angular2 v. 2.3.1, I didn't need to add in the @types/file-saver.
The following example is to download a journal as PDF.
The journal actions
public static DOWNLOAD_JOURNALS = '[Journals] Download as PDF';
public downloadJournals(referenceId: string): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS,
payload: { referenceId: referenceId }
};
}
public static DOWNLOAD_JOURNALS_SUCCESS = '[Journals] Download as PDF Success';
public downloadJournalsSuccess(blob: Blob): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS_SUCCESS,
payload: { blob: blob }
};
}
The journal effects
@Effect() download$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS)
.switchMap(({payload}) =>
this._journalApiService.downloadJournal(payload.referenceId)
.map((blob) => this._actions.downloadJournalsSuccess(blob))
.catch((err) => handleError(err, this._actions.downloadJournalsFail(err)))
);
@Effect() downloadJournalSuccess$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS_SUCCESS)
.map(({payload}) => saveBlobAs(payload.blob, 'journal.pdf'))
The journal service
public downloadJournal(referenceId: string): Observable<any> {
const url = `${this._config.momentumApi}/api/journals/${referenceId}/download`;
return this._http.getBlob(url);
}
The HTTP service
public getBlob = (url: string): Observable<any> => {
return this.request({
method: RequestMethod.Get,
url: url,
responseType: ResponseContentType.Blob
});
};
The journal reducer Though this only sets the correct states used in our application I still wanted to add it in to show the complete pattern.
case JournalActions.DOWNLOAD_JOURNALS: {
return Object.assign({}, state, <IJournalState>{ downloading: true, hasValidationErrors: false, errors: [] });
}
case JournalActions.DOWNLOAD_JOURNALS_SUCCESS: {
return Object.assign({}, state, <IJournalState>{ downloading: false, hasValidationErrors: false, errors: [] });
}
I hope this is helpful.
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
Assert is very useful when developing. You use it when something just cannot happen if your code is working correctly. It's easy to use, and can stay in the code for ever, because it will be turned off in real life.
If there is any chance that the condition can occur in real life, then you must handle it.
I love it, but don't know how to turn it on in Eclipse/Android/ADT . It seems to be off even when debugging. (There is a thread on this, but it refers to the 'Java vm', which does not appear in the ADT Run Configuration).
Spring is great for gluing instances of classes together. You know that your Hibernate classes are always going to need a datasource, Spring wires them together (and has an implementation of the datasource too).
Your data access objects will always need Hibernate access, Spring wires the Hibernate classes into your DAOs for you.
Additionally, Spring basically gives you solid configurations of a bunch of libraries, and in that, gives you guidance in what libs you should use.
Spring is really a great tool. (I wasn't talking about Spring MVC, just the base framework).
I fixed this problem by changing the first line in Application.mk from
APP_STL := gnustl_static
to
APP_STL := c++_static
The expires
and add_header
directives have no impact on NGINX caching the files, those are purely about what the browser sees.
What you likely want instead is:
location stuffyoudontwanttocache {
# don't cache it
proxy_no_cache 1;
# even if cached, don't try to use it
proxy_cache_bypass 1;
}
Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?
The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?
You can use git blame
for this, it will anotate each line with a SHA1 and a date when it was changed. git blame
can also tell you when a certain line was deleted or where it was moved if you are interested in that.
If you are trying to find out, when a certain bug was introduced, git bisect
is a very powerfull tool. git bisect
will do a binary search on your history. You can use git bisect start
to start bisecting, then git bisect bad
to mark a commit where the bug is present and git bisect good
to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.
Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.
If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.
You may connect to Oracle database using sqlplus:
sqlplus "/as sysdba"
Then create new users and assign privileges.
grant all privileges to dac;
Use a Macro.
Macro>Start Recording
Use the keyboard to make your changes in a repeatable manner e.g.
home>type "able">end>down arrow>home
Then go back to the menu and click stop recording then run a macro multiple times.
That should do it and no regex based complications!
We wrote a wrapper class that captures the buffer and converts the printed output to an exception. this lets us upgrade the phpmailer file without having to remember to comment out the echo statements each time we upgrade.
The wrapper class has methods something along the lines of:
public function AddAddress($email, $name = null) {
ob_start();
parent::AddAddress($email, $name);
$error = ob_get_contents();
ob_end_clean();
if( !empty($error) ) {
throw new Exception($error);
}
}
Since most answers focused on the theory I think I can add something to the discussion by giving a practical test I did. In my database I have around 4.5 million UUIDs generated using Java 8 UUID.randomUUID(). The following ones are just some I found out:
c0f55f62-b990-47bc-8caa-f42313669948
c0f55f62-e81e-4253-8299-00b4322829d5
c0f55f62-4979-4e87-8cd9-1c556894e2bb
b9ea2498-fb32-40ef-91ef-0ba00060fe64
be87a209-2114-45b3-9d5a-86d00060fe64
4a8a74a6-e972-4069-b480-bdea1177b21f
12fb4958-bee2-4c89-8cf8-edea1177b21f
If it was truly random, the probability of having these kind of similar UUIDs would be considerably low (see edit), since we're considering only 4.5 million entries. So, although this function is good, in terms of not having collisions, for me it doesn't seem that good as it would be in theory.
Edit:
A lot of people seem to not understand this answer so I'll clarify my point: I know that the similarities are "small" and far from a full collision. However, I just wanted to compare the Java's UUID.randomUUID() with a true random number generator, which is the actual question.
In a true random number generator, the probability of the last case happening would be around = 0.007%. Therefore, I think my conclusion stands.
Formula is explained in this wiki article en.wikipedia.org/wiki/Birthday_problem
Time package in Golang has some methods that might be worth looking.
func (Time) Format
func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,
Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.
Source (http://golang.org/pkg/time/#Time.Format)
I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)
func ExampleTime_Format() {
// layout shows by example how the reference time should be represented.
const layout = "Jan 2, 2006 at 3:04pm (MST)"
t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
fmt.Println(t.Format(layout))
fmt.Println(t.UTC().Format(layout))
// Output:
// Nov 10, 2009 at 3:00pm (PST)
// Nov 10, 2009 at 11:00pm (UTC)
}
Here is another way to display PDF inside Div by using Iframe like below.
<div>_x000D_
<iframe src="/pdf/test.pdf" style="width:100%;height:700px;"></iframe>_x000D_
</div>_x000D_
<div>_x000D_
<!-- I agree button -->_x000D_
</div>
_x000D_
If you are using Sql Management Studio, just start it as Administrator.
Right click->Run as Administrator
Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:
-e
-z
for testing empty variable (string)test
s and &&
them: [ ... ] && [ ... ]
-a
operator in a single test
: [ ... -a ... ]
Here is a working command (searching through all txt files in a directory, and dumping those that grep
finds contain both of two words):
find /usr/share/doc -name '*.txt' | while read file; do \
a1=$(grep -H "description" $file); \
a2=$(grep -H "changes" $file); \
[ ! -z "$a1" -a ! -z "$a2" ] && echo -e "$a1 \n $a2" ; \
done
Edit 12 Aug 2013: related problem note:
Note that when checking string equality with classic test
(single square bracket [
), you MUST have a space between the "is equal" operator, which in this case is a single "equals" =
sign (although two equals' signs ==
seem to be accepted as equality operator too). Thus, this fails (silently):
$ if [ "1"=="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi
A
... but add the space - and all looks good:
$ if [ "1" = "" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi
B
I beat my head against the wall on this one. This started happening when I installed the latest version of HTC sync (3.0.5579). For some reason adb.exe was showing up multiple times in the task manager and I was getting the adb server is out of date killing errors multiple times. I found the adb.exe version in the HTC sync directory and the Android SDK platform-tools directory. I had the path setup correctly pointing at the android SDK directory and didn't see the HTC Sync path (maybe I was missing something, but I don't think so). Anyway, to fix the issue, I simply renamed the adb.exe file in the HTC Sync directory and everything worked again. This may not be the right way to go about this fix, but it worked for me.
IntelliJ IDEA 14.0.3 Ultimate:
Press Ctrl+Alt+S, then choose Editor\General
choose Show quick domentation on mouse move
Tips: Look at the top right conner (gear icon) at JavaDoc pop-up window, You can choose:
- Show Toolbar
- Pinded Mode
- Docked Mode
- Floatting Mode
- Split Mode
self and $self aren't the same. The former is the object pointed to by "this" and the latter a jQuery object whose "scope" is the object pointed to by "this". Similarly, $body isn't the body DOM element but the jQuery object whose scope is the body element.
By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.
You need to qualify the a
part of the selector too:
.button input, .button a {
//css stuff here
}
Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.
Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".
new StringBuilder().append(str.charAt(0))
.append(str.charAt(10))
.append(str.charAt(20))
.append(str.charAt(30))
.toString();
This way you can get the new string with whatever characters you want.
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Sometimes we have more than one net interface.
A simple method to find out the mac address of a specific interface, is:
def getmac(interface):
try:
mac = open('/sys/class/net/'+interface+'/address').readline()
except:
mac = "00:00:00:00:00:00"
return mac[0:17]
to call the method is simple
myMAC = getmac("wlan0")
If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.
There are only five:
" "
' '
< <
> >
& &
Escaping characters depends on where the special character is used.
The examples can be validated at the W3C Markup Validation Service.
The safe way is to escape all five characters in text. However, the three characters "
, '
and >
needn't be escaped in text:
<?xml version="1.0"?>
<valid>"'></valid>
The safe way is to escape all five characters in attributes. However, the >
character needn't be escaped in attributes:
<?xml version="1.0"?>
<valid attribute=">"/>
The '
character needn't be escaped in attributes if the quotes are "
:
<?xml version="1.0"?>
<valid attribute="'"/>
Likewise, the "
needn't be escaped in attributes if the quotes are '
:
<?xml version="1.0"?>
<valid attribute='"'/>
All five special characters must not be escaped in comments:
<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
All five special characters must not be escaped in CDATA sections:
<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
All five special characters must not be escaped in XML processing instructions:
<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
HTML has its own set of escape codes which cover a lot more characters.
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
A better alternative is to use weakref.finalize. See the examples at Finalizer Objects and Comparing finalizers with __del__() methods.
You can use the wmic command:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
I know this is an old post, but another solution would be to use cURL, for example:
redirect.php:
<?php
if (isset($_GET['url'])) {
$url = $_GET['url'];
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
}
then in your iframe tag, something like:
<iframe src="/redirect.php?url=http://www.example.com/"></iframe>
This is just a MINIMAL example to illustrate the idea -- it doesn't sanitize the URL, nor would it prevent someone else using the redirect.php for their own purposes. Consider these things in the context of your own site.
The upside, though, is it's more flexible. For example, you could add some validation of the curl'd $data to make sure it's really what you want before displaying it -- for example, test to make sure it's not a 404, and have alternate content of your own ready if it is.
Plus -- I'm a little weary of relying on Javascript redirects for anything important.
Cheers!
as the official site says: "jQuery: The Write Less, Do More, JavaScript Library"
try to translate the following jQuery code without any library
$("p.neat").addClass("ohmy").show("slow");
Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.
Applying
<item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
in Theme.AppCompat.Light.DarkActionBar
didn't worked for me. What did the trick is , giving colorPrimaryDark
as usual along with android:colorPrimary
in styles.xml
<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>
and in setting
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
Window window = this.Window;
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
}
didn't had to set statusbar color in code .
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
First I find out the number of commits between my feature branch and current master branch by
git checkout master
git rev-list master.. --count
Then, I create another branch based out my-feature branch, keep my-feature
branch untouched.
Lastly, I run
git checkout my-feature
git checkout -b my-rebased-feature
git checkout master
git checkout my-rebased-feature
git rebase master
git rebase head^x -i
// fixup/pick/rewrite
git push origin my-rebased-feature -f // force, if my-rebased-feature was ever pushed, otherwise no need for -f flag
// make a PR with clean history, delete both my-feature and my-rebased-feature after merge
Hope it helps, thanks.
My simple fix it turned out to be calling the form's Activate()
method, so there's no need to use TopMost
(which is what I was aiming at).
you cannot see the groupBy data directly by print statement but you can see by iterating over the group using for loop try this code to see the group by data
group = df.groupby('A') #group variable contains groupby data
for A,A_df in group: # A is your column and A_df is group of one kind at a time
print(A)
print(A_df)
you will get an output after trying this as a groupby result
I hope it helps
The constraint could be removed with syntax:
As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name:
ALTER TABLE tbl_name DROP CONSTRAINT symbol;
Example:
CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));
-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';
-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;
An OutputStream
is one where you write data to. If some module exposes an OutputStream
, the expectation is that there is something reading at the other end.
Something that exposes an InputStream
, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.
So it is possible to connect an InputStream
to an OutputStream
InputStream----read---> intermediateBytes[n] ----write----> OutputStream
As someone metioned, this is what the copy()
method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense
UPDATE:
Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped
input/ouput streams, but there is another possibility.
If the output stream that is exposed is a ByteArrayOutputStream
, then you can always get the full contents by calling the toByteArray()
method. Then you can create an input stream wrapper by using the ByteArrayInputStream
sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...
You can use this to replace the function if it doesn't exist:
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
</script>
I had the same issue and stumbled on this library.
Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
With bootstrap
<div class="table-responsive">
<table class="table">
...
</table>
</div>
INSERT INTO viewname (Column name) values (value);
If you are using Homebrew to install [email protected], the location is
/usr/local/Homebrew/var/mysql
I don't know if the location is the same for other versions.
You may also want to check to see whether you're linking against the dynamic or static C runtime library. If your DLL files are linking against the static C runtime library, then the DLL files have separate heaps.
Hence, if you were to create an object in one DLL and try to free it in another DLL, you would get the same message you're seeing above. This problem is referenced in another Stack Overflow question, Freeing memory allocated in a different DLL.
svn help unlock
And find locker after all - lock isn't needed in most cases
FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).
FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.
Try hasattr()
:
if hasattr(a, 'property'):
a.property
EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr
. If the property is likely to not be there most of the time, or you're not sure, using hasattr
will probably be faster than repeatedly falling into an exception block.
A Python script like this:
import time
cur_time = int(time.time()*1000)
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
As of today, the UI of developer tools in Google chrome has changed where we select the log level of log statements being shown in the console. There is a logging level drop down beside "Filter" text box. Supported values are Verbose
, Info
, Warnings
and Errors
with Info
being the default selection.
Any log whose severity is equal or higher will get shown in the "Console" tab e.g. if selected log level is Info
then all the logs having level Info
, Warning
and Error
will get displayed in console.
When I changed it to Verbose
then my console.debug
and console.log
statements started showing up in the console. Till the time Info
level was selected they were not getting shown.
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158
Another reason to go with the short one is that it matches other instances where you might specify a character set in markup. For example:
<script type="javascript" charset="UTF-8" src="/script.js"></script>
<p><a charset="UTF-8" href="http://example.com/">Example Site</a></p>
Consistency helps to reduce errors and make code more readable.
Note that the charset attribute is case-insensitive. You can use UTF-8 or utf-8, however UTF-8 is clearer, more readable, more accurate.
Also, there is absolutely no reason at all to use any value other than UTF-8 in the meta charset attribute or page header. UTF-8 is the default encoding for Web documents since HTML4 in 1999 and the only practical way to make modern Web pages.
Also you should not use HTML entities in UTF-8. Characters like the copyright symbol should be typed directly. The only entities you should use are for the 5 reserved markup characters: less than, greater than, ampersand, prime, double prime. Entities need an HTML parser, which you may not always want to use going forward, they introduce errors, make your code less readable, increase your file sizes, and sometimes decode incorrectly in various browsers depending on which entities you used. Learn how to type/insert copyright, trademark, open quote, close quote, apostrophe, em dash, en dash, bullet, Euro, and any other characters you encounter in your content, and use those actual characters in your code. The Mac has a Character Viewer that you can turn on in the Keyboard System Preference, and you can find and then drag and drop the characters you need, or use the matching Keyboard Viewer to see which keys to type. For example, trademark is Option+2. UTF-8 contains all of the characters and symbols from every written human language. So there is no excuse for using -- instead of an em dash. It is not a bad idea to learn the rules of punctuation and typography also ... for example, knowing that a period goes inside a close quote, not outside.
Using a tag for something like content-type and encoding is highly ironic, since without knowing those things, you couldn't parse the file to get the value of the meta tag.
No, that is not true. The browser starts out parsing the file as the browser's default encoding, either UTF-8 or ISO-8859-1. Since US-ASCII is a subset of both ISO-8859-1 and UTF-8, the browser can read just fine either way ... it is the same. When the browser encounters the meta charset tag, if the encoding is different than what the browser is already using, the browser reloads the page in the specified encoding. That is why we put the meta charset tag at the top, right after the head tag, before anything else, even the title. That way you can use UTF-8 characters in your title.
You must save your file(s) in UTF-8 encoding without BOM
That is not strictly true. If you only have US-ASCII characters in your document, you can Save it as US-ASCII and serve it as UTF-8, because it is a subset. But if there are Unicode characters, you are correct, you must Save as UTF-8 without BOM.
If you want a good text editor that will save your files in UTF-8, I recommend Notepad++.
On the Mac, use Bare Bones TextWrangler (free) from Mac App Store, or Bare Bones BBEdit which is at Mac App Store for $39.99 ... very cheap for such a great tool. In either app, there is a menu at the bottom of the document window where you specify the document encoding and you can easily choose "UTF-8 no BOM". And of course you can set that as the default for new documents in Preferences.
But if your Webserver serves the encoding in the HTTP header, which is recommended, both [meta tags] are needless.
That is incorrect. You should of course set the encoding in the HTTP header, but you should also set it in the meta charset attribute so that the page can be Saved by the user, out of the browser onto local storage and then Opened again later, in which case the only indication of the encoding that will be present is the meta charset attribute. You should also set a base tag for the same reason ... on the server, the base tag is unnecessary, but when opened from local storage, the base tag enables the page to work as if it is on the server, with all the assets in place and so on, no broken links.
AddDefaultCharset UTF-8
Or you can just change the encoding of particular file types like so:
AddType text/html;charset=utf-8 html
A tip for serving both UTF-8 and Latin-1 (ISO-8859-1) files is to give the UTF-8 files a "text" extension and Latin-1 files "txt."
AddType text/plain;charset=iso-8859-1 txt
AddType text/plain;charset=utf-8 text
Finally, consider Saving your documents with Unix line endings, not legacy DOS or (classic) Mac line endings, which don't help and may hurt, especially down the line as we get further and further from those legacy systems. An HTML document with valid HTML5, UTF-8 encoding, and Unix line endings is a job well done. You can share and edit and store and read and recover and rely on that document in many contexts. It's lingua franca. It's digital paper.
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
Here is how to create the desired outcome:
library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() +
geom_tile(aes(X1, X2, fill = value)) +
scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom",
legend.spacing.x = unit(0, 'cm'))+
guides(fill = guide_legend(label.position = "bottom"))
Created on 2019-12-07 by the reprex package (v0.3.0)
Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.
Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).
library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom", legend.direction="vertical")
p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")
Created on 2019-02-28 by the reprex package (v0.2.1)
In order to remove a row from a JTable, you need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:
((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);
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>
If you have FTP access to your account:
First, login to your wp-admin and go to Settings > Permalinks
You should see something at the bottom that says:
"If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all."
If this is true do the following:
Go into preferences for your FTP client and make sure hidden files are displayed (varies depending on your FTP client) - If you don't do this you won't be able to find your htaccess file
Go to the folder that your wp-admin, wp-content, wp-includes directories are located. Check for .htaccess file. If it exists skip to step 4
If it does not exist, create a new blank file in your FTP program called .htaccess
Change the CHMOD for your .htaccess file to 666 (your preference on how you want to do this)
Go back to your Permalinks page and edit the link structure you want. Problem should be solved!
Make sure to change the chmod of the htaccess file back to 644 after you are done.
Just had the same problem and it seemed to fix it instantly! Good luck!
As said before, Control
/Command
+ Shift
+ A
gives you basic support for tag matching. Press it again to extend the match to the parent element. Press arrow left/right to jump to the start/end tag.
Anyway, there is no built-in highlighting of matching tags. Emmet is a popular plugin but it's overkill for this purpose and can get in the way if you don't want Emmet-like editing. Bracket Highlighter seems to be a better choice for this use case.
I ran this bad boy:
launchctl setenv STUDIO_JDK /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/
Apps targeting Android Q - API 29 by default are given a filtered view into external storage. A quick fix for that is to add this code in the AndroidManifest.xml:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Read more about it here: https://developer.android.com/training/data-storage/compatibility
Change Minute to be 0
. That's it :)
Note: you can check your "crons" in http://cronchecker.net/
The files are using some sort of template engine in which curly braces indicate variables being generated by that templating engine, the files creating such variables must be present elsewhere with the more or less same name as the tpl file name. Here are some of templates engine mostly used.
Smarty
Savant
Tinybutstrong
etc
With smarty being widely used.
I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.
The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.
Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”
Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!
Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.
??
test -z
returns true if the parameter is empty (see man sh
or man test
).
Try
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
The z
represents an integer of length same as size_t
, and the PRIu32
macro, defined in the C99 header inttypes.h
, represents an unsigned 32-bit integer.
Using newInstance()
directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...)
with the corresponding exceptions.
Here's a very simple use case and has nothing to do with thread safety.
To share an object between lambda invocations, the AtomicReference
is an option:
public void doSomethingUsingLambdas() {
AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();
soSomethingThatTakesALambda(() -> {
yourObjectRef.set(youObject);
});
soSomethingElseThatTakesALambda(() -> {
YourObject yourObject = yourObjectRef.get();
});
}
I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference
is an option.
In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;
You want a check constraint.
CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.
You want something like:
ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.
Try this:
if (Arrays.asList(item1, item2, item3).stream().anyMatch(string::contains))
I often have this problem with date fields (where comparison operators are very common).
To elaborate further on Mihai's answer, which I believe is a solid approach.
To the models you can add scopes like this:
scope :updated_at_less_than, -> (date_param) {
where(arel_table[:updated_at].lt(date_param)) }
... and then in your controller, or wherever you are using your model:
result = MyModel.updated_at_less_than('01/01/2017')
... a more complex example with joins looks like this:
result = MyParentModel.joins(:my_model).
merge(MyModel.updated_at_less_than('01/01/2017'))
A huge advantage of this approach is (a) it lets you compose your queries from different scopes and (b) avoids alias collisions when you join to the same table twice since arel_table will handle that part of the query generation.
In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
If you only made changes and deleted a file, but not commit it, and now you broke up with your changes
git checkout -- .
but your deleted files did not return, you simply do the following command:
git checkout <file_path>
And presto, your file is back.
If you are using the Prototype Framework, you can use the intersect method of an array to find out of they are the same (regardless of the order):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
just use stoi/stol/stoll for example:
std::cout << std::stol("fffefffe", nullptr, 16) << std::endl;
output: 4294901758
$("#myDiv").hide();
will set the css display to none. if you need to set visibility to hidden as well, could do this via
$("#myDiv").css("visibility", "hidden");
or combine both in a chain
$("#myDiv").hide().css("visibility", "hidden");
or write everything with one css() function
$("#myDiv").css({
display: "none",
visibility: "hidden"
});
If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.
[For a bonus point...]
Using the JOIN syntax allows you to more easily comment out the join as its all included on one line. This can be useful if you are debugging a complex query
As everyone else says, they are functionally the same, however the JOIN is more clear of a statement of intent. It therefore may help the query optimiser either in current oracle versions in certain cases (I have no idea if it does), it may help the query optimiser in future versions of Oracle (no-one has any idea), or it may help if you change database supplier.
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).
Improved with input from @a_horse_with_no_name in the comments below.
You could even use an empty SELECT
list:
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
Since the SELECT
list is not relevant to the outcome of EXISTS
. Only the existence of at least one qualifying row matters.
1. Generalized Substring
To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:
${string: -7:4}
Where 4 is the length of course (7-3).
2. Alternative using cut
In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:
echo $string | cut -c $((${#string}-2))-
Here, ${#string}
is the length of the string, and the "-" means cut to the end.
3. Alternative using awk
This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length)
going to the end if the length is omitted. length($string)-2)
thus picks up the last three characters.
echo $string | awk '{print substr($1,length($1)-2) }'
When using java -cp
you are required to provide fully qualified main class name, e.g.
java -cp com.mycompany.MyMain
When using java -jar myjar.jar
your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF
:
Main-Class: com.mycompany.MyMain
Here is a good choice for gradients for both platforms iOS and Android:
https://github.com/react-native-community/react-native-linear-gradient
There are others approaches like expo, however react-native-linear-gradient have worked better for me.
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
<Text style={styles.buttonText}>
Sign in with Facebook
</Text>
</LinearGradient>
// Later on in your styles..
var styles = StyleSheet.create({
linearGradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
borderRadius: 5
},
buttonText: {
fontSize: 18,
fontFamily: 'Gill Sans',
textAlign: 'center',
margin: 10,
color: '#ffffff',
backgroundColor: 'transparent',
},
});
If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.
If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.
If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important
keyword.
An example:
.override {
border: 1px solid #000 !important;
}
.a_class {
border: 2px solid red;
}
And the HTML:
<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>
Try to use !important
only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.
This works in both SQL 2005 and 2008:
declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select cast('' as xml).value('xs:hexBinary(sql:variable("@source"))', 'varchar(max)');
I do it like this:
static String formatDate(long dateInMillis) {
Date date = new Date(dateInMillis);
return DateFormat.getDateInstance().format(date);
}
You can also use getDateInstance(int style)
with following parameters:
DateFormat.SHORT
DateFormat.MEDIUM
DateFormat.LONG
DateFormat.FULL
DateFormat.DEFAULT
Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.
The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.
Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.
I found out that the URL of the application conflicted with a module in the Sun GlassFish.
So, in the file sun-web.xml
I renamed the <context-root>/servlets-samples</context-root>.
It is now working.
Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)
<input @change="foo" v-model... >
If you wanna detect single character changes (during user typing) use
<input @keydown="foo" v-model... >
You can also use @keyup
and @input
events. If you wanna to pass additional parameters use in template e.g. @keyDown="foo($event, param1, param2)"
. Comparision below (editable version here)
new Vue({_x000D_
el: "#app",_x000D_
data: { _x000D_
keyDown: { key:null, val: null, model: null, modelCopy: null },_x000D_
keyUp: { key:null, val: null, model: null, modelCopy: null },_x000D_
change: { val: null, model: null, modelCopy: null },_x000D_
input: { val: null, model: null, modelCopy: null },_x000D_
_x000D_
_x000D_
},_x000D_
methods: {_x000D_
_x000D_
keyDownFun: function(event){ // type of event: KeyboardEvent _x000D_
console.log(event); _x000D_
this.keyDown.key = event.key; // or event.keyCode_x000D_
this.keyDown.val = event.target.value; // html current input value_x000D_
this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
keyUpFun: function(event){ // type of event: KeyboardEvent_x000D_
console.log(event); _x000D_
this.keyUp.key = event.key; // or event.keyCode_x000D_
this.keyUp.val = event.target.value; // html current input value_x000D_
this.keyUp.modelCopy = this.keyUp.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
changeFun: function(event) { // type of event: Event_x000D_
console.log(event);_x000D_
this.change.val = event.target.value; // html current input value_x000D_
this.change.modelCopy = this.change.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
inputFun: function(event) { // type of event: Event_x000D_
console.log(event);_x000D_
this.input.val = event.target.value; // html current input value_x000D_
this.input.modelCopy = this.input.model; // copy of model value at the moment on event handling_x000D_
}_x000D_
}_x000D_
})
_x000D_
div {_x000D_
margin-top: 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
Type in fields below (to see events details open browser console)_x000D_
_x000D_
<div id="app">_x000D_
<div><input type="text" @keyDown="keyDownFun" v-model="keyDown.model"><br> @keyDown (note: model is different than value and modelCopy)<br> key:{{keyDown.key}}<br> value: {{ keyDown.val }}<br> modelCopy: {{keyDown.modelCopy}}<br> model: {{keyDown.model}}</div>_x000D_
_x000D_
<div><input type="text" @keyUp="keyUpFun" v-model="keyUp.model"><br> @keyUp (note: model change value before event occure) <br> key:{{keyUp.key}}<br> value: {{ keyUp.val }}<br> modelCopy: {{keyUp.modelCopy}}<br> model: {{keyUp.model}}</div>_x000D_
_x000D_
<div><input type="text" @change="changeFun" v-model="change.model"><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: {{ change.val }}<br> modelCopy: {{change.modelCopy}}<br> model: {{change.model}}</div>_x000D_
_x000D_
<div><input type="text" @input="inputFun" v-model="input.model"><br> @input<br> value: {{ input.val }}<br> modelCopy: {{input.modelCopy}}<br> model: {{input.model}}</div>_x000D_
_x000D_
</div>
_x000D_
You can use the -B
and -A
to print lines before and after the match.
grep -i -B 10 'error' data
Will print the 10 lines before the match, including the matching line itself.
To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:
Array.prototype.get = function(name) {
for (var i=0, len=this.length; i<len; i++) {
if (typeof this[i] != "object") continue;
if (this[i].name === name) return this[i].value;
}
};
this will add the get() method to all arrays and let you do what you want, i.e:
arr.get('k1'); //= abc
What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.
Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.
From Ubuntu 18.4 (Bionic Beaver) it is advisable to use apt instead of apt-get since it has much better structural form.
sudo apt install libxml2-dev libxslt1-dev python-dev
If you're happy with a possibly older version of lxml
altogether though, you could try
sudo apt install python-lxml
The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.
The servlet-api jar is best left up to the server to manage see here for detail
With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency>
So becareful to check how your container has provided the servlet implementation.
This will require Node.js 7 or later with a support for Promises and Async/Await.
Create a wrapper function that leverage promises to control the behavior of the child_process.exec
command.
Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await
keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec
done.
const childProcess = require("child_process");
/**
* @param {string} command A shell command to execute
* @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
* @example const output = await execute("ls -alh");
*/
function execute(command) {
/**
* @param {Function} resolve A function that resolves the promise
* @param {Function} reject A function that fails the promise
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
*/
return new Promise(function(resolve, reject) {
/**
* @param {Error} error An error triggered during the execution of the childProcess.exec command
* @param {string|Buffer} standardOutput The result of the shell command execution
* @param {string|Buffer} standardError The error resulting of the shell command execution
* @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
*/
childProcess.exec(command, function(error, standardOutput, standardError) {
if (error) {
reject();
return;
}
if (standardError) {
reject(standardError);
return;
}
resolve(standardOutput);
});
});
}
async function main() {
try {
const passwdContent = await execute("cat /etc/passwd");
console.log(passwdContent);
} catch (error) {
console.error(error.toString());
}
try {
const shadowContent = await execute("cat /etc/shadow");
console.log(shadowContent);
} catch (error) {
console.error(error.toString());
}
}
main();
root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]
Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied
I would recommend to add the -sha256 parameter, to use the SHA-2 hash algorithm, because major browsers are considering to show "SHA-1 certificates" as not secure.
The same command line from the accepted answer - @diegows with added -sha256
openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX
More information in Google Security blog.
Update May 2018. As many noted in the comments that using SHA-2 does not add any security to a self-signed certificate. But I still recommend using it as a good habit of not using outdated / insecure cryptographic hash functions. Full explanation is available in Why is it fine for certificates above the end-entity certificate to be SHA-1 based?.
It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged()
you have full control of the Views generation and rendering.
Take a look at these tutorials
If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
}
Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.
You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.
Another might be using CDATA
tags.
Example using CDATA
:
<xml>
<title>Your HTML title</title>
<htmlData><![CDATA[<html>
<head>
<script/>
</head>
<body>
Your HTML's body
</body>
</html>
]]>
</htmlData>
</xml>
Please note:
CDATA's opening character sequence: <![CDATA[
CDATA's closing character sequence: ]]>
Adding processData: false
to the $.ajax
options will fix this issue.
Given that you're only converting to int
s to then perform a comparison, I'd just switch the table definition around to using varchar
also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERT
s from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name
set scrolling="no"
attribute in your iframe.
private void UpdateFont()
{
//Change cell font
foreach(DataGridViewColumn c in dgAssets.Columns)
{
c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
}
}
I like to set the 'line-height' in the css for the divs to get them to line up properly. Here is an example of how I do it using asp and css:
ASP:
<div id="profileRow1">
<div id="profileRow1Col1" class="righty">
<asp:Label ID="lblCreatedDateLabel" runat="server" Text="Date Created:"></asp:Label><br />
<asp:Label ID="lblLastLoginDateLabel" runat="server" Text="Last Login Date:"></asp:Label><br />
<asp:Label ID="lblUserIdLabel" runat="server" Text="User ID:"></asp:Label><br />
<asp:Label ID="lblUserNameLabel" runat="server" Text="Username:"></asp:Label><br />
<asp:Label ID="lblFirstNameLabel" runat="server" Text="First Name:"></asp:Label><br />
<asp:Label ID="lblLastNameLabel" runat="server" Text="Last Name:"></asp:Label><br />
</div>
<div id="profileRow1Col2">
<asp:Label ID="lblCreatedDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
<asp:Label ID="lblLastLoginDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
<asp:Label ID="lblUserId" runat="server" Text="UserId"></asp:Label><br />
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
</div>
</div>
And here is the code in the CSS file to make all of the above fields look nice and neat:
#profileRow1{width:100%;line-height:40px;}
#profileRow1Col1{float:left; width:25%; margin-right:20px;}
#profileRow1Col2{float:left; width:25%;}
.righty{text-align:right;}
you can basically pull everything but the DIV tags and replace with your own content.
Trust me when I say it looks aligned the way the image in the original post does!
I would post a screenshot but Stack wont let me: Oops! Your edit couldn't be submitted because: We're sorry, but as a spam prevention mechanism, new users aren't allowed to post images. Earn more than 10 reputation to post images.
:)
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
You could do something like this:
//outside of main
namespace A
{
enum A
{
a = 0,
b = 69,
c = 666
};
};
//in main:
A::A a = A::c;
std::cout << a << std::endl;
Found the chrome Options class in the Selenium source code.
Usage to create a Chrome driver instance:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)
It is best practice to always supply the permission when registering the receiver, otherwise you will receive for any application that sends a matching intent. This can allow malicious apps to broadcast to your receiver.
Use django-phonenumber-field: https://github.com/stefanfoulis/django-phonenumber-field
pip install django-phonenumber-field
Use a varchar
field with a length restriction.
Had similar problem and in the end I had to set both
obj.attr('data-myvar','myval')
and
obj.data('myvar','myval')
And after this
obj.data('myvar') == obj.attr('data-myvar')
Hope this helps.
public Map<String, String> parseJSON(JSONObject json, Map<String, String> dataFields) throws JSONException {
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = json.getJSONObject(key);
parseJSON(value, dataFields);
} catch (Exception e) {
if (json.isNull(key)) {
val = "";
} else {
try {
val = json.getString(key);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
if (val != null) {
dataFields.put(key, val);
}
}
return dataFields;
}
Here's the default template for ListViewItem from Blend:
Default ListViewItem Template:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}}"/>
</MultiTrigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
Just remove the IsSelected Trigger and IsSelected/IsSelectionActive MultiTrigger, by adding the below code to your Style to replace the default template, and there will be no visual change when selected.
Solution to turn off the IsSelected property's visual changes:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
These days listen for oninput
. It feels like onchange
without the need to lose focus on the element. It is HTML5.
It’s supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange
. I use it like this:
const source = document.getElementById('source');_x000D_
const result = document.getElementById('result');_x000D_
_x000D_
const inputHandler = function(e) {_x000D_
result.innerHTML = e.target.value;_x000D_
}_x000D_
_x000D_
source.addEventListener('input', inputHandler);_x000D_
source.addEventListener('propertychange', inputHandler); // for IE8_x000D_
// Firefox/Edge18-/IE9+ don’t fire on <select><option>_x000D_
// source.addEventListener('change', inputHandler);
_x000D_
<input id="source">_x000D_
<div id="result"></div>
_x000D_
PostGIS_Lib_Version();
- returns the version number of the PostGIS library.
http://postgis.refractions.net/docs/PostGIS_Lib_Version.html
Put this line into your vimrc
:
set nobk nowb noswf noudf
"
nobackup
nowritebackup
noswapfile
noundofile
In windows that would be the:
C:\Program Files (x86)\vim\_vimrc
file for system-wide vim configuration for all users.
Setting the last one noundofile
is important in Windows to prevent the creation of *~
tilda files after editing.
I wish Vim had that line included by default. Nobody likes ugly directories.
Let the user choose if and how she wants to enable advanced backup/undo file features first.
This is the most annoying part of Vim.
The next step might be setting up:
set noeb vb t_vb=
"
errorbells
visualbell
to disable beeping in vim as well :-)
You can use it which is most helpful.
df = pd.read_csv(('data.txt'), sep="\t", skiprows=[0,1], names=['FromNode','ToNode'])
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:
SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS SUBQUERY
follow he steps. in pgadmin
host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.
note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
It happens due to a missing plugin configuration (as per vaadin's demo pom.xml comment):
This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e ettings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>com.vaadin</groupId>
<artifactId>
vaadin-maven-plugin
</artifactId>
<versionRange>
[7.1.5,)
</versionRange>
<goals>
<goal>resources</goal>
<goal>update-widgetset</goal>
<goal>compile</goal>
<goal>update-theme</goal>
<goal>compile-theme</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
Update 18-11-23: From Go 1.11 mod is official experiment. Please see @krish answer.
Update 19-01-01: From Go 1.12 mod is still official experiment.
Starting in Go 1.13, module mode will be the default for all development.
Update 19-10-17: From Go 1.13 mod is official package manager.
https://blog.golang.org/using-go-modules
Old answer:
You can set version by offical dep
dep ensure --add github.com/gorilla/[email protected]
You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:
This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.
A simple example in Groovy for your reference:
def outer() {
def x = 1
return { -> println(x)} // inner
}
def innerObj = outer()
innerObj() // prints 1
Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.
android:layout_height="wrap_content"
Use the -k
option (or --key=POS1[,POS2]
). It can appear multiple times and each key can have global options (such as n
for numeric sort)
Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf
returns a view of the string as a List
.
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.
Example:
angular.module("app", []).component("component", {_x000D_
controller: ["$window", function($window) {_x000D_
var self = this;_x000D_
_x000D_
self.logg = function() {_x000D_
console.log("logging!");_x000D_
};_x000D_
_x000D_
$window.angularControllerLogg = self.logg;_x000D_
}_x000D_
});_x000D_
_x000D_
window.angularControllerLogg();
_x000D_
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Microsoft has their own Command Line Standard specification:
This document is focused at developers of command line utilities. Collectively, our goal is to present a consistent, composable command line user experience. Achieving that allows a user to learn a core set of concepts (syntax, naming, behaviors, etc) and then be able to translate that knowledge into working with a large set of commands. Those commands should be able to output standardized streams of data in a standardized format to allow easy composition without the burden of parsing streams of output text. This document is written to be independent of any specific implementation of a shell, set of utilities or command creation technologies; however, Appendix J - Using Windows Powershell to implement the Microsoft Command Line Standard shows how using Windows PowerShell will provide implementation of many of these guidelines for free.
// An Answer w/o using Hashset or map or Arraylist
public class Count {
static String names[] = {"name1","name1","name2","name2", "name2"};
public static void main(String args[]) {
printCount(names);
}
public static void printCount(String[] names){
java.util.Arrays.sort(names);
int n = names.length, c;
for(int i=0;i<n;i++){
System.out.print(names[i]+" ");
}
System.out.println();
int result[] = new int[n];
for(int i=0;i<n;i++){
result[i] = 0;
}
for(int i =0;i<n;i++){
if (i != n-1){
for(int j=0;j<n;j++){
if(names[i] == names[j] )
result[i]++;
}
}
else if (names[n-2] == names[n-1]){
result[i] = result[i-1];
}
else result[i] = 1;
}
int max = 0,index = 0;
for(int i=0;i<n;i++){
System.out.print(result[i]+" ");
if (result[i] >= max){
max = result[i];
index = i;
}
}
}
}
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
I solved that problem by using a special setting for JsonSerializerSettings which is called TypeNameHandling.All
TypeNameHandling setting includes type information when serializing JSON and read type information so that the create types are created when deserializing JSON
Serialization:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
var text = JsonConvert.SerializeObject(configuration, settings);
Deserialization:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
var configuration = JsonConvert.DeserializeObject<YourClass>(json, settings);
The class YourClass might have any kind of base type fields and it will be serialized properly.
In my opinion, the most elegant and idiomatic way of prepending an element or list to another list, in Python, is using the expansion operator * (also called unpacking operator),
# Initial list
l = [4, 5, 6]
# Modification
l = [1, 2, 3, *l]
Where the resulting list after the modification is [1, 2, 3, 4, 5, 6]
I also like simply combining two lists with the operator +, as shown,
# Prepends [1, 2, 3] to l
l = [1, 2, 3] + l
# Prepends element 42 to l
l = [42] + l
I don't like the other common approach, l.insert(0, value)
, as it requires a magic number. Moreover, insert()
only allows prepending a single element, however the approach above has the same syntax for prepending a single element or multiple elements.
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
cout << " " ;
}
cout <<endl;
reverseValues(values) {
let maxLength = values.reduce((acc, val) => Math.max(val.length, acc), 0);
return [...Array(maxLength)].map((val, index) => values.map((v) => v[index]));
}
You can create the ordered dict from old dict in one line:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())
The default sorting key is by dictionary key, so the new ordered_dict
is sorted by old dict's keys.
display
syntax instead, for clarityThe display
CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.
If you use the two-value display
syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:
display: block
is equivalent to display: block flow
display: inline
is equivalent to display: inline flow
display: flex
is equivalent to display: block flex
display: inline-flex
is equivalent to display: inline flex
display: grid
is equivalent to display: block grid
display: inline-grid
is equivalent to display: inline grid
block
or inline
:An element with the outer display type of block
will take up the whole width available to it, like <div>
does. An element with the outer display type of inline
will only take up the width that it needs, with wrapping, like <span>
does.
flow
, flex
or grid
:The inner display type flow
is the default inner display type when flex
or grid
is not specified. It is the way of laying out children elements that we are used to in a <p>
for instance. flex
and grid
are new ways of laying out children that each deserve their own post.
The difference between display: flex
and display: inline-flex
is the outer display type, the first's outer display type is block
, and the second's outer display type is inline
. Both of them have the inner display type of flex
.
Based on Ramon's answer I run into an error. The problem where spaces in the JSON I tried to write I got it fixed by changing the task in the playbook to look like:
- copy:
content: "{{ your_json_feed }}"
dest: "/path/to/destination/file"
As of now I am not sure why this was needed. My best guess is that it had something to do with how variables are replaced in Ansible and the resulting file is parsed.
CTRL+N-- to open a new document.
Right Edge find "MORE SHAPES" then "SOFTWARES AND DATABASES" and finaly "SOFTWARES". All UML DIAGRAMS are available here.
You have to explicitly list the fields in the order you want them to be returned instead of using * for the 'default' order.
original query:
select * from foobar
returns
foo bar
--- ---
1 2
now write
select bar, foo from foobar
bar foo
--- ---
2 1
This worked for me..
select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view
As @Ming mentioned:
pip install -r file.txt
Here's a simple line to force update all dependencies:
while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt
Regarding some points mentioned in previous answers, and to improve readability:
No need for data.loc or query, but I do think it is a bit long.
The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.
I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.
q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time
df.loc[q_product & q_start & q_end, c('Time,Product')]
# c is just a convenience
c = lambda v: v.split(',')
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");
For Bootstrap 3, you would need to use a custom wrapper and set its width to 100%.
.container-full {
margin: 0 auto;
width: 100%;
}
Here is a working example on Bootply
If you prefer not to add a custom class, you can acheive a very wide layout (not 100%) by wrapping everything inside a col-lg-12
(wide layout demo)
Update for Bootstrap 3.1
The container-fluid
class has returned in Bootstrap 3.1, so this can be used to create a full width layout (no additional CSS required)..