Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
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.
The solution from @ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:
"dependencies":
{
"react": "17.0.1",
}
"devDependencies": {
"typescript": "4.1.5",
}
export const SubscriptionsView: React.FC = () => {
const [data, setData] = useState<Subscription[]>();
const isMounted = React.useRef(true);
React.useEffect(() => {
if (isMounted.current) {
// fetch data
// setData (fetch result)
return () => {
isMounted.current = false;
};
}
}
});
In My case, I had a added async at app.js like shown below.
const App = async() => {
return(
<Text>Hello world</Text>
)
}
But it was not necessary, when testing something I had added it and it was no longer required. After removing it, as shown below, things started working.
const App =() => {
return(
<Text>Hello world</Text>
)
}
Mine was a name spacing issue. I had two files with the same name. Just renamed them and it resolved.
Always gotta check the 'stupid me' box first before looking elsewhere. : )
You should declare your method first in void initState()
, so when the first time pages has been loaded, it will init your method first, hope it can help
This can also be an issue with hyper-v settings on Windows 10 pro. Because with this error I was facing BSOD - https://www.techclassy.com/fix-hypervisor-error-bsod/
Place your RaisedButton(...)
in a SizedBox
SizedBox(
width: double.infinity,
child: RaisedButton(...),
)
I've done exactly this on Windows. I have a local .html page that I use as a "dashboard" for all my current work. In addition to the usual links, I've been able to add clickable links that open MS-Word documents, Excel spreadsheets, open my IDE, ssh to servers, etc. It is a little involved but here's how I did it ...
First, update the Windows registry. Your browser handles usual protocols like http, https, ftp. You can define your own protocol and a handler to be invoked when a link of that protocol-type is clicked. Here's the config (run with regedit
)
[HKEY_CLASSES_ROOT\mydb]
@="URL:MyDB Document"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\mydb\shell]
@="open"
[HKEY_CLASSES_ROOT\mydb\shell\open]
[HKEY_CLASSES_ROOT\mydb\shell\open\command]
@="wscript C:\_opt\Dashboard\Dashboard.vbs \"%1\""
With this, when I have a link like <a href="mydb:open:ProjectX.docx">ProjectX</a>
, clicking it will invoke C:\_opt\Dashboard\Dashboard.vbs
passing it the command line parameter open:ProjectX.docx
. My VBS code looks at this parameter and does the necessary thing (in this case, because it ends in .docx, it invokes MS-Word with ProjectX.docx
as the parameter to it.
Now, I've written my handler in VBS only because it is very old code (like 15+ years). I haven't tried it, but you might be able to write a Python handler, Dashboard.py
, instead. I'll leave it up to you to write your own handler. For your scripts, your link could be href="mydb:runpy:whatever.py"
(the runpy:
prefix tells your handle to run with Python).
While it might be possible to use numpy alone to do this, the operation is not built-in. That said, you can use scikit-image
(which is built on numpy) to do this kind of image manipulation.
Scikit-Image rescaling documentation is here.
For example, you could do the following with your image:
from skimage.transform import resize
bottle_resized = resize(bottle, (140, 54))
This will take care of things like interpolation, anti-aliasing, etc. for you.
class Loader extends StatefulWidget {
@override
State createState() => LoaderState();
}
class LoaderState extends State<Loader> with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: 1200), vsync: this);
animation = CurvedAnimation(parent: controller, curve: Curves.elasticOut);
animation.addListener(() {
this.setState(() {});
});
animation.addStatusListener((AnimationStatus status) {});
controller.repeat();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 100.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue[300],
height: 3.0,
width: animation.value * 75.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 50.0,
)
],
);
}
}
Expanded(
child: Padding(
padding:
EdgeInsets.only(left: 20.0, right: 5.0, top:20.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FirstScreen()));
},
child: Container(
alignment: Alignment.center,
height: 45.0,
decoration: BoxDecoration(
color: Color(0xFF1976D2),
borderRadius: BorderRadius.circular(9.0)),
child: Text('Login',
style: TextStyle(
fontSize: 20.0, color: Colors.white))),
),
),
),
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
This is the value that i want to clear and create it in state 1st STEP
state={
TemplateCode:"",
}
craete submitHandler function for Button or what you want 3rd STEP
submitHandler=()=>{
this.clear();//this is function i made
}
This is clear function Final STEP
clear = () =>{
this.setState({
TemplateCode: ""//simply you can clear Templatecode
});
}
when click button Templatecode is clear 2nd STEP
<div class="col-md-12" align="right">
<button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save
</button>
</div>
My solution was to hide the badge, then display it when the user focuses on a form input - thus still adhering to Google's T&Cs.
Note: The reCAPTCHA I was tweaking had been generated by a WordPress plugin, so you may need to wrap the reCAPTCHA with a <div class="inv-recaptcha-holder"> ... </div>
yourself.
CSS
.inv-recaptcha-holder {
visibility: hidden;
opacity: 0;
transition: linear opacity 1s;
}
.inv-recaptcha-holder.show {
visibility: visible;
opacity: 1;
transition: linear opacity 1s;
}
jQuery
$(document).ready(function () {
$('form input, form textarea').on( 'focus', function() {
$('.inv-recaptcha-holder').addClass( 'show' );
});
});
Obviously you can change the jQuery selector to target specific forms if necessary.
Scenario:
Windows 10 with Visual Studio 2017 (FRESH installation).
'C' project (ERROR like -> cannot open source file: 'stdio.h', 'windows.h', etc.).
Resolve:
Run 'Visual Studio Installer'.
Click button 'Modify'.
Select 'Desktop development with C++'.
From "Installation details"(usually on the right-sidebar) select:
4.1. Windows 10 SDK(10.0.17134.0).
Click button 'Modify', to apply changes.
Maybe you installed a pod file and you are still trying to build from the .xcodeproj
file instead of .xcworkspace
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';
The --net=host
option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.
Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.
While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.
For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host
.
Generally speaking, --net=host
is only needed when you are running programs with very specific, unusual network needs.
Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host
then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.
If the other answers aren't working for you, there's also a homepage
field in package.json
. After running npm run build
you should get a message like the following:
The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",
You would just add it as one of the root fields in package.json
, e.g.
{
// ...
"scripts": {
// ...
},
"homepage": "https://example.com"
}
When it's successfully set, either via homepage
or PUBLIC_URL
, you should instead get a message like this:
The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.
In the specific case of react-router
, using context
is a valid case scenario, e.g.
class MyComponent extends React.Component {
props: PropsType;
static contextTypes = {
router: PropTypes.object
};
render () {
this.context.router;
}
}
You can access an instance of the history via the router context, e.g. this.context.router.history
.
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
I also wanted to read the Request.Body without automatically map it to some action parameter model. Tested a lot of different ways before solved this. And I didn´t find any working solution described here. This solution is currently based on the .NET Core 3.0 framework.
reader.readToEnd() seamed like a simple way, even though it compiled, it throwed an runtime exception required me to use async call. So instead I used ReadToEndAsync(), however it worked sometimes, and sometimes not. Giving me errors like, cannot read after stream is closed. The problem is that we cannot guarantee that it will return the result in the same thread (even if we use the await). So we need some kind of callback. This solution worked for me.
[Route("[controller]/[action]")]
public class MyController : ControllerBase
{
// ...
[HttpPost]
public async void TheAction()
{
try
{
HttpContext.Request.EnableBuffering();
Request.Body.Position = 0;
using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
{
var task = stream
.ReadToEndAsync()
.ContinueWith(t => {
var res = t.Result;
// TODO: Handle the post result!
});
// await processing of the result
task.Wait();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to handle post!");
}
}
I encountered a similar issue, but putting it in my page’s module didn’t work.
I had created a component, which needed a pipe. This component was declared and exported in a ComponentsModule file, which holds all of the app’s custom components.
I had to put my PipesModule in my ComponentsModule as an import, in order for these components to use these pipes and not in the page’s module using that component.
Credits: enter link description here Answer by: tumain
On a rather unrelated note: more performance hacks!
When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N
(shown first):
To leap past these 2 elements means to compute (N >> 1) + N + 1
, ((N << 1) + N + 1) >> 1
and N >> 2
, respectively.
Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1
.
Case (1) is obvious. Case (2) implies (N & 1) == 1
, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba
from most- to least-significant, then a = 1
, and the following holds:
(N << 1) + N + 1: (N >> 1) + N + 1:
b10 b1
b1 b
+ 1 + 1
---- ---
bBb0 bBb
where B = !b
. Right-shifting the first result gives us exactly what we want.
Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1
.
As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.
The resulting algorithm looks like this:
uint64_t sequence(uint64_t size, uint64_t *path) {
uint64_t n, i, c, maxi = 0, maxc = 0;
for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
c = 2;
while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
c += 2;
if (n == 2)
c++;
if (c > maxc) {
maxi = i;
maxc = c;
}
}
*path = maxc;
return maxi;
}
int main() {
uint64_t maxi, maxc;
maxi = sequence(1000000, &maxc);
printf("%llu, %llu\n", maxi, maxc);
return 0;
}
Here we compare n > 2
because the process may stop at 2 instead of 1 if the total length of the sequence is odd.
Let`s translate this into assembly!
MOV RCX, 1000000;
DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;
@main:
XOR RSI, RSI;
LEA RDI, [RCX + 1];
@loop:
ADD RSI, 2;
LEA RDX, [RDI + RDI*2 + 2];
SHR RDX, 1;
SHRD RDI, RDI, 2; ror rdi,2 would do the same thing
CMOVL RDI, RDX; Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
CMOVS RDI, RDX;
CMP RDI, 2;
JA @loop;
LEA RDX, [RSI + 1];
CMOVE RSI, RDX;
CMP RAX, RSI;
CMOVB RAX, RSI;
CMOVB RBX, RCX;
SUB RCX, 2;
JA @main;
MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;
@itoa:
XOR RDX, RDX;
DIV RCX;
ADD RDX, '0';
PUSH RDX;
TEST RAX, RAX;
JNE @itoa;
PUSH RCX;
LEA RAX, [RBX + 1];
TEST RBX, RBX;
MOV RBX, RDI;
JNE @itoa;
POP RCX;
INC RDI;
MOV RDX, RDI;
@outp:
MOV RSI, RSP;
MOV RAX, RDI;
SYSCALL;
POP RAX;
TEST RAX, RAX;
JNE @outp;
LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;
Use these commands to compile:
nasm -f elf64 file.asm
ld -o file file.o
See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)
Ok, here is a fetch DELETE
example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
A workaround to achieve the same specially if you want to use checkbox with for loop is to store the state of the checkbox inside an array and change it based on the index of the *ngFor
loop. This way you can change the state of the checkbox in your component.
app.component.html
<div *ngFor="let item of items; index as i">
<input type="checkbox" [checked]="category[i]" (change)="checkChange(i)">
{{item.name}}
</div>
app.component.ts
items = [
{'name':'salad'},
{'name':'juice'},
{'name':'dessert'},
{'name':'combo'}
];
category= []
checkChange(i){
if (this.category[i]){
this.category[i] = !this.category[i];
}
else{
this.category[i] = true;
}
}
Check also that your migrations are working correctly
Python3 manage.py makemigrations
Python3 manage.py migrate
actions.js
const axios = require('axios');
const types = require('./types');
export const actions = {
GET_CONTENT({commit}){
axios.get(`${URL}`)
.then(doc =>{
const content = doc.data;
commit(types.SET_CONTENT , content);
setTimeout(() =>{
commit(types.IS_LOADING , false);
} , 1000);
}).catch(err =>{
console.log(err);
});
},
}
home.vue
<script>
import {value , onCreated} from "vue-function-api";
import {useState, useStore} from "@u3u/vue-hooks";
export default {
name: 'home',
setup(){
const store = useStore();
const state = {
...useState(["content" , "isLoading"])
};
onCreated(() =>{
store.value.dispatch("GET_CONTENT" );
});
return{
...state,
}
}
};
</script>
I'm guessing there are compatibility problems with the version of google-services and firebase versions.
I changed in the Project's build.gradle file, the dependency
classpath 'com.google.gms:google-services:4.1.0' to 4.2.0
and then updated the module's build.gradle dependencies to:
implementation 'com.google.firebase:firebase-database:16.0.6'
implementation 'com.google.firebase:firebase-core:16.0.7'
Everything works like a charm, no need to type FirebaseApp.initializeApp(this);
Similar to the above solutions I used @Input()
in a directive and able to pass multiple arrays of values in the directive.
selector: '[selectorHere]',
@Input() options: any = {};
Input.html
<input selectorHere [options]="selectorArray" />
Array from TS file
selectorArray= {
align: 'left',
prefix: '$',
thousands: ',',
decimal: '.',
precision: 2
};
By default, homebrew gave me OpenSSL version 1.1 and I was looking for version 1.0 instead. This worked for me.
To install version 1.0:
brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Then I tried to symlink my way through it but it gave me the following error:
ln -s /usr/local/Cellar/openssl/1.0.2t/include/openssl /usr/bin/openssl
ln: /usr/bin/openssl: Operation not permitted
Finally linked openssl to point to 1.0 version using brew switch command:
brew switch openssl 1.0.2t
Cleaning /usr/local/Cellar/openssl/1.0.2t
Opt link created for /usr/local/Cellar/openssl/1.0.2t
I had the same question, so I created Git Merger.
hope this helps :)
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
For me, the issue was I had git and my macOS filesystem set to two different case sensitivities. My Mac was formatted APFS/Is Case-Sensitive: NO but I had flipped my git settings at some point trying to get over a weird issue with Xcode image asset naming so git config --global core.ignorecase false. By flipping it back aligned the settings and recreating the branch and pushing got me back on track.
git config --global core.ignorecase true
@Hostlistnening deals basically with the host element say (a button) listening to an action by a user and performing a certain function say alert("Ahoy!") while @Hostbinding is the other way round. Here we listen to the changes that occurred on that button internally (Say when it was clicked what happened to the class) and we use that change to do something else, say emit a particular color.
Think of the scenario that you would like to make a favorite icon on a component, now you know that you would have to know whether the item has been Favorited with its class changed, we need a way to determine this. That is exactly where @Hostbinding comes in.
And where there is the need to know what action actually was performed by the user that is where @Hostlistening comes in
Try this:
1- From Xcode menu open: Product > Scheme > Edit Scheme
2- On your Environment Variables set OS_ACTIVITY_MODE
= disable
COPY . <destination>
Which would be in your case:
COPY . /
The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test
command.
You can use this for some further reading:
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.setColor(getResources().getColor(R.color.colorPrimaryDark))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build());
Using a ternary operator inside the ngStyle
binding will function as an if/else condition.
<div [ngStyle]="{'background-image': 'url(' + value ? image : otherImage + ')'}"></div>
Try parent_window.maxsize(x,x);
to set the maximum size. It shouldn't get larger even if you set the background, etc.
Edit: use parent_window.minsize(x,x)
also to set it to a constant size!
Please don't use any workaround because it will impact build performance.
Webpack File Manager Plugin
Easy to install copy this tag on top of the webpack.config.js
const FileManagerPlugin = require('filemanager-webpack-plugin');
Install
npm install filemanager-webpack-plugin --save-dev
Add the plugin
module.exports = {
plugins: [
new FileManagerPlugin({
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}),
],
};
Screenshot
this worked fine for me:
<div class="card card-body " style="height:80% !important">
forcing our CSS over the bootstraps general CSS.
A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.
Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.
Reference: http://static.springframework.org/sp...ng-interceptor
Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});
The verified solution doesn't work for me, since my notebook is not in my sys.path. This works however;
import os,sys
sys.path.insert(1, os.path.join(os.getcwd() , '..'))
Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...
If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:
@Component({
selector: 'my-component',
template: 'app-element',
host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}
And if you use a class on the entry tag, Angular will merge the classes, i.e.,
<my-component class="someClass2">
I have both someClass1 & someClass2 applied to me
</my-component>
That's what I do:
Component:
const Button = ({ className }) => (
<div className={ className }> </div>
);
Calling Component:
<Button className = 'hashButton free anotherClass' />
Try:
Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools
from an elevated PowerShell (run as Administrator).
You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.
This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6
I had the same issue, but when I ran the following command, it was ok:
php artisan config:cache
You should now be able to browse to your container via localhost:8080 and your-internal-ip:8080.
The way I do is go to http://getbootstrap.com/customize/ and only check "grid system" to download. There are bootstrap-theme.css
and bootstrap.css
in downloaded files, and I only need the latter.
In this way, I can use the grid system of Bootstrap, with everything else from Material UI.
ts-node
node module globally.node
in command line to run below file js
file (The path is for windows, but you can do it for linux as well)
~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
ts
file path as a command line argument.In my case, I got the error when I had my Web Application in 4.5.2 and the referenced class libaries in 4.6.1. When I updated the Web Application to 4.5.2 version the error went away.
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
why not try opening your file as text?
with open(fname, 'rt') as f:
lines = [x.strip() for x in f.readlines()]
Additionally here is a link for python 3.x on the official page: https://docs.python.org/3/library/io.html And this is the open function: https://docs.python.org/3/library/functions.html#open
If you are really trying to handle it as a binary then consider encoding your string.
Had the same issue, API was enabled for my project but not for the specific API key I was using.
You should be able to see your API keys here: https://console.cloud.google.com/apis/credentials
Then click on the key you're using and enable the API for that. For me it took ~5min for the changes to take effect.
The solution is quite easy.
This is one of the solution which worked for me.
It might be possible that your project's app/build/outputs/apk folder is opened.
so just close this folder and rebuild your project. and it will be solved.
Starting with v0.20.0
, the dtype
keyword argument in read_excel()
function could be used to specify the data types that needs to be applied to the columns just like it exists for read_csv()
case.
Using converters
and dtype
arguments together on the same column name would lead to the latter getting shadowed and the former gaining preferance.
1) Inorder for it to not interpret the dtypes
but rather pass all the contents of it's columns as they were originally in the file before, we could set this arg to str
or object
so that we don't mess up our data. (one such case would be leading zeros in numbers which would be lost otherwise)
pd.read_excel('file_name.xlsx', dtype=str) # (or) dtype=object
2) It even supports a dict mapping wherein the keys
constitute the column names and values
it's respective data type to be set especially when you want to alter the dtype
for a subset of all the columns.
# Assuming data types for `a` and `b` columns to be altered
pd.read_excel('file_name.xlsx', dtype={'a': np.float64, 'b': np.int32})
Raw code:
function capi(str) {
var s2 = str.trim().toLowerCase().split(' ');
var s3 = [];
s2.forEach(function(elem, i) {
s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
});
return s3.join(' ');
}
capi('JavaScript string exasd');
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/
In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"
Filter out people with gender = 'm'
var people = [
{
name: 'john',
age: 10,
gender: 'm'
},
{
name: 'joseph',
age: 12,
gender: 'm'
},
{
name: 'annie',
age: 8,
gender: 'f'
}
]
var filters = {
gender: 'm'
}
var out = people.filter(person => {
return Object.keys(filters).every(filter => {
return filters[filter] === person[filter]
});
})
console.log(out)
_x000D_
Filter out people with gender = 'm' and name = 'joseph'
var people = [
{
name: 'john',
age: 10,
gender: 'm'
},
{
name: 'joseph',
age: 12,
gender: 'm'
},
{
name: 'annie',
age: 8,
gender: 'f'
}
]
var filters = {
gender: 'm',
name: 'joseph'
}
var out = people.filter(person => {
return Object.keys(filters).every(filter => {
return filters[filter] === person[filter]
});
})
console.log(out)
_x000D_
You can give as many filters as you want.
UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.
Iterating through all subplots sequentially:
fig, axes = plt.subplots(nrows, ncols)
for ax in axes.flatten():
ax.plot(x,y)
Accessing a specific index:
for row in range(nrows):
for col in range(ncols):
axes[row,col].plot(x[row], y[col])
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
We can write multiple Filter/where conditions in Dataframe.
For example:
table1_df
.filter($"Col_1_name" === "buddy") // check for equal to string
.filter($"Col_2_name" === "A")
.filter(not($"Col_2_name".contains(" .sql"))) // filter a string which is not relevent
.filter("Col_2_name is not null") // no null filter
.take(5).foreach(println)
In my case, just using flex-shrink: 0
didn't work. But adding flex-grow: 1
to it worked.
.item {
flex-shrink: 0;
flex-grow: 1;
}
You can use setState inside componentDidUpdate
Visual Studio
windows.h
)Visual Studio Code
In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne
Unfortunately it doesn't work then the argument got it's default value defined.
one can first check if the argument was provided by comparing it with the Namespace
object and providing the default=argparse.SUPPRESS
option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
Usage
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
With
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
Has
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
This is a fast way to encode the array, the array shape and the array dtype:
def numpy_to_bytes(arr: np.array) -> str:
arr_dtype = bytearray(str(arr.dtype), 'utf-8')
arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
sep = bytearray('|', 'utf-8')
arr_bytes = arr.ravel().tobytes()
to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
return to_return
def bytes_to_numpy(serialized_arr: str) -> np.array:
sep = '|'.encode('utf-8')
i_0 = serialized_arr.find(sep)
i_1 = serialized_arr.find(sep, i_0 + 1)
arr_dtype = serialized_arr[:i_0].decode('utf-8')
arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
arr_str = serialized_arr[i_1 + 1:]
arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
return arr
To use the functions:
a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype
When app is release some time that case https://developers.facebook.com/apps/{$appid}/alerts/ "Your app has been placed into development mode due to an invalid Privacy Policy." can change you app from release mode to development mode so check the Privacy Policy
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
I know it's an old question, but I needed this solution too, and I acme with another solution.
I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:
HOST=`hostname --fqdn`
Then, I used it across my entrypoint script:
echo "Value: $HOST"
Hope this helps
Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :
create(e) {
e.preventDefault();
let name = this.refs.name.input.value;
alert(name);
}
constructor(){
super();
this.create = this.create.bind(this);
}
render() {
return (
<form>
<TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
<RaisedButton label="Create" onClick={this.create} primary={true} />
</form>
)}
hope this helps.
There are a few npm libraries for cancellable promises.
p-cancelable https://github.com/sindresorhus/p-cancelable
cancelable-promise https://github.com/alkemics/CancelablePromise
y my case i solved this by named it in the "Identifier" property of Table View Cell:
Don't forgot: to declare in your Class: UITableViewDataSource
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
In my case the solution was simple:
I have defined the route at the very start of the route.php
file.
After moving the named route to the bottom, my app finally saw it. It means that somehow the route was defined too early.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
I think we're over analyzing and maybe complicating a bit the "continuous" suite of words. In this context continuous means automation. For the other words attached to "continuous" use the English language as your translation guide and please don't try to complicate things! In "continuous build" we automatically build (write/compile/link/etc) our application into something that's executable for a specific platform/container/runtime/etc. "Continuous integration" means that your new functionality tests and performs as intended when interacting with another entity. Obviously, before integration takes place, the build must happen and thorough testing would also be used to validate the integration. So, in "continuous integration" one uses automation to add value to an existing bucket of functionality in a way that doesn't negatively disrupt the existing functionality but rather integrates nicely with it, adding a perceived value to the whole. Integration implies, by its mere English definition, that things jive harmoniously so in code-talk my add compiles, links, tests and runs perfectly within the whole. You wouldn't call something integrated if it failed the end product, would you?! In our context "Continuous deployment" is synonymous with "continuos delivery" since at the end of the day we've provided functionality to our customers. However, by over analyzing this, I could argue that deploy is a subset of delivery because deploying something doesn't necessarily mean that we delivered. We deployed the code but because we haven't effectively communicated to our stakeholders, we failed to deliver from a business perspective! We deployed the troops but we haven't delivered the promised water and food to the nearby town. What if I were to add the "continuous transition" term, would it have its own merit? After all, maybe it's better suited to describe the movement of code through environments since it has the connotation of "from/to" more so than deployment or delivery which could imply one location only, in perpetuity! This is what we get if we don't apply common sense.
In conclusion, this is simple stuff to describe (doing it is a bit more ...complicated!), just use common sense, the English language and you'll be fine.
Just wanted to point out that the built-in sink
function has good examples of different ways to set arguments in a function:
> sink
function (file = NULL, append = FALSE, type = c("output", "message"),
split = FALSE)
{
type <- match.arg(type)
if (type == "message") {
if (is.null(file))
file <- stderr()
else if (!inherits(file, "connection") || !isOpen(file))
stop("'file' must be NULL or an already open connection")
if (split)
stop("cannot split the message connection")
.Internal(sink(file, FALSE, TRUE, FALSE))
}
else {
closeOnExit <- FALSE
if (is.null(file))
file <- -1L
else if (is.character(file)) {
file <- file(file, ifelse(append, "a", "w"))
closeOnExit <- TRUE
}
else if (!inherits(file, "connection"))
stop("'file' must be NULL, a connection or a character string")
.Internal(sink(file, closeOnExit, FALSE, split))
}
}
for importing the image in flask you want a sub folder named static into the folder keep your img
and go into your html file and write
For those having this problem on IIS servers.
Explanation: sometimes certificates carry an URL of an intermediate certificate instead of the actual certificate. Desktop browsers can DOWNLOAD the missing intermediate certificate using this URL. But older mobile browsers are unable to do that. So they throw this warning.
You need to
1) make sure all intermediate certificates are served by the server
2) disable unneeded certification paths in IIS - Under "Trusted Root Certification Authorities", you need to "disable all purposes" for the certificate that triggers the download.
PS. my colleague has wrote a blog post with more detailed steps: https://www.jitbit.com/maxblog/21-errcertauthorityinvalid-on-android-and-iis/
You can use isTRUE
for such cases. isTRUE
is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }
If you use shiny there you could use isTruthy
which covers the following cases:
FALSE
NULL
""
An empty atomic vector
An atomic vector that contains only missing values
A logical vector that contains all FALSE or missing values
An object of class "try-error"
A value that represents an unclicked actionButton()
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
Comparing to writing your styles in a CSS file, React's style attribute has the following advantages:
However, the React's style attribute comes with a few drawbacks - you can't
Using CSS in JS, you can get all the advantages of a style tag, without those drawbacks. As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium. Those libraries are to CSS kind of what React is to HTML. They allow you to write your CSS and control your CSS in your JS code.
let's compare how our code will look for styling a simple element. We'll style a "hello world" div so it shows big on desktop and smaller on mobile.
Using the style attribute
return (
<div style={{fontSize:24}} className="hello-world">
Hello world
</div>
)
Since media query is not possible in a style tag, we'll have to add a className to the element and add a css rule.
@media screen and (max-width: 700px){
.hello-world {
font-size: 16px;
}
}
Using Emotion's 10 CSS tag
return (
<div
css={{
fontSize: 24,
[CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
fontSize: 16
}
}
>
Hello world
</div>
)
Emotion also supports template strings as well as styled-components. So if you prefer you can write:
return (
<Box>
Hello world
</Box>
)
const Box = styled.div`
font-size: 24px;
${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
font-size: 16px;
}
`
Behind the hoods "CSS in JS" uses CSS classes. Emotion specifically built with performance in mind and uses caching. Compared to React style attributes CSS in JS will provide better performance.
###Best Practices
Here are a few best practices I recommend:
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
should I avoid inline styles completely?
// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
BUTTON: css`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
}
// SomeButton.js
const SomeButton = (props) => {
...
return (
<button
css={COMMON_STYLES.BUTTON}
...
>
Click Me
</button>
)
}
// Option 2 - Write your common styles in a dedicated component
const Button = styled.button`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
const SomeButton = (props) => {
...
return (
<Button ...>
Click me
</Button>
)
}
React coding pattern is of encapsulated components - HTML and JS that controls a component is written in one file. That is where your css/style code to style that component belongs.
When necessary, add a styling prop to your component. This way you can reuse code and style written in a child component, and customize it to your specific needs by the parent component.
const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])
const SmallButton = (props)=>(
<Button
...
stl={css`font-size: 12px`}
>
Click me if you can see me
</Button>
)
const BigButton = (props) => (
<Button
...
stl={css`font-size: 30px;`}
>
Click me
</Button>
)
Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct
EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:
Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps
If you plot in IPython console (where you can't use %matplotlib inline
) instead of Jupyter notebook, and don't want to run plt.show()
repeatedly, you can start IPython console with ipython --pylab
:
$ ipython --pylab
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg
In [1]: import seaborn as sns
In [2]: tips = sns.load_dataset("tips")
In [3]: sns.relplot(x="total_bill", y="tip", data=tips) # you can see the plot now
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
try parsing a default value which can be returned by max if length of v none
max(v, default=0)
You can easily make your own 'AlertView' and use it everywhere.
alertView("You really want this?");
Implement it once:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialoginterface, int i) {
// dialoginterface.cancel();
// }})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}
In the case where you are able to import the module when using the CLI interpreter but not in PyCharm, make sure your project interpreter in PyCharm is set to an actual interpreter (eg. /usr/bin/python2.7) and not venv (~/PycharmProject/venv/...)
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
status of 200 will be the default when using res.send
, res.json
, etc.
You can set the status like res.status(500).json({ error: 'something is wrong' });
Often I'll do something like...
router.get('/something', function(req, res, next) {
// Some stuff here
if(err) {
res.status(500);
return next(err);
}
// More stuff here
});
Then have my error middleware send the response, and do anything else I need to do when there is an error.
Additionally: res.sendStatus(status)
has been added as of version 4.9.0
http://expressjs.com/4x/api.html#res.sendStatus
Swift 3 | UIDeviceOrientationDidChange Notification Observed Too Often
The following code prints "deviceDidRotate" every time your device changes orientation in 3D space - regardless of a change from portrait to landscape orientation. For example, if you hold your phone in portrait orientation and tilt it forward and backward - deviceDidRotate() is called repeatedly.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIDeviceOrientationDidChange,
object: nil
)
}
func deviceDidRotate() {
print("deviceDidRotate")
}
To work around this you could hold the previous device orientation and check for a change in deviceDidRotate().
var previousDeviceOrientation: UIDeviceOrientation = UIDevice.current.orientation
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIDeviceOrientationDidChange,
object: nil
)
}
func deviceDidRotate() {
if UIDevice.current.orientation == previousDeviceOrientation { return }
previousDeviceOrientation = UIDevice.current.orientation
print("deviceDidRotate")
}
Or you can use a different notification that only gets called when the device changes from landscape to portrait. In this case you'd want to use the UIApplicationDidChangeStatusBarOrientation
notification.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIApplicationDidChangeStatusBarOrientation,
object: nil
)
}
func deviceDidRotate() {
print("deviceDidRotate")
}
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.@all
Whole view.@form
Closest ancestor form of current component.@none
No component.and the standard JSF 2.3+ keywords:
@child(n)
nth child.@composite
Closest composite component ancestor.@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.@namingcontainer
Closest ancestor naming container of current component.@parent
Parent of the current component.@previous
Previous sibling.@next
Next sibling.@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.@widgetVar(name)
Component with given widgetVar.And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
To build further upon the ajax part which you may or may not use (from the comments)
a simple way to load another page and replace it with your current one is:
<script>
$(document).ready( function() {
$.ajax({
type: 'get',
url: 'http://pageToLoad.from',
success: function(response) {
// response = data which has been received and passed on to the 'success' function.
$('body').html(response);
}
});
});
<script>
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
There's an open-source multi-platform client, written in Go: drive. It's quite nice and full-featured, and also is in active development.
$ drive help pull
Name
pull - pulls remote changes from Google Drive
Description
Downloads content from the remote drive or modifies
local content to match that on your Google Drive
Note: You can skip checksum verification by passing in flag `-ignore-checksum`
* For usage flags: `drive pull -h`
The Accept Ranges
header (the bit in writeHead()
) is required for the HTML5 video controls to work.
I think instead of just blindly send the full file, you should first check the Accept Ranges
header in the REQUEST, then read in and send just that bit. fs.createReadStream
support start
, and end
option for that.
So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat
to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream
to send the requested part to the client.
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path");
http.createServer(function (req, res) {
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
} else {
var file = path.resolve(__dirname,"movie.mp4");
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
}).listen(8888);
Try this instead:
ping -c2 -s16 sntdn | awk '{print NR " | " strftime("%Y-%m-%d_%H:%M:%S") " | " $0 }'
Check if it suits you
Another reason for "lost update" can be the next:
If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this
static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}
Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)
Swift 4
let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
You need to remove the raw value in swift 4
The warning message MAY BE due to an XMLHttpRequest request within the main thread with the async flag set to false.
https://xhr.spec.whatwg.org/#synchronous-flag:
Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.
The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.
Based on Jacob Tabak's answer (+1 for him), I was able to add onLongClick listener:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Then you can use it like this:
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// ...
}
@Override
public void onItemLongClick(View view, int position) {
// ...
}
}));
Here's the complete answer for the future reader. Note that this is only possible in Laravel 5+.
First of all you'll need the doctrine/dbal package:
composer require doctrine/dbal
Now in your migration you can do this to make the column nullable:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
You may be wondering how to revert this operation. Sadly this syntax is not supported:
// Sadly does not work :'(
$table->integer('user_id')->unsigned()->change();
This is the correct syntax to revert the migration:
$table->integer('user_id')->unsigned()->nullable(false)->change();
Or, if you prefer, you can write a raw query:
public function down()
{
/* Make user_id un-nullable */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
Hopefully you'll find this answer useful. :)
VARCHAR with probably 15-20 length would be sufficient and would be the best option for the database. Since you would probably require various hyphens and plus signs along with your phone numbers.
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler
argument. Observe:
func someHandler(alert: UIAlertAction!) {
// Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: someHandler))
You can also use values.makeIterator()
to iterate over dict values, like this:
for sb in sbItems.values.makeIterator(){
// do something with your sb item..
print(sb)
}
You can also do the iteration like this, in a more swifty style:
sbItems.values.makeIterator().forEach{
// $0 is your dict value..
print($0)
}
sbItems
is dict of type [String : NSManagedObject]
From The Swift Programming Language
:
The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.
The sort
function has two declarations.
The default declaration which allows you to specify a comparison closure:
func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]
And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."
func sort<T : Comparable>(array: T[]) -> T[]
Example:
sort( _arrayToSort_ ) { $0 > $1 }
I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.
let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = random()
}
let y = sort(x) { $0 > $1 }
It is not an efficient function, an I would recommend using a better sorting function implementation.
EDIT:
I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)
import Foundation
func quickSort(inout array: Int[], begin: Int, end: Int) {
if (begin < end) {
let p = partition(&array, begin, end)
quickSort(&array, begin, p - 1)
quickSort(&array, p + 1, end)
}
}
func partition(inout array: Int[], left: Int, right: Int) -> Int {
let numElements = right - left + 1
let pivotIndex = left + numElements / 2
let pivotValue = array[pivotIndex]
swap(&array[pivotIndex], &array[right])
var storeIndex = left
for i in left..right {
let a = 1 // <- Used to see how many comparisons are made
if array[i] <= pivotValue {
swap(&array[i], &array[storeIndex])
storeIndex++
}
}
swap(&array[storeIndex], &array[right]) // Move pivot to its final place
return storeIndex
}
let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = Int(arc4random())
}
quickSort(&x, 0, x.count - 1) // <- Does the sorting
for i in 0..n {
x[i] // <- Used by the playground to display the results
}
Using this with n=1000, I found that
It seems that the built-in sort method is (or is close to) quick sort, and is really slow...
Please run this in your terminal:
$ vagrant box list
You will see something like laravel/homestead(virtualbox,x.x.x)
Next locate your Vagrantfile
and locate the line that says
config.vm.box = "box"
replace box
with the box name when you run vagrant box list
.
Make sure that you are editing the correct build.gradle
file. I received this error when editing android/build.gradle
rather than android/app/build.gradle
.
You need to use the bracket notation because key
is a variable holding the key as a value
$.each(sjonObj, function(key,value){
// console.log(value);
if(value==""||value==null){
delete sjonObj[key];
}
});
delete sjonObj.key
deletes the property called key
from sjonObj
, instead you need to use key
as a variable holding the property name.
Note: Still it will not handle the nested objects
Like this.
function printMousePos(event) {_x000D_
document.body.textContent =_x000D_
"clientX: " + event.clientX +_x000D_
" - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
express.basicAuth
is gonebasic-auth-connect
is deprecatedbasic-auth
doesn't have any logichttp-auth
is an overkillexpress-basic-auth
is what you wantSince you're using Express then you can use the express-basic-auth
middleware.
See the docs:
Example:
const app = require('express')();
const basicAuth = require('express-basic-auth');
app.use(basicAuth({
users: { admin: 'supersecret123' },
challenge: true // <--- needed to actually show the login dialog!
}));
Comment out the res.render
lines in your code and add in next(err);
instead. If you're not using a view engine, the res.render
stuff will throw an error.
Sorry, you'll have to comment out this line as well:
app.set('view engine', 'html');
My solution would result in not using a view engine though. You don't need a view engine, but if that's the goal, try this:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//swap jade for ejs etc
You'll need the res.render
lines when using a view engine as well. Something like this:
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
next(err);
res.render('error', {
message: err.message,
error: {}
});
});
<script type="text/javascript">
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
<form id="myform" action="/your_url" method="post">
...
</form>
Okay, redis is pretty user friendly but there are some gotchas.
Here are just some easy commands for working with redis on Ubuntu:
install:
sudo apt-get install redis-server
start with conf:
sudo redis-server <path to conf>
sudo redis-server config/redis.conf
stop with conf:
redis-ctl shutdown
(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)
log:
tail -f /var/log/redis/redis-server.log
Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:
/etc/redis/redis.conf
Then paste it at <path to conf>
, tweak as needed and you're good to go.
I did everything from visiting http://www.google.com/accounts/DisplayUnlockCaptcha to setting up 2-fa and creating an application password. The only thing that worked was logging into http://mail.google.com and sending an email from the server itself.
This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.
If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
to:
RewriteRule ^(wp-(content|admin|includes).*) - [L]
The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.
It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.
-p|--parent
will be used if you are trying to create a directory with top-down
approach. That will create the parent directory then child and so on iff none exists.
-p, --parents no error if existing, make parent directories as needed
About rlidwka
it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.
Setting spring.datasource.tomcat.testOnBorrow=true
in application.properties didn't work.
Programmatically setting like below worked without any issues.
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
@Bean
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(this.properties.getDatabase().getUrl());
poolProperties.setUsername(this.properties.getDatabase().getUsername());
poolProperties.setPassword(this.properties.getDatabase().getPassword());
//here it is
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
return new DataSource(poolProperties);
}
You can sum up the values of a BigDecimal
stream using a reusable Collector named summingUp
:
BigDecimal sum = bigDecimalStream.collect(summingUp());
The Collector
can be implemented like this:
public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
Just in case someone else runs into this problem I solved it by the following
brew update && brew upgrade # installs libpng 1.6
This caused an error with other packages requiring 1.5 which they were built with, so I linked it:
cd /usr/local/lib/
ln -s ../Cellar/libpng/1.5.18/lib/libpng15.15.dylib
Now they are both living in harmony and side by side for the different packages. It would be better to rebuild the packages that depend on 1.5, but this works as a quick bandage fix.
Use $http Interceptor
By using an $http interceptor you can send headers to Back-end or the other way around and do your checks that way.
Great article on $http interceptors
Example:
$httpProvider.interceptors.push(function ($q) {
return {
'response': function (response) {
// TODO Create check for user authentication. With every request send "headers" or do some other check
return response;
},
'responseError': function (reject) {
// Forbidden
if(reject.status == 403) {
console.log('This page is forbidden.');
window.location = '/';
// Unauthorized
} else if(reject.status == 401) {
console.log("You're not authorized to view this page.");
window.location = '/';
}
return $q.reject(reject);
}
};
});
Put this in your .config or .run function.
Along the lines of ggovan's answer, I do this as follows:
/**
* Provides various high-order functions.
*/
public final class F {
/**
* When the returned {@code Function} is passed as an argument to
* {@link Stream#flatMap}, the result is a stream of instances of
* {@code cls}.
*/
public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
return o -> cls.isInstance(o)
? Stream.of(cls.cast(o))
: Stream.empty();
}
}
Using this helper function:
Stream.of(objects).flatMap(F.instancesOf(Client.class))
.map(Client::getId)
.forEach(System.out::println);
You'll need to use fs
for that: http://nodejs.org/api/fs.html
And in particular the fs.rename()
function:
var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.
fs.readFile('/path/to/countries.json', function(error, data) {
if (error) {
console.log(error);
return;
}
var obj = JSON.parse(data);
for(var p in obj) {
fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
}
});
(This assumes here that your .json
file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Calling System.exit(0)
(or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java
process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System
class, the compiler does not know what it will do - and hence does not complain about unreachable code.
return
statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void
(as in your example), then you do not need to specify a value, as you'd need to return void
. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.
return
would cause the program to exit only if it's inside the main
method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:
public static void main(String... str) {
System.out.println(1);
return;
System.out.println(2);
System.exit(0);
}
will not compile with most compiler - producing unreachable code
error pointing to the second System.out.println
call.
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
I know, that maybe it sounds stuppid, but perhaps it can be the best and the easiest solution.
You have to create additional Excel file. It can be even empty. Or you can use any other existing Excel file from your directories.
'Start'
Workbooks.Open("File_where_you_have_to_do_refresh.xlsx")
Workbooks("File_where_you_have_to_do_refresh.xlsx").RefreshAll
Workbooks.Open("Any_file.xlsx)
'Excell is waiting till Refresh on first file will finish'
Workbooks("Any_file.xlsx).Close False
Workbooks("File_where_you_have_to_do_refresh.xlsx").Save
or use this:
Workbooks("File_where_you_have_to_do_refresh.xlsx").Close True
It's working properly on all my files.
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
I'm posting this because (to my surprise) there was no other place I could find that recommended this.
There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label>
tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].
The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:
label.myLabel input[type="file"] {_x000D_
position:absolute;_x000D_
top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
border: 2px solid #AAA;_x000D_
border-radius: 4px;_x000D_
padding: 2px 5px;_x000D_
margin: 2px;_x000D_
background: #DDD;_x000D_
display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
<input type="file" required/>_x000D_
<span>My Label</span>_x000D_
</label>
_x000D_
I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden
or display:none
file-input). I've tested in emulated IE7 and up, and it worked perfectly.
<button>
s inside <label>
tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.for
attribute is defined, its value is used to trigger the input with the same id
as the for
attribute on the <label>
.One obvious thing is that you will have to remove the comma here
receipt int(10),
but the actual problem is because of the line
amount double(10) NOT NULL,
change it to
amount double NOT NULL,
To solve this issue the first thing you need to do is to get the last version of composer :
curl -sS https://getcomposer.org/installer | php
I recommend you to move the composer.phar file to a global “bin” directoy, in my case (OS X) the path is:
mv composer.phar /usr/local/bin/composer.phar
than you need to create an alias file for an easy access
alias composer='/usr/local/bin/composer.phar'
If everything is ok, now it is time to verify our Composer version:
composer --version
Let's make composer great again.
In Android Studio
1) Open terminal and ensure you are at project's root folder.
2) Run ./gradlew app:dependencies
(if not using gradle wrapper, try gradle app:dependencies
)
Note that running ./gradle dependencies
will only give you dependency tree of project's root folder, so mentioning app in above manner, i.e. ./gradlew app:dependencies
is important.
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
On the .ASPX
page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
response(data.d);
}
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>
In your .ASPX.CS
code-behind file:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");
SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
con.Open();
cmd.Parameters.AddWithValue("@Name", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}
Extending answer of @MichaelLaCroix when a scenario is that the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.
In the case of <Filters />
and <TopBar />
don't have any of the above relationship, a simple global emitter could be used like this:
componentDidMount
- Subscribe to event
componentWillUnmount
- Unsubscribe from event
EventSystem.js
class EventSystem{
constructor() {
this.queue = {};
this.maxNamespaceSize = 50;
}
publish(/** namespace **/ /** arguments **/) {
if(arguments.length < 1) {
throw "Invalid namespace to publish";
}
var namespace = arguments[0];
var queue = this.queue[namespace];
if (typeof queue === 'undefined' || queue.length < 1) {
console.log('did not find queue for %s', namespace);
return false;
}
var valueArgs = Array.prototype.slice.call(arguments);
valueArgs.shift(); // remove namespace value from value args
queue.forEach(function(callback) {
callback.apply(null, valueArgs);
});
return true;
}
subscribe(/** namespace **/ /** callback **/) {
const namespace = arguments[0];
if(!namespace) throw "Invalid namespace";
const callback = arguments[arguments.length - 1];
if(typeof callback !== 'function') throw "Invalid callback method";
if (typeof this.queue[namespace] === 'undefined') {
this.queue[namespace] = [];
}
const queue = this.queue[namespace];
if(queue.length === this.maxNamespaceSize) {
console.warn('Shifting first element in queue: `%s` since it reached max namespace queue count : %d', namespace, this.maxNamespaceSize);
queue.shift();
}
// Check if this callback already exists for this namespace
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
throw ("The exact same callback exists on this namespace: " + namespace);
}
}
this.queue[namespace].push(callback);
return [namespace, callback];
}
unsubscribe(/** array or topic, method **/) {
let namespace;
let callback;
if(arguments.length === 1) {
let arg = arguments[0];
if(!arg || !Array.isArray(arg)) throw "Unsubscribe argument must be an array";
namespace = arg[0];
callback = arg[1];
}
else if(arguments.length === 2) {
namespace = arguments[0];
callback = arguments[1];
}
if(!namespace || typeof callback !== 'function') throw "Namespace must exist or callback must be a function";
const queue = this.queue[namespace];
if(queue) {
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
queue.splice(i, 1); // only unique callbacks can be pushed to same namespace queue
return;
}
}
}
}
setNamespaceSize(size) {
if(!this.isNumber(size)) throw "Queue size must be a number";
this.maxNamespaceSize = size;
return true;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
NotificationComponent.js
class NotificationComponent extends React.Component {
getInitialState() {
return {
// optional. see alternative below
subscriber: null
};
}
errorHandler() {
const topic = arguments[0];
const label = arguments[1];
console.log('Topic %s label %s', topic, label);
}
componentDidMount() {
var subscriber = EventSystem.subscribe('error.http', this.errorHandler);
this.state.subscriber = subscriber;
}
componentWillUnmount() {
EventSystem.unsubscribe('error.http', this.errorHandler);
// alternatively
// EventSystem.unsubscribe(this.state.subscriber);
}
render() {
}
}
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.
I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.
I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
});
}
res.writeHead( ... );
res.end(results);
The problem with the previous code is that the search
function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results
is empty.
To fix the problem, you have to put the code after the loop in the callback function.
search(query, function(result) {
results.push(result);
// Put res.writeHead( ... ) and res.end(results) here
});
However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.
To get a list of all keys, use Object.keys
. Then, to iterate through this list, I use .forEach
(you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }
, but that could give problems, see JavaScript closure inside loops – simple practical example).
Here's a complete example:
var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
res.writeHead( ... );
res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
onComplete();
} else {
// There is at least one element, so the callback will be called.
keys.forEach(function(key) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
if (--tasksToGo === 0) {
// No tasks left, good to go
onComplete();
}
});
});
}
Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:
var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
if (index === keys.length) { // No items left
res.writeHead( ... );
res.end(results);
return;
}
var key = keys[index];
var query = config[key].query;
search(query, function(result) {
results.push(result);
next(index + 1);
});
})(0);
What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.
According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null
. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}
), or a list with a null value ([null]
), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}
) or an empty list ([]
) are perfectly fine, but aren't null either.
In Python:
>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
[None]
>>> print json.loads('[]')
[]
>>> print json.loads('{}')
{}
>>> print json.loads('null')
None
I wouldn't recommend doing this, but you can override the ngClick
directive to do what you are looking for. That's not saying, you should.
With the original implementation in mind:
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
We can do this to override it:
// Go into your config block and inject $provide.
app.config(function ($provide) {
// Decorate the ngClick directive.
$provide.decorator('ngClickDirective', function ($delegate) {
// Grab the actual directive from the returned $delegate array.
var directive = $delegate[0];
// Stow away the original compile function of the ngClick directive.
var origCompile = directive.compile;
// Overwrite the original compile function.
directive.compile = function (el, attrs) {
// Apply the original compile function.
origCompile.apply(this, arguments);
// Return a new link function with our custom behaviour.
return function (scope, el, attrs) {
// Get the name of the passed in function.
var fn = attrs.ngClick;
el.on('click', function (event) {
scope.$apply(function () {
// If no property on scope matches the passed in fn, return.
if (!scope[fn]) {
return;
}
// Throw an error if we misused the new ngClick directive.
if (typeof scope[fn] !== 'function') {
throw new Error('Property ' + fn + ' is not a function on ' + scope);
}
// Call the passed in function with the event.
scope[fn].call(null, event);
});
});
};
};
return $delegate;
});
});
Then you'd pass in your functions like this:
<div ng-click="func"></div>
as opposed to:
<div ng-click="func()"></div>
jsBin: http://jsbin.com/piwafeke/3/edit
Like I said, I would not recommend doing this but it's a proof of concept showing you that, yes - you can in fact overwrite/extend/augment the builtin angular behaviour to fit your needs. Without having to dig all that deep into the original implementation.
Do please use it with care, if you were to decide on going down this path (it's a lot of fun though).
You can remove passphrase for the key
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
or you can run
$ ssh-keygen -p
you get a prompt for keyfile. By default it ~/.ssh/id_rsa
so press enter
You'll be prompted for current pass phrase enter it.
Then there will be a prompt for new pass phrase, press enter
I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.
If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.
Since Dec 2014 Travis CI offers an Enterprise on-premises version.
http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/
The pricing is part of the article as well:
The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.
We also faced this issue recently. If the issue is related to mapper memory, couple of things I would like to suggest that needs to be checked are.
One way to achieve this is using a position:fixed
container for the background image and place it outside of the .jumbotron
. Make the bg
container the same height as the .jumbotron
and center the background image:
background: url('/assets/example/...jpg') no-repeat center center;
CSS
.bg {
background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
position: fixed;
width: 100%;
height: 350px; /*same height as jumbotron */
top:0;
left:0;
z-index: -1;
}
.jumbotron {
margin-bottom: 0px;
height: 350px;
color: white;
text-shadow: black 0.3em 0.3em 0.3em;
background:transparent;
}
Then use jQuery to decrease the height of the .jumbtron
as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.
JavaScript
var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
var scrolled = $(window).scrollTop();
$('.bg').css('height', (jumboHeight-scrolled) + 'px');
}
$(window).scroll(function(e){
parallax();
});
Demo
use this filter:
(dns.flags.response == 0) and (ip.src == 159.25.78.7)
what this query does is it only gives dns queries
originated from your ip
If you take a look at the source of the select
method, you can see that what it does when you pass a from
key is essentially:
find(:select, from, options).find(:option, value, options).select_option
In other words, it finds the <select>
you're interested in, then finds the <option>
within that, then calls select_option
on the <option>
node.
You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option
method on the end:
find('#organizationSelect').find(:xpath, 'option[2]').select_option
<script>
$(function() {
$("#client").on("change", function() {
var clientid=$("#client").val();
//show the loading div here
$.ajax({
type:"post",
url:"clientnetworkpricelist/yourfile.php",
data:"title="+clientid,
success:function(data){
$("#result").html(data);
//hide the loading div here
}
});
});
});
</script>
Or you can also do this:
$(document).ajaxStart(function() {
// show loader on start
$("#loader").css("display","block");
}).ajaxSuccess(function() {
// hide loader on success
$("#loader").css("display","none");
});
It helps not to focus on the strong
or weak
part of the discussion. Instead focus on the cycle part.
A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:
Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.
So, what we're worried about is retain cycles, and there's nothing about blocks in and of themselves that create these cycles. This isn't a problem, for example:
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
[self doSomethingWithObject:obj];
}];
The block retains self
, but self
doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.
Where you get into trouble is something like:
//In the interface:
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL *stop);
//In the implementation:
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWithObj:obj];
}];
Now, your object (self
) has an explicit strong
reference to the block. And the block has an implicit strong reference to self
. That's a cycle, and now neither object will be deallocated properly.
Because, in a situation like this, self
by definition already has a strong
reference to the block, it's usually easiest to resolve by making an explicitly weak reference to self
for the block to use:
__weak MyObject *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[weakSelf doSomethingWithObj:obj];
}];
But this should not be the default pattern you follow when dealing with blocks that call self
! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self
was deallocated.
//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
//By the time this gets called, "weakSelf" might be nil because it's not retained!
[weakSelf doSomething];
}];
Your first usage of Map
is inside a function in the combat
class. That happens before Map
is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map
is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h
file and the function bodies in a .cpp
. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier
date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")
This was you can always keep a check of when it was run
Try adding this rule to the top of your htaccess:
RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]
Then under that (or any other rules that you have):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]
In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.
<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />
and
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
Use value(cellref)
on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173
).
This is a shot in the dark but try putting the two operands for the AND in parentheses
On ((A = B) And (C = D))
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)
Pay attention to the opposite position of parameters.
This should do the trick:
mapper.readValue(fileReader, MyClass.class);
I say should because I'm using that with a String
, not a BufferedReader
but it should still work.
Here's my code:
String inputString = // I grab my string here
MySessionClass sessionObject;
try {
ObjectMapper objectMapper = new ObjectMapper();
sessionObject = objectMapper.readValue(inputString, MySessionClass.class);
Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)
You can also define a custom deserializer when you instantiate the ObjectMapper
:
http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
Edit:
I just remembered something else. If your object coming in has more properties than the POJO
has and you just want to ignore the extras you'll want to set this:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Or you'll get an error that it can't find the property to set into.
Verify you have following signature of your MyContext
class
public class MyContext : IdentityDbContext<MyUser>
Or
public class MyContext : IdentityDbContext
The code is working for me, without any modification!!!
In the case of web applications, another cause of slow building and debugging (but not IDE navigation) could be the Browser Link feature.
I found that with this switched on, building would take 4 times longer and debugging was painful - after every postback, web pages would freeze for a few seconds before you could interact with them.
The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.
Here is the script https://github.com/kedarvj/mysqldumpsplitter
And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully
I've found the best implementation. It's in the Google I/O 2014 app.
They use the same approach as Kevin's. If you can abstract yourself from all unneeded stuff in I/O app, you could extract everything you need and it is assured by Google that it's a correct usage of navigation drawer pattern.
Each activity optionally has a DrawerLayout
as its main layout. The interesting part is how the navigation to other screens is done. It is implemented in BaseActivity
like this:
private void goToNavDrawerItem(int item) {
Intent intent;
switch (item) {
case NAVDRAWER_ITEM_MY_SCHEDULE:
intent = new Intent(this, MyScheduleActivity.class);
startActivity(intent);
finish();
break;
This differs from the common way of replacing current fragment by a fragment transaction. But the user doesn't spot a visual difference.
If you really want a vba solution you can loop through a range like this:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
*EDIT*
Instead of using varients you can just loop through the range like this:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
I encountered this error while there is an invisible view in an activity xml layout. At that time it was not used in my case so I have removed it and the crash is not seen anymore.
Below is an other approach that was useful for me
convertLittleEndianByteArrayToBigEndianByteArray (byte littlendianByte[], byte bigEndianByte[], int ArraySize){
int i =0;
for(i =0;i<ArraySize;i++){
bigEndianByte[i] = (littlendianByte[ArraySize-i-1] << 7 & 0x80) | (littlendianByte[ArraySize-i-1] << 5 & 0x40) |
(littlendianByte[ArraySize-i-1] << 3 & 0x20) | (littlendianByte[ArraySize-i-1] << 1 & 0x10) |
(littlendianByte[ArraySize-i-1] >>1 & 0x08) | (littlendianByte[ArraySize-i-1] >> 3 & 0x04) |
(littlendianByte[ArraySize-i-1] >>5 & 0x02) | (littlendianByte[ArraySize-i-1] >> 7 & 0x01) ;
}
}
You can use the following to make type="number"
accept positive numbers only:
input type="number" step="1" pattern="\d+"
Try this:
[[UINavigationBar appearance] setBackgroundImage: [UIImage new]
forBarMetrics: UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
Below image has the explanation (iOS7 NavigationBar):
And check this SO question: iOS7 - Change UINavigationBar border color
As all said above, you can easily install xampp first from https://www.apachefriends.org/download.html Then follow the instructions as:
http://localhost:80
and database at port 3306
, and PhpMyadmin at http://localhost/phpmyadmin/
Edit your settings.py
file like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '',
}}
Install the following packages in the virtualenv (if you're using django on virtualenv, which is more preferred):
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
That's it!! you have configured Django with MySQL in a very easy way.
Now run your Django project:
python manage.py migrate
python manage.py runserver
Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=gmailpassword
[email protected]
need authenticate username and password of mail then only once can successfully send mail from localhost
Something like this for $.ajax
(HTML5 only though):
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});
Note the require-dev (root-only) !
which means that the require-dev section is only valid when your package is the root of the entire project. I.e. if you run composer update
from your package folder.
If you develop a plugin for some main project, that has it's own composer.json, then your require-dev section will be completely ignored! If you need your developement dependencies, you have to move your require-dev to composer.json in main project.
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
If you uninstall all the files but it still fails, use this line:
sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk
I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:
Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)
When UserForm was destroyed (after Unload Me
) the memory allocated for the data loaded in the mainPicture
was not being de-allocated. I had to add an explicit
mainPicture = Nothing
in the terminate event.
why not simplify it?
jquery
$('.clickable').on('click', function() {//on parent click
$(this).removeClass('spot').addClass('grown');//use remove/add Class here because it needs to perform the same action every time, you don't want a toggle
}).children('.close_button').on('click', function(e) {//on close click
e.stopPropagation();//stops click from triggering on parent
$(this).parent().toggleClass('spot grown');//since this only appears when .grown is present, toggling will work great instead of add/remove Class and save some space
});
This way it's much easier to maintain.
made a fiddle: http://jsfiddle.net/filever10/3SmaV/
You can try more system indeppended method: system("pause");
Microsoft Access and LibreOffice Base can open a spreadsheet as a source and run sql queries on it. That would be the easiest way to run all kinds of queries, and avoid the mess of running macros or writing code.
Excel also has autofilters and data sorting that will accomplish a lot of simple queries like your example. If you need help with those features, Google would be a better source for tutorials than me.
You should use Asset Catalog:
I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.
Note: No need to make any entry in info.plist file :) And no any other configuration.
In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.
Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon.
If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution.
After uploading all required dimensions, you shouldn't get any warning.
2 possible reasons:
HTML
<div id="footer"></div>
CSS
#footer {
position:absolute;
bottom:0;
width:100%;
height:100px;
background:blue;//optional
}
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
A complete solution is here.
$(document).ready(function() {
$("#checkedAll").change(function() {
if (this.checked) {
$(".checkSingle").each(function() {
this.checked=true;
});
} else {
$(".checkSingle").each(function() {
this.checked=false;
});
}
});
$(".checkSingle").click(function () {
if ($(this).is(":checked")) {
var isAllChecked = 0;
$(".checkSingle").each(function() {
if (!this.checked)
isAllChecked = 1;
});
if (isAllChecked == 0) {
$("#checkedAll").prop("checked", true);
}
}
else {
$("#checkedAll").prop("checked", false);
}
});
});
Html should be :
Single check box on checked three checkbox will be select and deselect.
<input type="checkbox" name="checkedAll" id="checkedAll" />
<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />
Hope this helps to someone as it did for me.
JS Fiddle https://jsfiddle.net/52uny55w/
man you can use the basic Bootstrap Datepicker this way:
<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pickyDate').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
and inside body:
<body>
<div id="testDIV">
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</div>
</div>
</div>
datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.
In batch, the >
is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /?
help):
where compare-op may be one of:
EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal
That should explain what you want. The only other compare-op is ==
which can be switched with the if not
parameter. Other then that rely on these three letter ones.
You should avoid using pool.getConnection()
if you can. If you call pool.getConnection()
, you must call connection.release()
when you are done using the connection. Otherwise, your application will get stuck waiting forever for connections to be returned to the pool once you hit the connection limit.
For simple queries, you can use pool.query()
. This shorthand will automatically call connection.release()
for you—even in error conditions.
function doSomething(cb) {
pool.query('SELECT 2*2 "value"', (ex, rows) => {
if (ex) {
cb(ex);
} else {
cb(null, rows[0].value);
}
});
}
However, in some cases you must use pool.getConnection()
. These cases include:
If you must use pool.getConnection()
, ensure you call connection.release()
using a pattern similar to below:
function doSomething(cb) {
pool.getConnection((ex, connection) => {
if (ex) {
cb(ex);
} else {
// Ensure that any call to cb releases the connection
// by wrapping it.
cb = (cb => {
return function () {
connection.release();
cb.apply(this, arguments);
};
})(cb);
connection.beginTransaction(ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table1 ("value") VALUES (\'my value\');', ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table2 ("value") VALUES (\'my other value\')', ex => {
if (ex) {
cb(ex);
} else {
connection.commit(ex => {
cb(ex);
});
}
});
}
});
}
});
}
});
}
I personally prefer to use Promise
s and the useAsync()
pattern. This pattern combined with async
/await
makes it a lot harder to accidentally forget to release()
the connection because it turns your lexical scoping into an automatic call to .release()
:
async function usePooledConnectionAsync(actionAsync) {
const connection = await new Promise((resolve, reject) => {
pool.getConnection((ex, connection) => {
if (ex) {
reject(ex);
} else {
resolve(connection);
}
});
});
try {
return await actionAsync(connection);
} finally {
connection.release();
}
}
async function doSomethingElse() {
// Usage example:
const result = await usePooledConnectionAsync(async connection => {
const rows = await new Promise((resolve, reject) => {
connection.query('SELECT 2*4 "value"', (ex, rows) => {
if (ex) {
reject(ex);
} else {
resolve(rows);
}
});
});
return rows[0].value;
});
console.log(`result=${result}`);
}
Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code
scGetruntotals.CommandTimeout = 180;
Note : the parameter value is in seconds.
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:
char* my_variable = "";
or, if you want to be explicit:
char my_variable = '\0';
The way posted above is only for a character. And, the second way:
#include <string.h>
char* my_variable = strdup("");
Don't forget to use free() with this one because strdup() use malloc inside.
Basic docker-compose.yml
with extra hosts:
version: '3'
services:
api:
build: .
ports:
- "5003:5003"
extra_hosts:
- "your-host.name.com:162.242.195.82" #host and ip
- "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
The content in the /etc/hosts
file in the created container:
162.242.195.82 your-host.name.com
50.31.209.229 your-host--1.name.com your-host--2.name.com
You can check the /etc/hosts
file with the following commands:
$ docker-compose -f path/to/file/docker-compose.yml run api bash # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts
Page
is a special case handler.
Generic Web handler (*.ashx
, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler
directive.
ASP.NET page handler (*.aspx
) is the default HTTP handler for all ASP.NET pages.
Among the built-in HTTP handlers there are also Web service handler (*.asmx
) and Trace handler (trace.axd
)
MSDN says:
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
The image below illustrates this:
As to your second question:
Does ashx handle more connections than aspx?
Don't think so (but for sure, at least not less than).
If you want to change the layou_gravity
of an existing view do this:
((FrameLayout.LayoutParams) view.getLayoutParams()).gravity = Gravity.BOTTOM;
Remember to use the right LayoutParams
based on the Layout type your view is in. Ex:
LinearLayout.LayoutParams
svn log -r {2009-09-17}:HEAD
where 2009-09-17
is the date you went on holiday. To see the changed files as well as the summary, add a -v
option:
svn log -r {2009-09-17}:HEAD -v
I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.
If you are getting back a sun.awt.image.ToolkitImage
, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage
.
So instead of your last line of code where you are casting you would just do:
BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
adds handlers to be called only when Deferred is resolved. You can add multiple callbacks to be called.
var url = 'http://jsonplaceholder.typicode.com/posts/1';
$.ajax(url).done(doneCallback);
function doneCallback(result) {
console.log('Result 1 ' + result);
}
You can also write above like this,
function ajaxCall() {
var url = 'http://jsonplaceholder.typicode.com/posts/1';
return $.ajax(url);
}
$.when(ajaxCall()).then(doneCallback, failCallback);
adds handlers to be called when Deferred is resolved, rejected or still in progress.
var url = 'http://jsonplaceholder.typicode.com/posts/1';
$.ajax(url).then(doneCallback, failCallback);
function doneCallback(result) {
console.log('Result ' + result);
}
function failCallback(result) {
console.log('Result ' + result);
}
Just to give an alternative solution, because it isn't mentioned.
It's perfectly fine to use the HTML attribute defer
here. So when loading the DOM, a regular <script>
will load when the DOM hits the script. But if we use defer
, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).
<script src="{% static "build/react.js" %}" defer></script>
NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None
. That usually means that an assignment or function call up above failed or returned an unexpected result.
Copy host keys from both bitbucket and github:
ssh root@deployserver 'echo "$(ssh-keyscan -t rsa,dsa bitbucket.org)" >> /root/.ssh/known_hosts'
ssh root@deployserver 'echo "$(ssh-keyscan -t rsa,dsa github.com)" >> /root/.ssh/known_hosts'
I have run outerMethod
,method_1
and method_2
with different propagation mode.
Below is the output for different propagation mode.
Outer Method
@Transactional
@Override
public void outerMethod() {
customerProfileDAO.method_1();
iWorkflowDetailDao.method_2();
}
Method_1
@Transactional(propagation=Propagation.MANDATORY)
public void method_1() {
Session session = null;
try {
session = getSession();
Temp entity = new Temp(0l, "XXX");
session.save(entity);
System.out.println("Method - 1 Id "+entity.getId());
} finally {
if (session != null && session.isOpen()) {
}
}
}
Method_2
@Transactional()
@Override
public void method_2() {
Session session = null;
try {
session = getSession();
Temp entity = new Temp(0l, "CCC");
session.save(entity);
int i = 1/0;
System.out.println("Method - 2 Id "+entity.getId());
} finally {
if (session != null && session.isOpen()) {
}
}
}
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
For me, the issue was that the referenced library was built using java 7. I solved this by rebuilding using the 1.6 JDK.
Since creating an JQuery object for every comparison is not efficient, just use:
$.expr[":"].blank = function(element) {
return element.value == "";
};
Then you can do:
$(":input:blank")
Unfortunately, no, the Spark platform as of version 2.3.1 does not provide any way to programmatically access the value of every property at run time. It provides several methods to access the values of properties that were explicitly set through a configuration file (like spark-defaults.conf
), set through the SparkConf
object when you created the session, or set through the command line when you submitted the job, but none of these methods will show the default value for a property that was not explicitly set. For completeness, the best options are:
http://<driver>:4040
, has an “Environment” tab with a property value table.SparkContext
keeps a hidden reference to its configuration in PySpark, and the configuration provides a getAll
method: spark.sparkContext._conf.getAll()
.SET
command that will return a table of property values: spark.sql("SET").toPandas()
. You can also use SET -v
to include a column with the property’s description.(These three methods all return the same data on my cluster.)
I have already included common-logging1.1.1.jar and ...
Are you sure you spelled the name of the JAR file exactly right? I think it should probably be commons-logging-1.1.1.jar
(note the extra -
in the name). Also check if the directory name is correct.
NoClassDefFoundError
always means that a class cannot be found, so most likely your class path is not correct.
Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:
update
MasterTbl
set
TotalX = Sum(DetailTbl.X),
TotalY = Sum(DetailTbl.Y),
TotalZ = Sum(DetailTbl.Z)
from
DetailTbl
where
DetailTbl.MasterID = MasterID
This is a very simple to create file in git bash at first write touch then file name with extension
for example
touch filename.extension
You need to have superuser privileges,
sudo npm install -g <package name>
FWIR, if authentication is only username & pw, add remote server ip address to known_hosts like ssh-keyscan -H 192.168.1.162 >> ~/.ssh/known_hosts
for ref https://www.techrepublic.com/article/how-to-easily-add-an-ssh-fingerprint-to-your-knownhosts-file-in-linux/
I used the below. The genre element will start where the DJ element ends,
<div>
<div style="width:50%; float:left">DJ</div>
<div>genre</div>
</div>
pardon the inline css.
If you are interested in only selecting one column this will work.
df[["item1"]].to_dict("records")
The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.
df["item1"].to_dict("records")
I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.
I would like to take credit for the command I wish to share but the truth is I obtained it for my own use from http://commandlinefu.com. It has the advantage that if you cd
to any directory within your own home folder that is it will change all files and folders to lower case recursively please use with caution. It is a brilliant command line fix and especially useful for those multitudes of albums you have stored on your drive.
find . -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;
You can specify a directory in place of the dot(.) after the find which denotes current directory or full path.
I hope this solution proves useful the one thing this command does not do is replace spaces with underscores - oh well another time perhaps.
Adding to the mix: the OI File Manager has a public api registered at openintents.org
http://www.openintents.org/filemanager
http://www.openintents.org/action/org-openintents-action-pick-file/
Another tip: if you want to have cleaner PHP code, you can create a VIEW in the database, e.g.
For example:
CREATE VIEW view_news AS
SELECT
news.id news_id,
user.id user_id,
user.name user_name,
[ OTHER FIELDS ]
FROM news, users
WHERE news.user_id = user.id;
In PHP:
$sql = "SELECT * FROM view_news";
It's Varargs :)
The varargs short for variable-length arguments is a feature that allows the method to accept variable number of arguments (zero or more). With varargs it has become simple to create methods that need to take a variable number of arguments. The feature of variable argument has been added in Java 5.
Syntax of varargs
A vararg is secified by three ellipsis (three dots) after the data type, its general form is
return_type method_name(data_type ... variableName){
}
Need for varargs
Prior to Java 5, in case there was a need of variable number of arguments, there were two ways to handle it
If the max number of arguments, a method can take was small and known, then overloaded versions of the method could be created. If the maximum number of arguments a method could take was large or/and unknown then the approach was to put those arguments in an array and pass them to a method which takes array as a parameter. These 2 approaches were error-prone - constructing an array of parameters every time and difficult to maintain - as the addition of new argument may result in writing a new overloaded method.
Advantages of varargs
Offers a much simpler option. Less code as no need to write overloaded methods.
Example of varargs
public class VarargsExample {
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
public static void main(String[] args) {
VarargsExample vObj = new VarargsExample();
// four args
vObj.displayData("var", "args", "are", "passed");
//three args
vObj.displayData("Three", "args", "passed");
// no-arg
vObj.displayData();
}
}
Output
Number of arguments passed 4
var
args
are
passed
Number of arguments passed 3
Three
args
passed
Number of arguments passed 0
It can be seen from the program that length is used here to find the number of arguments passed to the method. It is possible because varargs are implicitly passed as an array. Whatever arguments are passed as varargs are stored in an array which is referred by the name given to varargs. In this program array name is values. Also note that method is called with different number of argument, first call with four arguments, then three arguments and then with zero arguments. All these calls are handled by the same method which takes varargs.
Restriction with varargs
It is possible to have other parameters with varargs parameter in a method, however in that case, varargs parameter must be the last parameter declared by the method.
void displayValues(int a, int b, int … values) // OK
void displayValues(int a, int b, int … values, int c) // compiler error
Another restriction with varargs is that there must be only one varargs parameter.
void displayValues(int a, int b, int … values, int … moreValues) // Compiler error
Overloading varargs Methods
It is possible to overload a method that takes varargs parameter. Varargs method can be overloaded by -
Types of its vararg parameter can be different. By adding other parameters. Example of overloading varargs method
public class OverloadingVarargsExp {
// Method which has string vararg parameter
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
// Method which has int vararg parameter
public void displayData(int ... values){
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
// Method with int vararg and one more string parameter
public void displayData(String a, int ... values){
System.out.println(" a " + a);
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
public static void main(String[] args) {
OverloadingVarargsExp vObj = new OverloadingVarargsExp();
// four string args
vObj.displayData("var", "args", "are", "passed");
// two int args
vObj.displayData(10, 20);
// One String param and two int args
vObj.displayData("Test", 20, 30);
}
}
Output
Number of arguments passed 4
var
args
are
passed
Number of arguments passed 2
10
20
a Test
Number of arguments passed 2
20
30
Varargs and overloading ambiguity
In some cases call may be ambiguous while we have overloaded varargs method. Let's see an example
public class OverloadingVarargsExp {
// Method which has string vararg parameter
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
// Method which has int vararg parameter
public void displayData(int ... values){
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
public static void main(String[] args) {
OverloadingVarargsExp vObj = new OverloadingVarargsExp();
// four string args
vObj.displayData("var", "args", "are", "passed");
// two int args
vObj.displayData(10, 20);
// This call is ambiguous
vObj.displayData();
}
}
In this program when we make a call to displayData() method without any parameter it throws error, because compiler is not sure whether this method call is for displayData(String ... values)
or displayData(int ... values)
Same way if we have overloaded methods where one has the vararg
method of one type and another method has one parameter and vararg
parameter of the same type, then also we have the ambiguity -
As Exp -
displayData(int ... values)
and displayData(int a, int ... values)
These two overloaded methods will always have ambiguity.
Here is an example for shared memory :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *data;
int mode;
if (argc > 2) {
fprintf(stderr, "usage: shmdemo [data_to_write]\n");
exit(1);
}
/* make the key: */
if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */
{
perror("ftok");
exit(1);
}
/* create the segment: */
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
/* attach to the segment to get a pointer to it: */
data = shmat(shmid, NULL, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}
/* read or modify the segment, based on the command line: */
if (argc == 2) {
printf("writing to segment: \"%s\"\n", argv[1]);
strncpy(data, argv[1], SHM_SIZE);
} else
printf("segment contains: \"%s\"\n", data);
/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
Steps :
Use ftok to convert a pathname and a project identifier to a System V IPC key
Use shmget which allocates a shared memory segment
Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process
Do the operations on the memory area
Detach using shmdt
Try this :
string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)
In case of lazy loading, you just need to import MatDialogModule in lazy loaded module. Then this module will be able to render entry component with its own imported MatDialogModule:
@NgModule({
imports:[
MatDialogModule
],
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomeComponent,
DialogResultExampleDialog
],
entryComponents: [DialogResultExampleDialog]
If you are seting the ToolBar
as ActionBar
then just call:
getSupportActionBar().setElevation(YOUR_ELEVATION);
Note: This must be called after setSupportActionBar(toolbar);
Watch out! checking the radiobutton with setChecked()
is not changing the state inside the RadioGroup. For example this method from the radioGroup will return a wrong result: getCheckedRadioButtonId()
.
Check the radioGroup always with
mOption.check(R.id.option1);
you've been warned ;)
Check the API Docs
Methods addOption(data)
and setValue(value)
might be what you are looking for.
Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...
setValue(value, silent)
Resets the selected items to the given value.
If "silent" is truthy (ie:true
,1
), no change event will be fired on the original input.
addOption(data)
Adds an available option, or array of options. If it already exists, nothing will happen.
Note: this does not refresh the options list dropdown (userefreshOptions()
for that).
In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:
// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options); // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')
// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);
// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
“pom” packaging is nothing but the container, which contains other packages/modules like jar, war, and ear.
if you perform any operation on outer package/container like mvn clean compile install. then inner packages/modules also get clean compile install.
no need to perform a separate operation for each package/module.
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
I created a PHP class for this with a corresponding jQuery plugin. I've open-sourced it at https://github.com/peterjtracey/timezoneWidget - the PHP code is inspired by another stackoverflow answer, but I think much more elegant. The jQuery plugin gives a great interface for selecting a timezone.
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import express = require('express');
or (depending on your module loader)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
you shall see something like the following:
Angular CLI: 7.3.8
Node: 10.15.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, router
Angular version is in line 4 above
To add yet another potential solution, Helium by Clockworkmod has it's own version of ADB built in that kept being started. Exiting the Helium Desktop application resolves the issue.
Go to https://university.xamarin.com/resources/working-with-android-emulators . Scroll down to the "Installing Google Play Services" section. Step by step walk through there.
Directly plagarized from xamarin here so I don't get dinged for linking and not including solution. Posting this as I found the hit in stack before I found the solution that worked across the board on the xamarin page.
Now you can run applications that depend on Google Maps in the Xamarin Android Player.
FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:
Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"
In R1C1 you would use:
Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"
It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.
The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :
Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"
In ruby 1.9 one can use Array's choice method which returns random element from array
After seeing how you responded in the comments. It seems like it would be best to use push
as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
In the example you shared you are loading the existing file into book
and setting the writer.book
value to be book
. In the line writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
you are accessing each sheet in the workbook as ws
. The sheet title is then ws
so you are creating a dictionary of {sheet_titles: sheet}
key, value pairs. This dictionary is then set to writer.sheets. Essentially these steps are just loading the existing data from 'Masterfile.xlsx'
and populating your writer with them.
Now let's say you already have a file with x1
and x2
as sheets. You can use the example code to load the file and then could do something like this to add x3
and x4
.
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
writer = pd.ExcelWriter(path, engine='openpyxl')
df3.to_excel(writer, 'x3', index=False)
df4.to_excel(writer, 'x4', index=False)
writer.save()
That should do what you are looking for.
I would generally prefer something a bit simpler, like activate
/deactivate
sub-resource (linked by a Link
header with rel=service
).
POST /groups/api/v1/groups/{group id}/activate
or
POST /groups/api/v1/groups/{group id}/deactivate
For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}
I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.
var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);
THIS WILL ALSO work for END
It is also possible to include bitmaps. I think you also can use transformations on that.
It should be (new minus old)/mod avg of old and new With a special case when both val are zeros
It's probably putting tabs into your message. Print out message before you pass it to sendMail.
It seems that no one has mentioned the switch --stat
:
$ git diff --stat HEAD~5 HEAD
.../java/org/apache/calcite/rex/RexSimplify.java | 50 +++++++++++++++++-----
.../apache/calcite/sql/fun/SqlTrimFunction.java | 2 +-
.../apache/calcite/sql2rel/SqlToRelConverter.java | 16 +++++++
.../org/apache/calcite/util/SaffronProperties.java | 19 ++++----
.../org/apache/calcite/test/RexProgramTest.java | 24 +++++++++++
.../apache/calcite/test/SqlToRelConverterTest.java | 8 ++++
.../apache/calcite/test/SqlToRelConverterTest.xml | 15 +++++++
pom.xml | 2 +-
.../apache/calcite/adapter/spark/SparkRules.java | 7 +--
9 files changed, 117 insertions(+), 26 deletions(-)
There are also --numstat
$ git diff --numstat HEAD~5 HEAD
40 10 core/src/main/java/org/apache/calcite/rex/RexSimplify.java
1 1 core/src/main/java/org/apache/calcite/sql/fun/SqlTrimFunction.java
16 0 core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
8 11 core/src/main/java/org/apache/calcite/util/SaffronProperties.java
24 0 core/src/test/java/org/apache/calcite/test/RexProgramTest.java
8 0 core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
15 0 core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
1 1 pom.xml
4 3 spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java
and --shortstat
$ git diff --shortstat HEAD~5 HEAD
9 files changed, 117 insertions(+), 26 deletions(-)
This is indirect answer, on the folder structure itself, very related.
A few years ago I had same question, took a folder structure but had to do a lot directory moving later on, because the folder was meant for a different purpose than that I have read on internet, that is, what a particular folder does has different meanings for different people on some folders.
Now, having done multiple projects, in addition to explanation in all other answers, on the folder structure itself, I would strongly suggest to follow the structure of Node.js itself, which can be seen at: https://github.com/nodejs/node. It has great detail on all, say linters and others, what file and folder structure they have and where. Some folders have a README that explains what is in that folder.
Starting in above structure is good because some day a new requirement comes in and but you will have a scope to improve as it is already followed by Node.js itself which is maintained over many years now.
Hope this helps.
You're specifying the table name twice. The ALTER TABLE part names the table. Try: Alter table TableName alter column [Date] default getutcdate()
LatLngBounds
must be defined with points in (south-west, north-east) order. Your points are not in that order.
The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
The API will sort out the bounds.
Does the column allow null?
Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:
INSERT INTO `database`.`table` (`column`) VALUES (NULL);
What Access File extension or you using? The Jet OLEDB or the Ace OLEDB. If your Access DB is .mdb (aka Jet Oledb)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Oledb
namespace MembershipInformationSystem.Helpers
{
public class dbs
{
private String connectionString;
private String OleDBProvider = "Microsoft.JET.OLEDB.4.0"; \\if ACE Microsoft.ACE.OLEDB.12.0
private String OleDBDataSource = "C:\\yourdb.mdb";
private String OleDBPassword = "infosys";
private String PersistSecurityInfo = "False";
public dbs()
{
}
public dbs(String connectionString)
{
this.connectionString = connectionString;
}
public String konek()
{
connectionString = "Provider=" + OleDBProvider + ";Data Source=" + OleDBDataSource + ";JET OLEDB:Database Password=" + OleDBPassword + ";Persist Security Info=" + PersistSecurityInfo + "";
return connectionString;
}
}
}
The dword ptr
part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.
Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp
register and subtracting four with 0.
I'm assuming you are using m2eclipse as you mentioned it. However it is not clear whether you created your project under Eclipse or not so I'll try to cover all cases.
If you created a "Java" project under Eclipse (Ctrl+N > Java Project), then right-click the project in the Package Explorer view and go to Maven > Enable Dependency Management (depending on the initial project structure, you may have modify it to match the maven's one, for example by adding src/java
to the source folders on the build path).
If you created a "Maven Project" under Eclipse (Ctrl+N > Maven Project), then it should be already "Maven ready".
If you created a Maven project outside Eclipse (manually or with an archetype), then simply import it in Eclipse (right-click the Package Explorer view and select Import... > Maven Projects) and it will be "Maven ready".
Now, to add a dependency, either right-click the project and select Maven > Add Dependency) or edit the pom manually.
PS: avoid using the maven-eclipse-plugin if you are using m2eclipse. There is absolutely no need for it, it will be confusing, it will generate some mess. No, really, don't use it unless you really know what you are doing.
I think the NOBR tag might be overkill, and as you said, unreliable.
There are 2 options available depending on how you are displaying the text.
If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
Is this value intended? if (scroll <= 500) { ...
This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
(tomcat 8.0.28) Above method did not work for me. This is what worked:
Add this line to the end of your {CATALINA-HOME}/conf/logging.properties:
org.apache.jasper.level = FINEST
Shut down the server (if started).
Open console and run (in case of Windows):
%CATALINA_HOME%\bin\catalina.bat run
Enjoy logs, e.g. (again, for Windows):
{CATALINA-HOME}/logs/catalina.2015-12-28.log
I gave up on integrating this with Eclipse launch configuration so be aware that this works only from console, launching the server from Eclipse won't produce additional log messages.
I was getting lazyLoading exceptions on my entity because I was trying to access a lazy loaded collection that was in session.
What I would do was in a separate request, retrieve the entity from session and then try to access a collection in my jsp page which was problematic.
To alleviate this, I updated the same entity in my controller and passed it to my jsp, although I imagine when I re-saved in session that it will also be accessible though SessionScope
and not throw a LazyLoadingException
, a modification of example 2:
The following has worked for me:
// scenario 2 MY WAY
// tran starts
e = new MyEntity();
e = em.merge(e); // re-assign to the same entity "e"
//access e from jsp and it will work dandy!!
We eventually found the answer to this.
Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...
Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."
... fixed the problem. Hope this helps someone!
$ sudo su
$ /opt/google-appengine-sdk/bin/gcloud components update
$ su <yourusername>
I prefer TextMate on OS X. But Netbeans (multi-platform) is coming along quite nicely. Plus it comes with its IDE fully functional debugger.
What you are looking for is 'type casting'. typecasting (putting the type you know you want in brackets) tells the compiler you know what you are doing and are cool with it. The old way that is inherited from C is as follows.
float var_a = 9.99;
int var_b = (int)var_a;
If you had only tried to write
int var_b = var_a;
You would have got a warning that you can't implicitly (automatically) convert a float
to an int
, as you lose the decimal.
This is referred to as the old way as C++ offers a superior alternative, 'static cast'; this provides a much safer way of converting from one type to another. The equivalent method would be (and the way you should do it)
float var_x = 9.99;
int var_y = static_cast<int>(var_x);
This method may look a bit more long winded, but it provides much better handling for situations such as accidentally requesting a 'static cast' on a type that cannot be converted. For more information on the why you should be using static cast, see this question.
Count all the DISTINCT program names by program type and push number
SELECT COUNT(DISTINCT program_name) AS Count,
program_type AS [Type]
FROM cm_production
WHERE push_number=@push_number
GROUP BY program_type
DISTINCT COUNT(*)
will return a row for each unique count. What you want is COUNT(DISTINCT <expression>)
: evaluates expression for each row in a group and returns the number of unique, non-null values.
Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!
The difference is that one (Forms timeout) has to do with authenticating the user and the other (Session timeout) has to do with how long cached data is stored on the server. So they are very independent things, so one does not take precedence over the other.
Python 3.x makes a clear distinction between the types:
str
= '...'
literals = a sequence of Unicode characters (Latin-1, UCS-2 or UCS-4, depending on the widest character in the string)bytes
= b'...'
literals = a sequence of octets (integers between 0 and 255)If you're familiar with:
str
as String
and bytes
as byte[]
;str
as NVARCHAR
and bytes
as BINARY
or BLOB
;str
as REG_SZ
and bytes
as REG_BINARY
.If you're familiar with C(++), then forget everything you've learned about char
and strings, because a character is not a byte. That idea is long obsolete.
You use str
when you want to represent text.
print('???? ????')
You use bytes
when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str
to a bytes
object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes
into a str
.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...'
notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode
= u'...'
literals = sequence of Unicode characters = 3.x str
str
= '...'
literals = sequences of confounded bytes/characters
struct.pack
output.In order to ease the 2.x-to-3.x transition, the b'...'
literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes
in 3.x) from text strings (which should be str
in 3.x). The b
prefix does nothing in 2.x, but tells the 2to3
script not to convert it to a Unicode string in 3.x.
So yes, b'...'
literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
The r
prefix creates a raw string (e.g., r'\t'
is a backslash + t
instead of a tab), and triple quotes '''...'''
or """..."""
allow multi-line string literals.
in JetPack it work for me
NavigationUI.setupWithNavController(vb.toolbar, nav)
vb.toolbar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.icon_home, null)
You can use native JS so you don't have to rely on external libraries.
(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
});
You can also capture errors if any:
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
})
.catch(err => {
console.error('An error ocurred', err);
});
By default it uses GET
and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference
So yes, you should prefer the shadowPath property for performance, but also: From the header file of CALayer.shadowPath
Specifying the path explicitly using this property will usually * improve rendering performance, as will sharing the same path * reference across multiple layers
A lesser known trick is sharing the same reference across multiple layers. Of course they have to use the same shape, but this is common with table/collection view cells.
I don't know why it gets faster if you share instances, i'm guessing it caches the rendering of the shadow and can reuse it for other instances in the view. I wonder if this is even faster with
Both of these should work:
df.isnull().sum()
df.isna().sum()
DataFrame methods isna()
or isnull()
are completely identical.
Note: Empty strings ''
is considered as False (not considered NA)
You can do it using the Github API
This is the Python example:
import requests
if __name__ == '__main__':
base_api_url = 'https://api.github.com/repos'
git_repository_url = 'https://github.com/garysieling/wikipedia-categorization.git'
github_username, repository_name = git_repository_url[:-4].split('/')[-2:] # garysieling and wikipedia-categorization
res = requests.get(f'{base_api_url}/{github_username}/{repository_name}')
repository_size = res.json().get('size')
print(repository_size)
You can use
nditer
Here I calculated no. of positive and negative coefficients in a logistic regression:
b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
if i>0:
pos_coef=pos_coef+1
else:
neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))
Output:
no. of positive coefficients is : 85035
no. of negative coefficients is : 36199
Depending on the version you are running. It is basically the same just go to
File -> Invalidate caches, then restart Intellij
or
File -> Invalidate caches / Restart
The main difference is that in older versions you had to manually restart as cache files are not removed until you restart. The newer versions will ask if you also want to restart.
As seen here on this official Jetbrains help page
You can also try delete caches manually in the system
folder for your installed version. The location of this folder depends on your OS and version installed.
Windows Vista, 7, 8, 10
<SYSTEM DRIVE>\Users\<USER ACCOUNT NAME>\.<PRODUCT><VERSION>
Linux/Unix
~/.<PRODUCT><VERSION>
Mac OS
~/Library/Caches/<PRODUCT><VERSION>
Read this for more details on cache locations.
Another useful way is with Concat.
More information in the official documentation.
List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);
The output will be.
One
Two
Three
Four
Five
And there is another similar answer.
I realize this has been answered to death, but here's a modern ES6 version I wrote that follows airbnb-base eslint standards.
const getIpAddressFromRequest = (request) => {
let ipAddr = request.connection.remoteAddress;
if (request.headers && request.headers['x-forwarded-for']) {
[ipAddr] = request.headers['x-forwarded-for'].split(',');
}
return ipAddr;
};
The X-Forwarded-For header may contain a comma-separated list of proxy IPs. The order is client,proxy1,proxy2,...,proxyN. In the real world, people implement proxies that may supply whatever they want in this header. If you are behind a load balancer or something, you can at least trust the first IP in the list is at least whatever proxy some request came through.
Here's another option, which is less efficient but more concise. It's how I generally handle this sort of problem:
Get-ChildItem -Recurse .\targetdir -Exclude *.log |
Where-Object { $_.FullName -notmatch '\\excludedir($|\\)' }
The \\excludedir($|\\)'
expression allows you to exclude the directory and its contents at the same time.
Update: Please check the excellent answer from msorens for an edge case flaw with this approach, and a much more fleshed out solution overall.
There's not much of one in everyday work.
However, according to the documentation for both functions (accessed by putting a ?
before the function name and hitting enter), require
is used inside functions, as it outputs a warning and continues if the package is not found, whereas library
will throw an error.
Eileen: No, it is not var nameVal = form.inputname.val();
. It should be either...
in jQuery:
// you can use IDs (easier)
var nameVal = $(form).find('#id').val();
// or use the [name=Fieldname] to search for the field
var nameVal = $(form).find('[name=Fieldname]').val();
Or in JavaScript:
var nameVal = this.form.FieldName.value;
Or a combination:
var nameVal = $(this.form.FieldName).val();
With jQuery, you could even loop through all of the inputs in the form:
$(form).find('input, select, textarea').each(function(){
var name = this.name;
// OR
var name = $(this).attr('name');
var value = this.value;
// OR
var value = $(this).val();
....
});
>>> import os
>>> os.path.join('/home/user/tmp', 'subfolder')
'/home/user/tmp/subfolder'
>>> os.path.normpath('/home/user/tmp/../test/..')
'/home/user'
>>> os.path.relpath('/home/user/tmp', '/home/user')
'tmp'
>>> os.path.isabs('/home/user/tmp')
True
>>> os.path.isabs('/tmp')
True
>>> os.path.isabs('tmp')
False
>>> os.path.isabs('./../tmp')
False
>>> os.path.realpath('/home/user/tmp/../test/..') # follows symbolic links
'/home/user'
A detailed description is found in the docs. These are linux paths. Windows should work analogous.
You can also add this from the Nuget Package Manager Console, something like:
Install-Package Microsoft.AspNet.Mvc -Version 4.0.20710.0 -ProjectName XXXXX
Microsoft.AspNet.Mvc has dependencies on:
...which seems like no biggie to me. In our case, this is a class library that exists solely to provide support for our Mvc apps. So, we figure it's a benign dependency at worst.
I definitely prefer this to pointing to an assembly on the file system or in the GAC, since updating the package in the future will likely be a lot less painful than experiences I've had with the GAC and file system assembly references in the past.
I know this is an old question but why can't you do it like:
db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);
I am not sure how to do this using query expressions.
I'd go for jpeg
. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick
Hope this helps
For simplicity and well structured sake, use SpringMVC. It's just so simple.
@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
return carService.getAllCars();
}
Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
you can use something like this....div
container
<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >
<table width="60%" border="0" cellspacing="2" cellpadding="2" >
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006" >
<td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
<td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
</tr>
</table>
</form>
</div>
Also, we can use it following ways
To get only first
$cat_details = DB::table('an_category')->where('slug', 'people')->first();
To get by limit and offset
$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();
One workaround is to use Postman with same request url, headers and payload.
It will give response for sure.
Try this:
currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value)
with this function:
Function ConvertToLongInteger(ByVal stValue As String) As Long
On Error GoTo ConversionFailureHandler
ConvertToLongInteger = CLng(stValue) 'TRY to convert to an Integer value
Exit Function 'If we reach this point, then we succeeded so exit
ConversionFailureHandler:
'IF we've reached this point, then we did not succeed in conversion
'If the error is type-mismatch, clear the error and return numeric 0 from the function
'Otherwise, disable the error handler, and re-run the code to allow the system to
'display the error
If Err.Number = 13 Then 'error # 13 is Type mismatch
Err.Clear
ConvertToLongInteger = 0
Exit Function
Else
On Error GoTo 0
Resume
End If
End Function
I chose Long (Integer) instead of simply Integer because the min/max size of an Integer in VBA is crummy (min: -32768, max:+32767). It's common to have an integer outside of that range in spreadsheet operations.
The above code can be modified to handle conversion from string to-Integers, to-Currency (using CCur() ), to-Decimal (using CDec() ), to-Double (using CDbl() ), etc. Just replace the conversion function itself (CLng). Change the function return type, and rename all occurrences of the function variable to make everything consistent.
let elements = [1, 2, 3, 4, 5, 5]
elements.contains(5) // true
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
let results = elements.filter { element in element == 5 }
results.count // 2
Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.
In the version where you use argparse, you need to have this line in the main body.
args = parser.parse_args(args)
Normally when you are using argparse just in a script you just write
args = parser.parse_args()
and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.
Here is an example
import argparse
import sys
def x(x_center, y_center):
print "X center:", x_center
print "Y center:", y_center
def main(args):
parser = argparse.ArgumentParser(description="Do something.")
parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
args = parser.parse_args(args)
x(args.xcenter, args.ycenter)
if __name__ == '__main__':
main(sys.argv[1:])
Assuming you named this mytest.py To run it you can either do any of these from the command line
python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py
which returns respectively
X center: 8.0
Y center: 4
or
X center: 8.0
Y center: 2.0
or
X center: 2
Y center: 4
Or if you want to run from another python script you can do
import mytest
mytest.main(["-x","7","-y","6"])
which returns
X center: 7.0
Y center: 6.0
Seems like in Java 8 some methods are added to Long to treat old good [signed] long as unsigned. Seems like a workaround, but may help sometimes.
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
@JulienD Best way is to break above process into two steps.
Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.
Create another list :
ArrayList<String> listWithQuotes = new ArrayList<String>();
for(String element : rawList){
listWithQuotes.add("'"+element+"'");
}
Step 2 : Make 'listWithQuotes' comma separated.
String finalString = StringUtils.join(listWithQuotes.iterator(),",");
'finalString' will be string parameters with each element as single quoted and comma separated.
Swift 5:
If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.
extension UILabel {
func getSize(constrainedWidth: CGFloat) -> CGSize {
return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
}
}
You can use it like this:
let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)
Works for me
You should explore SQL Server\Memory Manager performance counters.
Not sure how but the below change sorted my issue:
i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .
Hope so it helps
<style>_x000D_
.hideFullColumn tr > .hidecol_x000D_
{_x000D_
display:none;_x000D_
}_x000D_
</style>
_x000D_
use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.
Create Custom Alert Dialog
cumstomDialog.xml
<ImageView
android:id="@+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_margin="5dp"
app:srcCompat="@drawable/error" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="@font/muli_bold"
android:text="Title"
android:layout_marginTop="5dp"
android:textColor="@android:color/black"
android:textSize="15sp" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:fontFamily="@font/muli_regular"
android:text="Message"
android:textColor="@android:color/black"
android:textSize="12dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/cancelBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_margin="5dp"
android:background="@drawable/bground_radius_button_white"
android:text="No"
android:textColor="@color/black" />
<Button
android:id="@+id/acceptBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_margin="5dp"
android:background="@drawable/bground_radius_button"
android:text="Yes"
android:textColor="@color/white" />
</LinearLayout>
Show your custom dialog on your activity:
public void showDialog(String title, String des, int icon) {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button cancelBTN = dialog.findViewById(R.id.cancelBTN);
Button acceptBTN = dialog.findViewById(R.id.acceptBtn);
TextView tvTitle = dialog.findViewById(R.id.title);
TextView tvDescription = dialog.findViewById(R.id.description);
ImageView ivIcon = dialog.findViewById(R.id.icon);
tvTitle.setText(title);
tvDescription.setText(des);
ivIcon.setImageResource(icon);
cancelBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
acceptBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
dialog.show();
}
Call like this:
showDialog("Title", "Message", R.drawable.warning);
In Python:
# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M)
or more rigorous:
# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
One way is by using document.getElementByID
, as below -
<body>
<h1>Adding 'a' and 'b'</h1>
a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br>
<button onclick="add(document.getElementById('a').value,document.getElementById('b').value)">Add</button>
<script>
function add(a, b) {
var sum = parseInt(a, 10) + parseInt(b, 10);
alert(sum);
}
</script>
</body>
_x000D_
https://www.npmjs.com/package/crypto-extra has a method for it :)
var value = crypto.random(/* desired length */)
Without using regex (though I would only do this if the search string is user input):
var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!'
<content>(?:[^\n]*(\n+))+</content>
You can use the Axes.set_yscale
method. That allows you to change the scale after the Axes
object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
ax.set_yscale('log')
You can use 'linear'
to switch back to a linear scale. Here's what your code would look like:
import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
line, = ax.plot(a, color='blue', lw=2)
ax.set_yscale('log')
pylab.show()
Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples
Also, you should really really really change your List
into a strongly typed list (List<T>
), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.
Another alternate approach to Diego's is to use a library:
https://github.com/airbnb/DeepLinkDispatch
You can easily declare the URIs you'd like to handle and the parameters you'd like to extract through annotations on the Activity, like:
@DeepLink("path/to/what/i/want")
public class SomeActivity extends Activity {
...
}
As a plus, the query parameters will also be passed along to the Activity as well.
I found a fix that while it's not actually using ajax it does allow you to use a javascript call to request the download and then get a callback when the download actually starts. I found this helpful if the link runs a server side script that takes a little bit to compose the file before sending it. so you can alert them that it's processing, and then when it does finally send the file remove that processing notification. which is why I wanted to try to load the file via ajax to begin with so that I could have an event happen when the file is requested and another when it actually starts downloading.
the js on the front page
function expdone()
{
document.getElementById('exportdiv').style.display='none';
}
function expgo()
{
document.getElementById('exportdiv').style.display='block';
document.getElementById('exportif').src='test2.php?arguments=data';
}
the iframe
<div id="exportdiv" style="display:none;">
<img src="loader.gif"><br><h1>Generating Report</h1>
<iframe id="exportif" src="" style="width: 1px;height: 1px; border:0px;"></iframe>
</div>
then the other file:
<!DOCTYPE html>
<html>
<head>
<script>
function expdone()
{
window.parent.expdone();
}
</script>
</head>
<body>
<iframe id="exportif" src="<?php echo "http://10.192.37.211/npdtracker/exportthismonth.php?arguments=".$_GET["arguments"]; ?>"></iframe>
<script>document.getElementById('exportif').onload= expdone;</script>
</body></html>
I think there's a way to read get data using js so then no php would be needed. but I don't know it off hand and the server I'm using supports php so this works for me. thought I'd share it in case it helps anyone.
Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this
SELECT IF(
count(*) > 15,
'good',
IF(
count(*) > 10,
'average',
'poor'
)
) as data_count
FROM companies
Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
An easy way to overcome this problem is to use 64 bit type
list = numpy.array(list, dtype=numpy.float64)
This one here:
s = raw_input()
a=len(s)
for i in xrange(0, a):
for j in xrange(0, a):
if j >= i:
if len(s[i:j+1]) > 0:
sub_strings.append(s[i:j+1])
seems to be very inefficient and expensive for large strings.
Better do
for i in xrange(0, a):
for j in xrange(i, a): # ensures that j >= i, no test required
part = buffer(s, i, j+1-i) # don't duplicate data
if len(part) > 0:
sub_Strings.append(part)
A buffer object keeps a reference to the original string and start and length attributes. This way, no unnecessary duplication of data occurs.
A string of length l
has l*l/2
sub strings of average length l/2
, so the memory consumption would roughly be l*l*l/4
. With a buffer, it is much smaller.
Note that buffer()
only exists in 2.x. 3.x has memoryview()
, which is utilized slightly different.
Even better would be to compute the indexes and cut out the substring on demand.
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=myproxy
-Dhttp.proxyPort=8080
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1
These settings require IDE restart (sometimes with -clean -refresh
command line options).
https://bugs.eclipse.org/bugs/show_bug.cgi?id=281472
Java8, Eclipse Neon3, slow proxy server:
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
-Dhttp.proxyHost=<proxy>
-Dhttp.proxyPort=8080
-Dhttps.proxyHost=<proxy>
-Dhttps.proxyPort=8080
-DsocksProxyHost=
-DsocksProxyPort=
-Dhttp.proxyUser=<user>
-Dhttp.proxyPassword=<pass>
-Dhttp.nonProxyHosts=localhost|127.0.0.1
-Dorg.eclipse.equinox.p2.transport.ecf.retry=5
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.connectTimeout=15000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts=20
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.browse.connectTimeout=3000
-Dorg.eclipse.ecf.provider.filetransfer.browse.readTimeout=1000
var findObjectByLabel = function(obj, label)
{
var foundLabel=null;
if(obj.label === label)
{
return obj;
}
for(var i in obj)
{
if(Array.isArray(obj[i])==true)
{
for(var j=0;j<obj[i].length;j++)
{
foundLabel = findObjectByLabel(obj[i], label);
}
}
else if(typeof(obj[i]) == 'object')
{
if(obj.hasOwnProperty(i))
{
foundLabel = findObjectByLabel(obj[i], label);
}
}
if(foundLabel)
{
return foundLabel;
}
}
return null;
};
var x = findObjectByLabel(cars, "Sedan");
alert(JSON.stringify(x));
I think a lot of folks are looking for a footer on the bottom that scrolls instead of being fixed, called a sticky footer. Fixed footers will cover body content when the height is too short. You have to set the html, body, and page container to a height of 100%, set your footer to absolute position bottom. Your page content container needs a relative position for this to work. Your footer has a negative margin equal to height of footer minus bottom margin of page content. See the example page I posted.
Example with notes: http://markbokil.com/code/bottomfooter/
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
You can read up on linux, which is pretty close to what Mac OS X is. Or you can read up on BSD Unix, which is a little closer. For the most part, the differences between Linux and BSD don't amount to much.
/etc/profile
are system environment variables.
~/.profile
are user-specific environment variables.
"where should I set my JAVA_HOME variable?"
/etc/profile
? Generally, I prefer not to mess with system-wide settings even though I'm the only user. I prefer to edit my local settings.
For Microsoft IIS servers, you can enable this header via your web.config
file:
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Content-Type-Options"/>
<add name="X-Content-Type-Options" value="nosniff"/>
</customHeaders>
</httpProtocol>
</system.webServer>
And you are done.
I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null
To open a URL with the default browser, you can execute:
rundll32 url.dll,FileProtocolHandler https://www.google.com
I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
SiteLink= (TextView) findViewById(R.id.textViewSite);
SiteLink.setText(Html.fromHtml(value));
SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
Run the following commands in CMD
choco install powershell
choco upgrade powershell
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
While creating a fragment transaction, make sure to add the following code.
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
Also make sure, to commit the transaction after adding it to backstack
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
You can accomplish this two ways, both of which need to be done through editing your template files.
The first one is just to add an html link to your navigation where ever you want it to show up.
The second (and my guess, the one you're looking for) is to create a new page template, which isn't too difficult if you have the ability to create a new .php file in your theme/template directory. Something like the below code should do:
<?php /*
Template Name: Page Redirect
*/
header('Location: http://www.nameofnewsite.com');
exit();
?>
Where the template name is whatever you want to set it too and the url in the header function is the new url you want to direct a user to. After you modify the above code to meet your needs, save it in a php file in your active theme folder to the template name. So, if you leave the name of your template "Page Redirect" name the php file page-redirect.php.
After that's been saved, log into your WordPress backend, and create a new page. You can add a title and content to the body if you'd like, but the important thing to note is that on the right hand side, there should be a drop down option for you to choose which page template to use, with default showing first. In that drop down list, there should be the name of the new template file to use. Select the new template, publish the page, and you should be golden.
Also, you can do this dynamically as well by using the Custom Fields section below the body editor. If you're interested, let me know and I can paste the code for that guy in a new response.
-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
The two parameters are X axis, and Y axis, -1 will be a mirror, but you can scale to any size you like to suit your needs. Upside down and backwards would be (-1, -1)
.
If you're interested in the best option available for cross browser support back in 2011, see my older answer.
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
Make sure your controller inherits from Controller
class.
It might even be crazier that stuff would work locally even without that.
You could use border-top-left-radius
and border-top-right-radius
properties to round the corners on the box according to the box's height (and added borders).
Then add a border to top/right/left sides of the box to achieve the effect.
Here you go:
.half-circle {
width: 200px;
height: 100px; /* as the half of the width */
background-color: gold;
border-top-left-radius: 110px; /* 100px of height + 10px of border */
border-top-right-radius: 110px; /* 100px of height + 10px of border */
border: 10px solid gray;
border-bottom: 0;
}
Alternatively, you could add box-sizing: border-box
to the box in order to calculate the width/height of the box including borders and padding.
.half-circle {
width: 200px;
height: 100px; /* as the half of the width */
border-top-left-radius: 100px;
border-top-right-radius: 100px;
border: 10px solid gray;
border-bottom: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
UPDATED DEMO. (Demo without background color)
this way i follow and its work for me fine, may it will works for you,
<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
height: iframeHeight * 0.75 + 'px'
}" style="width:100%"></iframe>
here trustThisUrl is just filter,
angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
return function (val) {
return $sce.trustAsResourceUrl(val);
};
}]);
Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?" Yes, it is.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])
plt.show()
You'll get:
Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:
this.print({bUI: false, bSilent: true, bShrinkToFit: true});
This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.
Auto-printing PDF!
Connect to the server as "system" using SID. Execute this query:
select value from v$parameter where name like '%service_name%';
It worked for me.
git branch copyOfMyBranch MyBranch
This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).
Add the below declarations to your class:
public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
After:
var client = new HttpClient();
And:
ServicePointManager.SecurityProtocol = Tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 /*| SecurityProtocolType.Tls */| Tls12;
Happy? :)
@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class TestPerf {
public static final int LOOP_MAX_COUNT = 1000;
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("success", true);
map.put("number", 1000);
map.put("longer", 1000L);
map.put("doubler", 1000D);
map.put("data1", "testString");
map.put("data2", "testString");
map.put("data3", "testString");
map.put("data4", "testString");
map.put("data5", "testString");
map.put("data6", "testString");
map.put("data7", "testString");
map.put("data8", "testString");
map.put("data9", "testString");
map.put("data10", "testString");
runBeanUtilsPopulate(map);
runJacksonMapper(map);
}
private static void runBeanUtilsPopulate(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
try {
TestClass bean = new TestClass();
BeanUtils.populate(bean, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
long t2 = System.currentTimeMillis();
System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));
}
private static void runJacksonMapper(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
ObjectMapper mapper = new ObjectMapper();
TestClass testClass = mapper.convertValue(map, TestClass.class);
}
long t2 = System.currentTimeMillis();
System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class TestClass {
private Boolean success;
private Integer number;
private Long longer;
private Double doubler;
private String data1;
private String data2;
private String data3;
private String data4;
private String data5;
private String data6;
private String data7;
private String data8;
private String data9;
private String data10;
}
}
$(document).ready(function() {
//calculate the window height & add css properties for height 100%
wh = $( window ).height();
ww = $( window ).width();
$(".targeted-div").css({"height": wh, "width": ww});
});
here is how i was able to solve it
docker run --rm -ti -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_SESSION_TOKEN -e AWS_SECURITY_TOKEN amazon/aws-cli s3 ls
one more example:
export VAR1=value1
export VAR2=value2
$ docker run --env VAR1 --env VAR2 ubuntu env | grep VAR
VAR1=value1
VAR2=value2
docker start `docker ps -a | awk '{print $1}'`
This will start up all the containers that are in the 'Exited' state
Create Sequence.
CREATE SEQUENCE user_role_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 3
CACHE 1;
ALTER TABLE user_role_id_seq
OWNER TO postgres;
and alter table
ALTER TABLE user_roles ALTER COLUMN user_role_id SET DEFAULT nextval('user_role_id_seq'::regclass);
I like @ninjagecko's answer the most.
This would also work:
for Python 2.x
isinstance(n, (int, long, float))
Python 3.x doesn't have long
isinstance(n, (int, float))
there is also type complex for complex numbers
Looking at the code I found the following differences between jquery.js and jquery.slim.js:
In the jquery.slim.js, the following features are removed:
The cherry-pick command can read the list of commits from the standard input.
The following command cherry-picks commits authored by the user John that exist in the "develop" branch but not in the "release" branch, and does so in the chronological order.
git log develop --not release --format=%H --reverse --author John | git cherry-pick --stdin
some refs =>
...
<head>
// CSRF for all ajax call
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
...
...
<script>
// CSRF for all ajax call
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...
Yes you only need $()
when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.
$(this)[0] === this
Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.
$("#myDiv")[0] === document.getElementById("myDiv");
And so on...
This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800
from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()
there are many ways can do this:
add X-UA-Compatible tag to head http response header
using IE tools F12
change windows Registry
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) +
geom_point()
ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
Taking some of the things you have described:
"So you could be sure that some fields in a class are defined for every implementation of this interface."
"If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor"
...these requirements are exactly what abstract classes are for.
byte[] byteArray = rs.getBytes("columnname");
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
also just try adding double slashes like this works for me only
set dir="C:\\1. Some Folder\\Some Other Folder\\Just Because"
@echo on MKDIR %dir%
OMG after posting they removed the second \ in my post so if you open my comment and it shows three you should read them as two......
Latest and greatest way to do this:
Node supports file and buffer operations with the base64
encoding:
const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
Or using the new promises API:
const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
Since git 1.7.9 version you can also use git commit --amend --no-edit
to get your result.
Note that this will not include metadata from the other commit such as the timestamp which may or may not be important to you.
char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character
& char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )
But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.
The solution for me was to set the AppPool from using the AppPoolIdentity to the NetworkService identity.
Image.paste
does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.
Pillow 2.0 contains an alpha_composite
function that does this.
background = Image.open("test1.png")
foreground = Image.open("test2.png")
Image.alpha_composite(background, foreground).save("test3.png")
EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA')
if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).
simply use the form_validation class of codeigniter:
strip_image_tags($str).
$this->load->library('form_validation');
$this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');
If you use:
ps uH p <PID_OF_U_PROCESS> | wc -l
You have to subtract 1 to the result, as one of the lines "wc" is counting is the headers of the "ps" command.
Use this code to pass arraylist<customobj>
to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);
You could use
options(warn=-1)
But note that turning off warning messages globally might not be a good idea.
To turn warnings back on, use
options(warn=0)
(or whatever your default is for warn
, see this answer)
The simple answer:
doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice
ADD 1 is probably faster than INC here
MOV 2 and DIV is very expensive; just shift right
64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code
If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.
if(view instanceof B)
This will return true if view is an instance of B or the subclass A (or any subclass of B for that matter).
Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this
echo "insert text here" > myfile.txt
That will put the text 'insert text here' into a file myfile.txt. To verify that this worked use the command 'cat'.
cat myfile.txt
If you want to append to a file use this
echo "append this text" >> myfile.txt
very simple
$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
Selecting text in an element (akin to highlighting with your mouse)
:)
Using the accepted answer on that post, you can call the function like this:
$(function() {
$('#textareaId').click(function() {
SelectText('#textareaId');
});
});
You can use resolve
:
angular.module('app',[])
.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl : 'app/views/login.html',
controller : 'YourController',
controllerAs : 'Your',
resolve: {
factory : checkLoginRedirect
}
})
}
And, the function of the resolve:
function checkLoginRedirect($location){
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
if ($location.path() == "/"){
$location.path('dash');
}
return true;
}else{
// No user is signed in.
$location.path('/');
return false;
}
}
Firebase also has a method that helps you install an observer, I advise installing it inside a .run
:
.run(function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User is signed in.');
} else {
console.log('No user is signed in.');
}
});
}
Use CDATA in the below way for formatting your text
<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
<b>
<![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
]]>
</b>
</string>
Just add any tag you want before the <![CDATA[
and you will get your proper output.
You have to start the gallery intent for a result.
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
Then in onActivityForResult
, call intent.getData()
to get the Uri of the Image. Then you need to get the Image from the ContentProvider.
I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:
File Source control > Advanced > Exclude web.config from source control
... and boom; your file is permanently excluded from source control.
try kill -9 {processID}
To find the process ID you can use ps -ef | grep gedit
This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.
The example below will look like this. You can modify it for any keyboard layout.
The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.
I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity
and "Hello World!" layout as it is.
Add the following two files to your app's res/layout
folder:
keyboard_view.xml
This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView
.
<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/keyboard_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:keyPreviewLayout="@layout/key_preview"
android:layout_alignParentBottom="true">
</android.inputmethodservice.KeyboardView>
key_preview.xml
The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/white"
android:textColor="@android:color/black"
android:textSize="30sp">
</TextView>
Create an xml
folder in your res
folder. (Right click res
and choose New > Directory.)
Then add the following two xml files to it. (Right click the xml
folder and choose New > XML resource file.)
number_pad.xml
This is where it starts to get more interesting. This Keyboard
defines the layout of the keys.
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="20%p"
android:horizontalGap="5dp"
android:verticalGap="5dp"
android:keyHeight="60dp">
<Row>
<Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
<Key android:codes="50" android:keyLabel="2"/>
<Key android:codes="51" android:keyLabel="3"/>
<Key android:codes="52" android:keyLabel="4"/>
<Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
<Key android:codes="55" android:keyLabel="7"/>
<Key android:codes="56" android:keyLabel="8"/>
<Key android:codes="57" android:keyLabel="9"/>
<Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="-5"
android:keyLabel="DELETE"
android:keyWidth="40%p"
android:keyEdgeFlags="left"
android:isRepeatable="true"/>
<Key android:codes="10"
android:keyLabel="ENTER"
android:keyWidth="60%p"
android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
Here are some things to note:
keyWidth
: This is the default width of each key. The 20%p
means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.keyHeight
: It is hard coded here, but you could use something like @dimen/key_height
to set it dynamically for different screen sizes.Gap
: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px
there is still a small gap.codes
: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText
if you want to input a longer Unicode string. keyLabel
: This is the text that is displayed on the key.keyEdgeFlags
: This indicates which edge the key should be aligned to.isRepeatable
: If you hold down the key it will keep repeating the input.method.xml
This file tells the system the input method subtypes that are available. I am just including a minimal version here.
<?xml version="1.0" encoding="utf-8"?>
<input-method
xmlns:android="http://schemas.android.com/apk/res/android">
<subtype
android:imeSubtypeMode="keyboard"/>
</input-method>
Create a new Java file. Let's call it MyInputMethodService
. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText
, for example).
public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
@Override
public View onCreateInputView() {
// get the KeyboardView and add our Keyboard layout to it
KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
return keyboardView;
}
@Override
public void onKey(int primaryCode, int[] keyCodes) {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
CharSequence selectedText = ic.getSelectedText(0);
if (TextUtils.isEmpty(selectedText)) {
// no selection, so delete previous character
ic.deleteSurroundingText(1, 0);
} else {
// delete the selection
ic.commitText("", 1);
}
break;
default:
char code = (char) primaryCode;
ic.commitText(String.valueOf(code), 1);
}
}
@Override
public void onPress(int primaryCode) { }
@Override
public void onRelease(int primaryCode) { }
@Override
public void onText(CharSequence text) { }
@Override
public void swipeLeft() { }
@Override
public void swipeRight() { }
@Override
public void swipeDown() { }
@Override
public void swipeUp() { }
}
Notes:
OnKeyboardActionListener
listens for keyboard input. It is also requires all those empty methods in this example.InputConnection
is what is used to send input to another view like an EditText
.I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service
section to your AndroidManifest.xml file. Put it in the application
section after activity
.
<manifest ...>
<application ... >
<activity ... >
...
</activity>
<service
android:name=".MyInputMethodService"
android:label="Keyboard Display Name"
android:permission="android.permission.BIND_INPUT_METHOD">
<intent-filter>
<action android:name="android.view.InputMethod"/>
</intent-filter>
<meta-data
android:name="android.view.im"
android:resource="@xml/method"/>
</service>
</application>
</manifest>
That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.
Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:
Here is a summary:
Now you should be able to use your keyboard anywhere that you can type in Android.
The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.
Don't like how the standard KeyboardView
looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.
The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:
ViewGroup
. You could fill it with Button
s or even make your own custom key views that subclass View
. If you use popup views, then note this.onKeyClicked(String text)
or onBackspace()
.keyboard_view.xml
, key_preview.xml
, or number_pad.xml
described in the directions above since these are all for the standard KeyboardView
. You will handle all these UI aspects in your custom view.MyInputMethodService
class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener
, which is no longer needed.MyInputMethodService
class's onCreateInputView()
method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this
. WPF has built-in converters for certain types. If you bind the Image's Source
property to a string
or Uri
value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource
.
So
<Image Source="{Binding ImageSource}"/>
would work if the ImageSource property was a string representation of a valid URI to an image.
You can of course roll your own Binding converter:
public class ImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
and use it like this:
<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>
In controller:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
If you want to create and copy the content in a single shot, just use the SELECT
:
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
As others have noted, most likely you don't have .html
set up to handle php code.
Having said that, if all you're doing is using index.html
to include index.php
, your question should probably be 'how do I use index.php
as index document?
In which case, for Apache (httpd.conf), search for DirectoryIndex
and replace the line with this (will only work if you have dir_module
enabled, but that's default on most installs):
DirectoryIndex index.php
If you use other directory indexes, list them in order of preference i.e.
DirectoryIndex index.php index.phtml index.html index.htm
For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as "csv" in "import csv") and select "go to definition" - this will open the file, but also on the top you can see the exact file location ("C:....csv.py")
You have already grouped by ContenderNum, no need to partition again by it. Use Dense_rank()and order by totals desc. In short,
SELECT contendernum,totals, **DENSE_RANK()**
OVER (ORDER BY totals **DESC**)
AS xRank
FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
There are many advantages of enums that are posted here, and I am creating such enums right now as asked in the question. But I have an enum with 5-6 fields.
enum Planet{
EARTH(1000000, 312312321,31232131, "some text", "", 12),
....
other planets
....
In these kinds of cases, when you have multiple fields in enums, it is much difficult to understand which value belongs to which field as you need to see constructor and eye-ball.
Class with static final
constants and using Builder
pattern to create such objects makes it more readable. But, you would lose all other advantages of using an enum, if you need them.
One disadvantage of such classes is, you need to add the Planet
objects manually to the list/set
of Planets.
I still prefer enum over such class, as values()
comes in handy and you never know if you need them to use in switch
or EnumSet
or EnumMap
in future :)
df['variance'] = df.loc[:,['budget','actual']].sum(axis=1)
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
I think most posters here miss the point completely. I had the same problem. The original question was about the Highlighted state of a Selected button (COMBINING BOTH STATES) which cannot be set in IB and falls back to Default state with some darkening going on. Only working solution as one post mentioned:
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
MSBuild usually works, but I've run into difficulties before. You may have better luck with
devenv YourSolution.sln /Build
There are two options:
Create a php class file inside app/libraries/YourClassFile.php
a. Any function you create in it would be easily accessible in all the views and controllers.
b. If it is a static function you can easily access it by the class name.
c. Make sure you inclued "app/libraries" in autoload classmap in composer file.
In app/config/app.php create a variable and you can reference the same using
Config::get('variable_name');
Hope this helps.
Edit 1:
Example for my 1st point:
// app/libraries/DefaultFunctions.php
class DefaultFunctions{
public static function getSomeValue(){
// Fetch the Site Settings object
$site_settings = Setting::all();
return $site_settings;
}
}
//composer.json
"autoload": {
"classmap": [
..
..
..
"app/libraries" // add the libraries to access globaly.
]
}
//YourController.php
$default_functions = new DefaultFunctions();
$default_functions->getSomeValue();
Here's a snippet of what I'm using for my latest project.
From the controller:
if ( IS_DEV ) {
$this->view->cacheBust = microtime(true);
} else {
$this->view->cacheBust = file_exists($versionFile)
// The version file exists, encode it
? urlencode( file_get_contents($versionFile) )
// Use today's year and week number to still have caching and busting
: date("YW");
}
From the view:
<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">
Our publishing process generates a file with the revision number of the current build. This works by URL encoding that file and using that as a cache buster. As a fail-over, if that file doesn't exist, the year and week number are used so that caching still works, and it will be refreshed at least once a week.
Also, this provides cache busting for every page load while in the development environment so that developers don't have to worry with clearing the cache for any resources (javascript, css, ajax calls, etc).
The Bootstrap Collapse has some Events that you can react to:
$(document).ready(function(){
$('#accordProfile').on('shown', function () {
$(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
});
$('#accordProfile').on('hidden', function () {
$(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
});
});