Refer this question: The mouseEvent.offsetX I am getting is much larger than actual canvas size .I have given a function there which will exactly suit in your situation
<html>
element in CSS pixels.viewport
in CSS pixels.screen
in device pixels.Regarding your last question if calculations are similar on desktop and mobile browsers... For a better understanding - on mobile browsers - we need to differentiate two new concept: the layout viewport and visual viewport. The visual viewport is the part of the page that's currently shown onscreen. The layout viewport is synonym for a full page rendered on a desktop browser (with all the elements that are not visible on the current viewport).
On mobile browsers the pageX
and pageY
are still relative to the page in CSS pixels so you can obtain the mouse coordinates relative to the document page. On the other hand clientX
and clientY
define the mouse coordinates in relation to the visual viewport.
There is another stackoverflow thread here regarding the differences between the visual viewport and layout viewport : Difference between visual viewport and layout viewport?
Another good resource: http://www.quirksmode.org/mobile/viewports2.html
To get the position look at the OnMouseMove event. The MouseEventArgs will give you the x an y positions...
protected override void OnMouseMove(MouseEventArgs mouseEv)
To set the mouse position use the Cursor.Position property.
http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx
Bottom line is that you'll have to write a new css rule for that.
Depending on which bundle of Twitter Bootstrap you're using, you should have variables for the various colours.
Try something like:
.table tbody tr > td {
&.success { background-color: $green; }
&.info { background-color: $blue; }
...
}
Surely there's a way to use extend
or the LESS equivalent to avoid repeating the same styling.
Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.
Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ......
Maximum is 2097151, If you try set more error occurred.
in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:
variant 1 without override: result is 200
class Car {
public int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
variant 2 with override keyword: result is 400
class Car {
public virtual int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public override int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
You could do something like this for your case - (syntax may be a bit off). Also look at this link
subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();
finalQuery = from u in Users where u.LastName.Contains('fra') && subQuery.Contains(u.Id) select u;
pyenv
is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.
Install pyenv
.
$ pyenv install --list
Available versions:
2.1.3
[...]
3.8.1
3.9-dev
activepython-2.7.14
activepython-3.5.4
activepython-3.6.0
anaconda-1.4.0
[... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]
$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1
$ pyenv versions
* system (set by /home/moose/.pyenv/version)
2.7.16
3.5.7
3.6.9
3.7.4
3.8-dev
$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)
$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment
$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)
You can also use the WriteLiteral method
This is what you need.
var hasNumber = /\d/;
hasNumber.test("ABC33SDF"); //true
hasNumber.test("ABCSDF"); //false
To grep for carriage return, namely the \r
character, or 0x0d
, we can do this:
grep -F $'\r' application.log
Alternatively, use printf
, or echo
, for POSIX compatibility
grep -F "$(printf '\r')" application.log
And we can use hexdump
, or less
to see the result:
$ printf "a\rb" | grep -F $'\r' | hexdump -c
0000000 a \r b \n
Regarding the use of $'\r'
and other supported characters, see Bash Manual > ANSI-C Quoting:
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard
In my case, I put a mistake in my web.config
file. The application key somehow was put under the <appSettings> tag. But I wonder why it doesn't display a configuration error. The error 500 is too generic for investigating the problem.
Try with the following mark-up instead of directly specifying height:
.box-centerside {_x000D_
background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;_x000D_
float: left;_x000D_
min-height: 100px;_x000D_
width: 260px;_x000D_
}
_x000D_
<div class="box-centerside">_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
This is sample content<br>_x000D_
</div>
_x000D_
If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.
Ok, solved my problem, if anyone is passing by here is the answer:
Just had to add left: 0,
and top: 0,
to the styles, and yes, I'm tired.
position: 'absolute',
left: 0,
top: 0,
Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:
#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()
which produces:
Name File
---- ----
...
m token /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...
.. suitable for grepping or what have you. Be warned, it's long!
^[0-9]{1,2}[:.,-]?po$
Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
Simple, try it:
It's /usr/local/java/jdk[version]
Try disabling Just My Code (JMC).
By default the debugger tries to restrict the view of the world to code that is only contained within your solution. This is really heplful at times but when you want to debug code which is not in your solution (as is your situation) you need to disable JMC in order to see it. Otherwise the code will be treated as external and largely hidden from your view.
EDIT
When you're broken in your code try the following.
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
you can set output format,eg to see only the command and the process id.
ps -eo pid,args
see the man page of ps for more output format. alternatively, you can use the -w
or --width n
options.
If all else fails, here's another workaround, (just to see your long cmds)
awk '{ split(FILENAME,f,"/") ; printf "%s: %s\n", f[3],$0 }' /proc/[0-9]*/cmdline
Html.Action is a poorly designed technology. Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.
To be closer to WebForm UserControl (*.ascx) you need to:
Create a page Model and a Partial Model
Place your Partial Model as a property in your page Model
In this situation you can use it like:
public class MyController : Controller
{
....
public MyController()
{
MyChildController = new MyControllerPartial(this.ViewData);
}
[HttpPost]
public ActionResult Index(MyPageViewModel model)
{
...
int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
...
}
}
P.S. In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see ASP.NET MVC partial views: input name prefixes
I'm on Ubuntu 20.04 and I kept getting the message that soon I wouldn't be able to login from console. I was terribly confused. Finally, I got to the URL below which will work. But you need to know how to create a PAT (Personal Access Token) which you are going to have to keep in a file on your computer.
Here's what the final URL will look like:
git push https://[email protected]/user-name/repo.git
long PAT (Personal Access Token) value -- The entire long value between the // and the @ sign in the url is your PAT.
user-name will be your exact username
repo.git will be your exact repo name
You need to generate a PAT following the steps at: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
That will give you the PAT value that you will place in your URL.
When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your REPOs.
Save Your PAT Or Lose It
Once you have your PAT. You're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT
Now you're going to need at the very least :
For 1, just use :
$ cat ~/files/myPatFile.txt
Where the path is a real path to the location and file where you stored your PAT value.
For 2
$ xclip -selection clipboard < ~/files/myPatFile.txt
That'll copy the contents of the file to the clipboard so you can use your PAT more easily.
FYI - if you don't have xclip do the following:
$ sudo apt-get install xclip
Downloads and installs xclip. If you don't have apt-get
, you might need to use another installer (like yum
)
Java has a assert
statement, the JVM disables assertion validation by default. They must be explicitly enabled using command line argument -enableassertions
(or its shorthand -ea
),
while JavaScript supports console.assert()
, it's just a logging method and won't interrupt current procedure if assertion failed.
To bring things together and satisfy various needs, here is a tiny js assertion lib.
globalThis.assert = (()=> {
class AssertionError extends Error {
constructor(message) {
super(message);
this.name = 'AssertionError';
}
}
let config = {
async: true,
silent: false
};
function assert(condition, message = undefined) {
if (!condition) {
if (config.silent) {
//NOOP
} else if (config.async) {
console.assert(condition, message || 'assert');
} else {
throw new AssertionError(message || 'assertion failed');
}
}
}
assert.config = config;
return assert;
})();
/* global assert */
Object.assign(assert.config, {
// silent: true, // to disable assertion validation
async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's)
});
let items = [
{id: 1},
{id: 2},
{id: 3}
];
function deleteItem(item) {
let index = items.findIndex((e)=> e.id === item.id);
assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`);
items.splice(index, 1);
}
console.log('begin');
deleteItem({id: 1});
deleteItem({id: 1});
console.log('end');
_x000D_
You may also do by this way:
override func viewWillLayoutSubviews() {
if let items = self.tabBar.items {
for item in 0..<items.count {
items[item].image = items[item].image?.withRenderingMode(.alwaysOriginal)
items[item].selectedImage = items[item].selectedImage?.withRenderingMode(.alwaysTemplate)
}
Optional:
UITabBar.appearance().tintColor = UIColor.red
I hope it will help you.
First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013
/p:VisualStudioVersion=12.0
add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.
So the complete code would be something like this
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0
The dataframe can be changed by just doing
df.columns = df.iloc[0]
df = df[1:]
Then
df.to_csv(path, index=False)
Should do the trick.
Just to notify here. (from a newbee, keviv22)
Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.
Invalid Folder namings as follows:
valid Folder namings for above:
What mistake I did:
consider the file structure.
Parent
. __init__.py
. Setup
.. __init__.py
.. Generic-Class-Folder
... __init__.py
... targetClass.py
. Check
.. __init__.py
.. testFile.py
What I wanted to do?
What command I did?
from Core.Generic-Class-Folder.targetClass import functionExecute
SyntaxError: invalid syntax
Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py
file, inserted environment path and hugely worried what went wrong......
And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!
(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)
I've found pickling confusing (possibly because I'm thick). I found that this works, though:
myDictionaryString=str(myDictionary)
Which you can then write to a text file. I gave up trying to use pickle as I was getting errors telling me to write integers to a .dat file. I apologise for not using pickle.
If you need to convert ALL columns to strings, you can simply use:
df = df.astype(str)
This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):
df[["D", "E"]] = df[["D", "E"]].astype(int)
I think this should do the trick:
<table border="1px" align="center">
According to http://w3schools.com/tags/tag_table.asp this is deprecated, but try it. If it does not work, go for styles, as mentioned on the site.
So you really want:
for each tweet
unless tweet is in db
insert tweet
If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.
What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.
Put this code in the <head></head>
tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
Team->Share project
is exactly what you need to do. Select SVN from the list, then click "Next". Subclipse will notice the presence of .svn directories that will ask you to confirm that the information is correct, and associate the project with subclipse.
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
It is usually handled automatically.
If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery
Node 1:
cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["node1.example.com"]
Node 2:
cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["node1.example.com"]
and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.
Edit: Please note that by ES rule, if you have N
nodes, then by convention, N/2+1
nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.
Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.
For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.
I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:
Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant
f.show
with f
.allowmultiselect = false
for each varfile in .selecteditems
msgbox varfile
next varfile
end with
Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here
If it is a reversible migration and the last one which has been executed, then run rake db:rollback
. And you can always use version.
e.g
the migration file is 20140716084539_create_customer_stats.rb,so the rollback command will be,
rake db:migrate:down VERSION=20140716084539
Between the above answers its been explained but I will try to expand slightly...
The point about the cup of tea is a good one. A flow chart is concerned with the physical aspects of a task and as such is used to represent something as it is currently. This is useful in developing understanding about a situation/communication/training etc etc..You will likley have come across these in your work places, certainly if they have adopted the ISO9000 standards.
A data flow diagram is concerned with the logical aspects of an activity so again the cup of tea analogy is a good one. If you use a data flow diagram in conjunction with a process flow your data flow would only be concerned with the flow of data/information regarding a process, to the exclusion of the physical aspects. If you wonder why that would be useful then its because data flow diagrams allow us to move from the 'as it is' situation and see it that something as it could/will be. These two modelling approaches are common in structured analysis and design and typically used by systems/business analysts as part of business process improvement/re-engineering.
Update: This answer has led to the development of ng2-completer
an Angular2 autocomplete component.
This is the list of existing autocomplete components for Angular2:
Credit goes to @dan-cancro for coming up with the idea
Keeping the original answer for those who wish to create their own directive:
To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:
It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.
This is the directive code:
"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";
@Directive({
selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
host: {
"(keyup)": "onKey($event)" // Liten to keyup events on the host component
}
})
export class AutocompleteDirective implements OnInit {
// The search function should be passed as an input
@Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
// The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
@Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();
private term = "";
private listCmp: ComponentRef<AutocompleteList> = undefined;
private refreshTimer: any = undefined;
private searchInProgress = false;
private searchRequired = false;
constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
/**
* On key event is triggered when a key is released on the host component
* the event starts a timer to prevent concurrent requests
*/
public onKey(event: any) {
if (!this.refreshTimer) {
this.refreshTimer = setTimeout(
() => {
if (!this.searchInProgress) {
this.doSearch();
} else {
// If a request is in progress mark that a new search is required
this.searchRequired = true;
}
},
200);
}
this.term = event.target.value;
if (this.term === "" && this.listCmp) {
// clean the list if the search term is empty
this.removeList();
}
}
public ngOnInit() {
// When an item is selected remove the list
this.selected.subscribe(() => {
this.removeList();
});
}
/**
* Call the search function and handle the results
*/
private doSearch() {
this.refreshTimer = undefined;
// if we have a search function and a valid search term call the search
if (this.search && this.term !== "") {
this.searchInProgress = true;
this.search(this.term)
.then((res) => {
this.searchInProgress = false;
// if the term has changed during our search do another search
if (this.searchRequired) {
this.searchRequired = false;
this.doSearch();
} else {
// display the list of results
this.displayList(res);
}
})
.catch(err => {
console.log("search error:", err);
this.removeList();
});
}
}
/**
* Display the list of results
* Dynamically load the list component if it doesn't exist yet and update the suggestions list
*/
private displayList(list: Array<{ text: string, data: any }>) {
if (!this.listCmp) {
this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
.then(cmp => {
// The component is loaded
this.listCmp = cmp;
this.updateList(list);
// Emit the selectd event when the component fires its selected event
(<AutocompleteList>(this.listCmp.instance)).selected
.subscribe(selectedItem => {
this.selected.emit(selectedItem);
});
});
} else {
this.updateList(list);
}
}
/**
* Update the suggestions list in the list component
*/
private updateList(list: Array<{ text: string, data: any }>) {
if (this.listCmp) {
(<AutocompleteList>(this.listCmp.instance)).list = list;
}
}
/**
* remove the list component
*/
private removeList() {
this.searchInProgress = false;
this.searchRequired = false;
if (this.listCmp) {
this.listCmp.destroy();
this.listCmp = undefined;
}
}
}
The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:
"use strict";
import {Component, Output, EventEmitter} from "@angular/core";
@Component({
selector: "autocomplete-list",
template: `<div class="dropdown-menu search-results">
<a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
</div>`, // Use a bootstrap 4 dropdown-menu to display the list
styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList {
// Emit a selected event when an item in the list is selected
@Output() public selected = new EventEmitter();
public list;
/**
* Listen for a click event on the list
*/
public onClick(item: {text: string, data: any}) {
this.selected.emit(item);
}
}
To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:
"use strict";
import {Component} from "@angular/core";
import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";
@Component({
selector: "my-cmp",
directives: [AutocompleteDirective],
template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent {
/**
* generate a search function that returns a Promise that resolves to array of text and optionally additional data
*/
public search() {
return (filter: string): Promise<Array<{ text: string, data: any }>> => {
// do the search
resolve({text: "one item", data: null});
};
}
/**
* handle item selection
*/
public onItemSelected(selected: { text: string, data: any }) {
console.log("selected: ", selected.text);
}
}
Update: code compatible with angular2 rc.1
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
This code should do the same as your new routine, working with the correct multi-dimensional array..
$arr = array(
'string1' => array('a' => '', 'b' => '', 'c' => ''),
'string2' => array('a' => '', 'b' => '', 'c' => ''),
'string3' => array('a' => '', 'b' => '', 'c' => '')
);
echo 'Index of "string2" = '. array_search('string2', array_keys($arr));
$('#root').append(child).anotherMethod();
This solution gives your answer plus additional properties. No JQuery or other dependencies required, paste and go.
Usage
getUrlParts("https://news.google.com/news/headlines/technology.html?ned=us&hl=en")
Output
{
"origin": "https://news.google.com",
"domain": "news.google.com",
"subdomain": "news",
"domainroot": "google.com",
"domainpath": "news.google.com/news/headlines",
"tld": ".com",
"path": "news/headlines/technology.html",
"query": "ned=us&hl=en",
"protocol": "https",
"port": 443,
"parts": [
"news",
"google",
"com"
],
"segments": [
"news",
"headlines",
"technology.html"
],
"params": [
{
"key": "ned",
"val": "us"
},
{
"key": "hl",
"val": "en"
}
]
}
Code
The code is designed to be easy to understand rather than super fast. It can be called easily 100 times per second, so it's great for front end or a few server usages, but not for high volume throughput.
function getUrlParts(fullyQualifiedUrl) {
var url = {},
tempProtocol
var a = document.createElement('a')
// if doesn't start with something like https:// it's not a url, but try to work around that
if (fullyQualifiedUrl.indexOf('://') == -1) {
tempProtocol = 'https://'
a.href = tempProtocol + fullyQualifiedUrl
} else
a.href = fullyQualifiedUrl
var parts = a.hostname.split('.')
url.origin = tempProtocol ? "" : a.origin
url.domain = a.hostname
url.subdomain = parts[0]
url.domainroot = ''
url.domainpath = ''
url.tld = '.' + parts[parts.length - 1]
url.path = a.pathname.substring(1)
url.query = a.search.substr(1)
url.protocol = tempProtocol ? "" : a.protocol.substr(0, a.protocol.length - 1)
url.port = tempProtocol ? "" : a.port ? a.port : a.protocol === 'http:' ? 80 : a.protocol === 'https:' ? 443 : a.port
url.parts = parts
url.segments = a.pathname === '/' ? [] : a.pathname.split('/').slice(1)
url.params = url.query === '' ? [] : url.query.split('&')
for (var j = 0; j < url.params.length; j++) {
var param = url.params[j];
var keyval = param.split('=')
url.params[j] = {
'key': keyval[0],
'val': keyval[1]
}
}
// domainroot
if (parts.length > 2) {
url.domainroot = parts[parts.length - 2] + '.' + parts[parts.length - 1];
// check for country code top level domain
if (parts[parts.length - 1].length == 2 && parts[parts.length - 1].length == 2)
url.domainroot = parts[parts.length - 3] + '.' + url.domainroot;
}
// domainpath (domain+path without filenames)
if (url.segments.length > 0) {
var lastSegment = url.segments[url.segments.length - 1]
var endsWithFile = lastSegment.indexOf('.') != -1
if (endsWithFile) {
var fileSegment = url.path.indexOf(lastSegment)
var pathNoFile = url.path.substr(0, fileSegment - 1)
url.domainpath = url.domain
if (pathNoFile)
url.domainpath = url.domainpath + '/' + pathNoFile
} else
url.domainpath = url.domain + '/' + url.path
} else
url.domainpath = url.domain
return url
}
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.
I use JuJu which basically allows to have a really tiny linux distribution (containing just the package manager) inside your $HOME/.juju directory.
It allows to have your custom system inside the home directory accessible via proot and, therefore, you can install any packages without root privileges. It will run properly to all the major linux distributions, the only limitation is that JuJu can run on linux kernel with minimum reccomended version 2.6.32.
For instance, after installed JuJu to install pip just type the following:
$>juju -f
(juju)$> pacman -S python-pip
(juju)> pip
Here is another way to do it, if you need something flexible where you want to display help if specific params are passed, none at all or more than 1 conflicting arg:
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--days', required=False, help="Check mapped inventory that is x days old", default=None)
parser.add_argument('-e', '--event', required=False, action="store", dest="event_id",
help="Check mapped inventory for a specific event", default=None)
parser.add_argument('-b', '--broker', required=False, action="store", dest="broker_id",
help="Check mapped inventory for a broker", default=None)
parser.add_argument('-k', '--keyword', required=False, action="store", dest="event_keyword",
help="Check mapped inventory for a specific event keyword", default=None)
parser.add_argument('-p', '--product', required=False, action="store", dest="product_id",
help="Check mapped inventory for a specific product", default=None)
parser.add_argument('-m', '--metadata', required=False, action="store", dest="metadata",
help="Check mapped inventory for specific metadata, good for debugging past tix", default=None)
parser.add_argument('-u', '--update', required=False, action="store_true", dest="make_updates",
help="Update the event for a product if there is a difference, default No", default=False)
args = parser.parse_args()
days = args.days
event_id = args.event_id
broker_id = args.broker_id
event_keyword = args.event_keyword
product_id = args.product_id
metadata = args.metadata
make_updates = args.make_updates
no_change_counter = 0
change_counter = 0
req_arg = bool(days) + bool(event_id) + bool(broker_id) + bool(product_id) + bool(event_keyword) + bool(metadata)
if not req_arg:
print("Need to specify days, broker id, event id, event keyword or past tickets full metadata")
parser.print_help()
sys.exit()
elif req_arg != 1:
print("More than one option specified. Need to specify only one required option")
parser.print_help()
sys.exit()
# Processing logic here ...
Cheers!
A simple one line code to check whether the string is palindrome or not:
function palindrome (str) {_x000D_
_x000D_
return str === str.split("").reverse().join("");_x000D_
_x000D_
}
_x000D_
<!-- Change the argument to check for other strings -->_x000D_
<button type="button" onclick="alert(palindrome('naman'));">Click Me<utton>
_x000D_
The above function will return true if the string is palindrome. Else, it will return false.
I have ubuntu 14 and the other answers where no working for me
iconv -f ISO-8859-1 -t UTF-8 in.tex > out.tex
I found this command here
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
_x000D_
They are simply called objects.
Implemented this way without using Jquery:
<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>
sendEmail(message) {
var email = message.emailId;
var subject = message.subject;
var emailBody = 'Hi '+message.from;
document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}
Simple but usefull way:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
If another_branch
already exists locally and you are not on this branch, then git checkout another_branch
switches to the branch.
If another_branch
does not exist but origin/another_branch
does, then git checkout another_branch
is equivalent to git checkout -b another_branch origin/another_branch; git branch -u origin/another_branch
. That's to create another_branch
from origin/another_branch
and set origin/another_branch
as the upstream of another_branch
.
If neither exists, git checkout another_branch
returns error.
git checkout origin another_branch
returns error in most cases. If origin
is a revision and another_branch
is a file, then it checks out the file of that revision but most probably that's not what you expect. origin
is mostly used in git fetch
, git pull
and git push
as a remote, an alias of the url to the remote repository.
git checkout origin/another_branch
succeeds if origin/another_branch
exists. It leads to be in detached HEAD state, not on any branch. If you make new commits, the new commits are not reachable from any existing branches and none of the branches will be updated.
UPDATE:
As 2.23.0 has been released, with it we can also use git switch
to create and switch branches.
If foo
exists, try to switch to foo
:
git switch foo
If foo
does not exist and origin/foo
exists, try to create foo
from origin/foo
and then switch to foo
:
git switch -c foo origin/foo
# or simply
git switch foo
More generally, if foo
does not exist, try to create foo
from a known ref or commit and then switch to foo
:
git switch -c foo <ref>
git switch -c foo <commit>
If we maintain a repository in Gitlab and Github at the same time, the local repository may have two remotes, for example, origin
for Gitlab and github
for Github. In this case the repository has origin/foo
and github/foo
. git switch foo
will complain fatal: invalid reference: foo
, because it does not known from which ref, origin/foo
or github/foo
, to create foo
. We need to specify it with git switch -c foo origin/foo
or git switch -c foo github/foo
according to the need. If we want to create branches from both remote branches, it's better to use distinguishing names for the new branches:
git switch -c gitlab_foo origin/foo
git switch -c github_foo github/foo
If foo
exists, try to recreate/force-create foo
from (or reset foo
to) a known ref or commit and then switch to foo
:
git switch -C foo <ref>
git switch -C foo <commit>
which are equivalent to:
git switch foo
git reset [<ref>|<commit>] --hard
Try to switch to a detached HEAD of a known ref or commit:
git switch -d <ref>
git switch -d <commit>
If you just want to create a branch but not switch to it, use git branch
instead. Try to create a branch from a known ref or commit:
git branch foo <ref>
git branch foo <commit>
It can be done by:
select{
background: url(data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6IzQ0NDt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPmFycm93czwvdGl0bGU+PHJlY3QgY2xhc3M9ImNscy0xIiB3aWR0aD0iNC45NSIgaGVpZ2h0PSIxMCIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxLjQxIDQuNjcgMi40OCAzLjE4IDMuNTQgNC42NyAxLjQxIDQuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIi8+PC9zdmc+) no-repeat 100% 50%;
}
select{_x000D_
background: url(data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6IzQ0NDt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPmFycm93czwvdGl0bGU+PHJlY3QgY2xhc3M9ImNscy0xIiB3aWR0aD0iNC45NSIgaGVpZ2h0PSIxMCIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxLjQxIDQuNjcgMi40OCAzLjE4IDMuNTQgNC42NyAxLjQxIDQuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIi8+PC9zdmc+) no-repeat 100% 50%;_x000D_
_x000D_
_x000D_
-moz-appearance: none;_x000D_
-webkit-appearance: none;_x000D_
-webkit-border-radius: 0px;_x000D_
appearance: none;_x000D_
outline-width: 0;_x000D_
_x000D_
padding: 10px 10px 10px 5px;_x000D_
display: block;_x000D_
width: 10em;_x000D_
border: none;_x000D_
font-size: 1rem;_x000D_
_x000D_
border-bottom: 1px solid #757575;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
<select class="units">_x000D_
<option value="Metres">Metres</option>_x000D_
<option value="Feet">Feet</option>_x000D_
<option value="Fathoms">Fathoms</option>_x000D_
</select>_x000D_
</div>
_x000D_
You can use data-*
attribute to embed custom data. The data-*
attributes gives us the ability to embed custom data attributes on all HTML elements.
jQuery .data()
method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
jQuery .attr()
method get/set attribute value for only the first element in the matched set.
Example:
<span id="test" title="foo" data-kind="primary">foo</span>
$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");
Even we faced the same problem where RAILS_ENV=production bundle exec rake assets:precompile
succeeded but things did not work as expected.
We found that unicorn was the main culprit here.
Same as your case, even we used to restart unicorn after compiling the assets. It was noticed that when unicorn is restarted, only its worker processes are restarted and not the master process.
This is the main reason the correct assets are not served.
Later, after compiling assets, we stopped and started unicorn so that the unicorn master process is also restarted and the correct assets were getting served.
Stopping and starting unicorn brings around 10 secs on downtime when compared to restarting the unicorn. This is the workaround that can be used where as long term solution is move to puma from unicorn.
I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.
You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %>
with its successor EL ${}
. They do not share the same variable scope. The allFestivals
is not available in scriptlet scope and the i
is not available in EL scope.
You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
and then iterate over the list as follows:
<c:forEach items="${allFestivals}" var="festival">
<tr>
<td>${festival.festivalName}</td>
<td>${festival.location}</td>
<td>${festival.startDate}</td>
<td>${festival.endDate}</td>
<td>${festival.URL}</td>
</tr>
</c:forEach>
(beware of possible XSS attack holes, use <c:out>
accordingly)
Don't forget to remove the <jsp:useBean>
as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml
so that you won't accidently use them:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
JAPICC, sample usage:
japi-compliance-checker OLD.jar NEW.jar
Sample reports for log4j: http://abi-laboratory.pro/java/tracker/timeline/log4j/
PkgDiff, sample usage:
pkgdiff OLD.jar NEW.jar
See sample report for args4j.
Clirr, sample usage:
java -jar clirr-core-0.6-uber.jar -o OLD.jar -n NEW.jar
Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.
However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:
CREATE TABLE my_table
(
id serial PRIMARY KEY not null,
my_date date not null default CURRENT_DATE
);
(CURRENT_DATE is basically a synonym for now() and a cast to date).
(Edited to use to_char).
Then you can get your output like:
SELECT id, to_char(my_date, 'yyyymm') FROM my_table;
Now, if you did really need to store that field as a string and ensure the format you could always do:
CREATE TABLE my_other_table
(
id serial PRIMARY KEY not null,
my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
);
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
I had my table originally created with CHARSET=latin1. After table conversion to utf8 some columns were not converted, however that was not really obvious.
You can try to run SHOW CREATE TABLE my_table;
and see which column was not converted or just fix incorrect character set on problematic column with query below (change varchar length and CHARSET and COLLATE according to your needs):
ALTER TABLE `my_table` CHANGE `my_column` `my_column` VARCHAR(10) CHARSET utf8
COLLATE utf8_general_ci NULL;
No such file or directory
can be also raised if you are trying to put a file argument to Popen
with double-quotes.
For example:
call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']
In this case, you need to remove double-quotes.
call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']
You can call a function after the state value has updated:
this.setState({foo: 'bar'}, () => {
// Do something here.
});
Also, if you have lots of states to update at once, group them all within the same setState
:
Instead of:
this.setState({foo: "one"}, () => {
this.setState({bar: "two"});
});
Just do this:
this.setState({
foo: "one",
bar: "two"
});
A very simple way.
Go to CMD and type the following without '$' and choose a name as your HotspotName
and a password as your HotspotPassword
.
$ netsh wlan set hostednetwork mode=HotspotName key=HotspotPassword
$ netsh wlan start hostednetwork
Connect your phone to the WiFi and explore its network info, get Gateway address
it's kinda like IP address.
Enter the Gateway address into Chrome URL bar and you're good
Remove style attribute from div using J query:
$("#TableDiv").removeAttr("style");
Add style to div using J query:
$("#TableDiv").attr("style", "display: none;");
Add style using html:
<div class="row" id="TableDiv" style="display: none;">
</div>
Hope it will helpful :)
A common mistake that I did because I was moving application from once pc to another and none of the above worked was that I forgot to copy the connection string to both App.Config and Web.Config!
Have you tried setting JButton.setOpaque(true)?
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
I'v solved this error by setting the correct path variables
C:\Users\name\AppData\Local\Programs\Python\Python37\Scripts
C:\Users\name\AppData\Local\Programs\Python\Python37\Lib\site-packages
You can also hide again advanced option after reconfigure:
-- show advanced options
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
-- enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
-- hide advanced options
EXEC sp_configure 'show advanced options', 0
GO
RECONFIGURE
GO
TL;DR:
They use a stack architecture with cached graphs for everything above the MySQL bottom of their stack.
Long Answer:
I did some research on this myself because I was curious how they handle their huge amount of data and search it in a quick way. I've seen people complaining about custom made social network scripts becoming slow when the user base grows. After I did some benchmarking myself with just 10k users and 2.5 million friend connections - not even trying to bother about group permissions and likes and wall posts - it quickly turned out that this approach is flawed. So I've spent some time searching the web on how to do it better and came across this official Facebook article:
I really recommend you to watch the presentation of the first link above before continue reading. It's probably the best explanation of how FB works behind the scenes you can find.
The video and article tells you a few things:
Let's take a look at this, friend connections are top left:
Well, this is a graph. :) It doesn't tell you how to build it in SQL, there are several ways to do it but this site has a good amount of different approaches. Attention: Consider that a relational DB is what it is: It's thought to store normalised data, not a graph structure. So it won't perform as good as a specialised graph database.
Also consider that you have to do more complex queries than just friends of friends, for example when you want to filter all locations around a given coordinate that you and your friends of friends like. A graph is the perfect solution here.
I can't tell you how to build it so that it will perform well but it clearly requires some trial and error and benchmarking.
Here is my disappointing test for just findings friends of friends:
DB Schema:
CREATE TABLE IF NOT EXISTS `friends` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`friend_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Friends of Friends Query:
(
select friend_id
from friends
where user_id = 1
) union (
select distinct ff.friend_id
from
friends f
join friends ff on ff.user_id = f.friend_id
where f.user_id = 1
)
I really recommend you to create you some sample data with at least 10k user records and each of them having at least 250 friend connections and then run this query. On my machine (i7 4770k, SSD, 16gb RAM) the result was ~0.18 seconds for that query. Maybe it can be optimized, I'm not a DB genius (suggestions are welcome). However, if this scales linear you're already at 1.8 seconds for just 100k users, 18 seconds for 1 million users.
This might still sound OKish for ~100k users but consider that you just fetched friends of friends and didn't do any more complex query like "display me only posts from friends of friends + do the permission check if I'm allowed or NOT allowed to see some of them + do a sub query to check if I liked any of them". You want to let the DB do the check on if you liked a post already or not or you'll have to do in code. Also consider that this is not the only query you run and that your have more than active user at the same time on a more or less popular site.
I think my answer answers the question how Facebook designed their friends relationship very well but I'm sorry that I can't tell you how to implement it in a way it will work fast. Implementing a social network is easy but making sure it performs well is clearly not - IMHO.
I've started experimenting with OrientDB to do the graph-queries and mapping my edges to the underlying SQL DB. If I ever get it done I'll write an article about it.
When encountering an 'Unsupported feature' error while using Statement.RETURN_GENERATED_KEYS
, try this:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BATCHID
is the auto generated id.
Note that in Java 8, you can use the java.time.ZonedDateTime class and its static parse(CharSequence text)
method.
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
method will turn a managed type instance into a JSON string.
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).
You could specify type like this:
[string[]] $a = "This", "Is", "a", "cat"
Checking the type:
$a.GetType()
Confirms:
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array
Outputting $a:
PS C:\> $a This Is a cat
Here's a video and explaination how to use Instruments and NSZombie to find and fix memory crashes on iOS: http://www.markj.net/iphone-memory-debug-nszombie/
I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:
Add a couple of globals:
var clickms = 100;
var lastTouchDown = -1;
Then modify the switch statement from the original to this:
var d = new Date();
switch(event.type)
{
case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
case "touchmove": type="mousemove"; lastTouchDown = -1; break;
case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
default: return;
}
You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.
Use the CSS3 Viewport-percentage feature.
Viewport-Percentage Explanation
Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Styles</title>_x000D_
_x000D_
<style>_x000D_
@media screen and (min-width: 480px) {_x000D_
body {_x000D_
background-color: skyblue;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
border: groove black;_x000D_
}_x000D_
_x000D_
div#main {_x000D_
font-size: 3vw;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div id="main">_x000D_
Viewport-Percentage Test_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I was using Write #1 "Print my Line" instead I tried Print #1, "Print my Line" and it give me all the data without default Quote(")
Dim strFile_Path As String
strFile_Path = ThisWorkbook.Path & "\" & "XXXX" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".txt"
Open strFile_Path For Output As #1
Dim selectedFeature As String
For counter = 7 To maxNumberOfColumn
selectedFeature = "X"
Print #1, selectedFeature
'Write #1, selectedFeature
Next counter
Close #1
There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.
grep -R "string" /directory/
-R follows also symlinks when -r does not.
Wont the below basic approach doesn't suffice your requirements?
HTML Code having a div
<div id="mydiv" onscroll='myMethod();'>
JS will have below code
function myMethod(){ alert(1); }
you can extend LinkedHashSet
adding your desired getIndex()
method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.
What you put directly under src/main/java
is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources
: they end up at the root of the classpath.
So the path of the resource is app-context.xml
, not main/resources/app-context.xml
.
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor
:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
In ubuntu 14.04, while execute apt-get install rubygems, there is a error
E: Package 'rubygems' has no installation candidate
follow command solve the problems.
sudo apt-get install gcc ruby-devel rubygems-integration ruby-compass
Probably because you're using unsafe code.
Are you doing something with pointers or unmanaged assemblies somewhere?
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
It's been a while since you asked but I just had the same issue. As already mentioned by Estel the problem with key listeners is that they only work with hardware keyboards. To do this with an IME (soft keyboard), the solution is a bit more elaborate.
The single method we actually want to override is sendKeyEvent
in the EditText
's InputConnection
class. This method is called when key events occur in an IME. But in order to override this, we need to implement a custom EditText
which overrides the onCreateInputConnection
method, wrapping the default InputConnection
object in a proxy class! :|
Sounds complicated, but here's the simplest example I could contrive:
public class ZanyEditText extends EditText {
private Random r = new Random();
public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ZanyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZanyEditText(Context context) {
super(context);
}
public void setRandomBackgroundColor() {
setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
.nextInt(256)));
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
true);
}
private class ZanyInputConnection extends InputConnectionWrapper {
public ZanyInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
ZanyEditText.this.setRandomBackgroundColor();
// Un-comment if you wish to cancel the backspace:
// return false;
}
return super.sendKeyEvent(event);
}
}
}
The line with the call to setRandomBackgroundColor
is where my special backspace action occurs. In this case, changing the EditText
's background colour.
If you're inflating this from XML remember to use the full package name as the tag:
<cc.buttfu.test.ZanyEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/somefield"
></cc.buttfu.test.ZanyEditText>
Actually if you do Ctrl+W W
, you won't need to add that extra Ctrl
. Does the same thing.
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
Using 3dGrabber's solution:
public static T GetEnumeratedType<T>(this IEnumerable<T> _)
{
return default(T);
}
//and now
var list = new Dictionary<string, int>();
var stronglyTypedVar = list.GetEnumeratedType();
Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.
Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)
#container {
height:500px;
min-height:500px;
}
This worked for me
On the tab "Workloads" check ".Net Core cross-platform development" and click on "Modify"
Don't forget to check ".NET Core 2.0 development tools" on the left menu.
I installed the Asp Net Core before, however not appeared on my Visual Studio, just after I installed using the installation of Visual Studio appeared for me.
To add all file at a time, use git add -A
To check git whole status, use git log
this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)
' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir
Sub luxation2()
Dim Filename As String
Filename = "temp201"
Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False
End Sub
Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?
Use dynamic query as below:
String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;
If I want to simply run the above query and get a List what is the best way?
List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
public String mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getString(1);
}
});
EDIT: To Stop SQL Injection, check for non word characters in the colName as :
Pattern pattern = Pattern.compile("\\W");
if(pattern.matcher(str).find()){
//throw exception as invalid column name
}
There's a great link about sending a POST request here by Example Depot::
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
If you want to send a GET request you can modify the code slightly to suit your needs. Specifically you have to add the parameters inside the constructor of the URL. Then, also comment out this wr.write(data);
One thing that's not written and you should beware of, is the timeouts. Especially if you want to use it in WebServices you have to set timeouts, otherwise the above code will wait indefinitely or for a very long time at least and it's something presumably you don't want.
Timeouts are set like this conn.setReadTimeout(2000);
the input parameter is in milliseconds
Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps
https://nominatim.openstreetmap.org/search?q=Mumbai&format=json
Here is the API documentation for reference.
Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.
Bassed on this page here:
I modified it so you can use ddbb in diferent hosts.
#!/bin/sh echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]" dump () { up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:}; mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2 } rm -f /tmp/db.diff # Compare up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:}; for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do if [ "`echo $3 | grep $table`" = "" ]; then echo "Comparing '$table'..." dump $1 /tmp/file1.sql dump $2 /tmp/file2.sql diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff else echo "Ignored '$table'..." fi done less /tmp/db.diff rm -f /tmp/file1.sql /tmp/file2.sql
Boost installed on OS X using homebrew has desired version.hpp
file in /usr/local/Cellar/boost/<version>/include/boost/version.hpp
(note, that the version is already mentioned in path).
I guess the fastest way to determine version on any UNIX-like system will be to search for boost
in /usr
:
find /usr -name "boost"
Put this in your CSS:
white-space:nowrap;
Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space
white-space
The white-space
property declares how white space inside the element is handled.
Values
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.
nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.
pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
inherit
Takes the same specified value as the property for the element's parent.
This is like default hint color, worked for me:
editText.setHintTextColor(Color.GRAY);
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
I know I am late... But for those who are curious... This is another way
if (Application.OpenForms.OfType<UpdateWindow>().Count() == 1)
Application.OpenForms.OfType<UpdateWindow>().First().Close();
UpdateWindow frm = new UpdateWindow()
frm.Show();
Do this.
public void FullScreencall() {
if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
View v = this.getWindow().getDecorView();
v.setSystemUiVisibility(View.GONE);
} else if(Build.VERSION.SDK_INT >= 19) {
//for new api versions.
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
}
This works 100% and you can do same for lower API versions, even if it's a late answer I hope it will helps someone else.
If you want this to be permanent, just call FullscreenCall()
inside your onResume()
method.
A simple way would be:
var newDt= dt.AsEnumerable()
.GroupBy(x => x.Field<int>("ColumnName"))
.Select(y => y.First())
.CopyToDataTable();
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
Please Follow this process
First of all install git bash and create a repository on git
1) Go to working directory where the file exist which you want to push on remote and create .git folder by
$ git init
2) Add the files in your new local repository.
$ git add .
Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity
3) Commit the files that you've staged in your local repository.
$ git commit -m "First commit"**
4) after this go to git repository and copy remote URL
$ git remote add origin *remote repository URL
5)
$ git remote -v
Note: this will ask for user.email and user.name just put it as per config
6)
$ git push origin master
this will push whole committed code to FILE.git on repository
And I think we done
We also need to mention default schema for SQSERVER: dbo
<property name="hibernate.default_schema">dbo</property>
Tested with hibernate 4
Maybe python changed since this question, all of the below seem to work well
Python2.7
int(1324343032.324325235 * 1000) / 1000.0
float(int(1324343032.324325235 * 1000)) / 1000
round(int(1324343032.324325235 * 1000) / 1000.0,3)
# result for all of the above is 1324343032.324
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
Actually, ECMAScript says on page 15: That an identifier may start with a $, an underscore or a UnicodeLetter, and then it goes on (just below that) to specify that a UnicodeLetter can be any character from the unicode catagories, Lo, Ll, Lu, Lt, Lm and Nl. And when you look up those catagories you will see that this opens up a lot more possibilities than just latin letters. Just search for "unicode catagories" in google and you can find them.
There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.
This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.
What would be needed, is the reverse of the eval()
function:
get_indentifier_name_missing_function()
which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.
Consider the following current state of affairs:
random_function(argument_data)
If one is passing an identifier name ('function','variable','dictionary',etc) argument_data
to a random_function()
(another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>
) to another identifier (e.g.: <function random_function at 0xafff78>
):
<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)
From my understanding, only the memory address is passed to the function:
<function at 0xafff78>(<object at 0xb1ce10>)
Therefore, one would need to pass a string as an argument to random_function()
in order for that function to have the argument's identifier name:
random_function('argument_data')
Inside the random_function()
def random_function(first_argument):
, one would use the already supplied string 'argument_data'
to:
serve as an 'identifier name' (to display, log, string split/concat, whatever)
feed the eval()
function in order to get a reference to the actual identifier, and therefore, a reference to the real data:
print("Currently working on", first_argument)
some_internal_var = eval(first_argument)
print("here comes the data: " + str(some_internal_var))
Unfortunately, this doesn't work in all cases. It only works if the random_function()
can resolve the 'argument_data'
string to an actual identifier. I.e. If argument_data
identifier name is available in the random_function()
's namespace.
This isn't always the case:
# main1.py
import some_module1
argument_data = 'my data'
some_module1.random_function('argument_data')
# some_module1.py
def random_function(first_argument):
print("Currently working on", first_argument)
some_internal_var = eval(first_argument)
print("here comes the data: " + str(some_internal_var))
######
Expected results would be:
Currently working on: argument_data
here comes the data: my data
Because argument_data
identifier name is not available in the random_function()
's namespace, this would yield instead:
Currently working on argument_data
Traceback (most recent call last):
File "~/main1.py", line 6, in <module>
some_module1.random_function('argument_data')
File "~/some_module1.py", line 4, in random_function
some_internal_var = eval(first_argument)
File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined
Now, consider the hypotetical usage of a get_indentifier_name_missing_function()
which would behave as described above.
Here's a dummy Python 3.0 code: .
# main2.py
import some_module2
some_dictionary_1 = { 'definition_1':'text_1',
'definition_2':'text_2',
'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
'key_4':'value_4',
'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
'etc':'etc.' }
for each_one_of_my_dictionaries in ( some_dictionary_1,
some_other_dictionary_2,
...,
some_other_dictionary_n ):
some_module2.some_function(each_one_of_my_dictionaries)
# some_module2.py
def some_function(a_dictionary_object):
for _key, _value in a_dictionary_object.items():
print( get_indentifier_name_missing_function(a_dictionary_object) +
" " +
str(_key) +
" = " +
str(_value) )
######
Expected results would be:
some_dictionary_1 definition_1 = text_1
some_dictionary_1 definition_2 = text_2
some_dictionary_1 etc = etc.
some_other_dictionary_2 key_3 = value_3
some_other_dictionary_2 key_4 = value_4
some_other_dictionary_2 etc = etc.
......
......
......
some_other_dictionary_n random_n = random_n
some_other_dictionary_n etc = etc.
Unfortunately, get_indentifier_name_missing_function()
would not see the 'original' identifier names (some_dictionary_
,some_other_dictionary_2
,some_other_dictionary_n
). It would only see the a_dictionary_object
identifier name.
Therefore the real result would rather be:
a_dictionary_object definition_1 = text_1
a_dictionary_object definition_2 = text_2
a_dictionary_object etc = etc.
a_dictionary_object key_3 = value_3
a_dictionary_object key_4 = value_4
a_dictionary_object etc = etc.
......
......
......
a_dictionary_object random_n = random_n
a_dictionary_object etc = etc.
So, the reverse of the eval()
function won't be that useful in this case.
Currently, one would need to do this:
# main2.py same as above, except:
for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
'some_other_dictionary_2',
'...',
'some_other_dictionary_n' ):
some_module2.some_function( { each_one_of_my_dictionaries_names :
eval(each_one_of_my_dictionaries_names) } )
# some_module2.py
def some_function(a_dictionary_name_object_container):
for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
for _key, _value in _dictionary_object.items():
print( str(_dictionary_name) +
" " +
str(_key) +
" = " +
str(_value) )
######
eval()
function if the name identifier is available in the current namespace.eval()
function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.This can be achieved by passing both the 'string'
and eval('string')
to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval()
function which may easily lead to unsecured code. Care must be taken to not feed the eval()
function with just about anything, especially unfiltered external-input data.
The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.
import arrow
def cleanWay(oneDate):
if currentDate.date().day > 25:
return currentDate.replace(months=+1,day=1)
else:
return currentDate.replace(day=1)
currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.
25-Feb-2017 01-Feb-2017
28-Feb-2017 01-Mar-2017
If this occurs IE intranet only, check compatibility settings and uncheck "Display intranet sites in Compatibility mode" .
IE-->settings-->compatibility
You can use rownum :
SELECT * FROM table WHERE rownum > 10 and rownum <= 20
You can run this in powershell:
[System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile
Which outputs this for .net 4:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
Note however that this might change depending on whether .net is running as 32 or 64 bit which will result in \Framework\
or \Framework64\
respectively.
Ditch the <a href="...">
. Put the onclick
(all lowercase) handler on the <li>
tag itself.
If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).
If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).
So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).
See the "Color" documentation for the supported formats.
Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
I also had this problem, and none of the solutions in this thread worked for me. As it turns out, the problem was that I had this line in ~/.bash_profile
:
alias php="/usr/local/php/bin/php"
And, as it turns out, /usr/local/php
was just a symlink to /usr/local/Cellar/php54/5.4.24/
. So when I invoked php -i
I was still invoking php54. I just deleted this line from my bash profile, and then php worked.
For some reason, even though php55 was now running, the php.ini
file from php54 was still loaded, and I received this warning every time I invoked php:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so' - dlopen(/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so, 9): image not found in Unknown on line 0
To fix this, I just added the following line to my bash profile:
export PHPRC=/usr/local/etc/php/5.5/php.ini
And then everything worked as normal!
reverse the string and then, in a second pass, reverse each word...
in c#, completely in-place without additional arrays:
static char[] ReverseAllWords(char[] in_text)
{
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);
//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}
return in_text;
}
static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}
Ud_an's solution with updated API's
Note: LatLng class is part of Google Play Services.
Mandatory:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.
public LatLng getLocationFromAddress(Context context,String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
// May throw an IOException
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (IOException ex) {
ex.printStackTrace();
}
return p1;
}
In Swift 3. You may use custom UITextField with indent that is set in its constructor. Don't need for extra declaration in a controller.
class CustomTextField : UITextField {
private let indentView = UIView(frame: CGRect(x: 0, y:0, width: 10, height: 10))
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.leftView = indentView
self.leftViewMode = .always
}
}
Where does the variable results come from?
This block:
foreach (People p in ppl.results) {
list.Add(results.name);
list.Add(results.email);
list2d.Add(list);
}
Should probably read more like:
foreach (People p in ppl.results) {
var list = new List<string>();
list.Add(p.name);
list.Add(p.email);
list2d.Add(list);
}
Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.
HTML
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
</a></div>
CSS
.navbar-toggle, .icon-bar {
border:1px solid orange;
}
BOOM...
Here are some other solutions. No need to use additional plugins.
Snippets down below uses .subtract
API and requires moment 2.1.0+
Snippets are also available in here https://jsfiddle.net/traBolic/ku5cyrev/
Formatting with the .format
API:
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
const inMilliseconds = duration.asMilliseconds();
// "mm:ss:SS" will include milliseconds
console.log(moment.utc(inMilliseconds).format("HH[h]:mm[m]:ss[s]"));
if (inMilliseconds !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
Manuel formatting by .hours
, .minutes
and .seconds
API in a template string
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
console.log(`${duration.hours()}h:${duration.minutes()}m:${duration.seconds()}s`);
// `:${duration.milliseconds()}` to add milliseconds
if (duration.asMilliseconds() !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
Just this command is enough to do the magic on centos 6.6
mysql_install_db
Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.
# list all containers
$ docker ps -a
$ docker stop docker101tutorial
# Use grep or rg to get Id of container
$ docker inspect docker101tutorial | grep -i id
"Id": "sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb",
# run plain ubuntu docker image with shell and change it's namespace to docker host
# https://stackoverflow.com/questions/60408574/how-to-access-var-lib-docker-in-windows-10-docker-desktop/60411313#60411313
# https://forums.docker.com/t/the-location-of-images-in-docker-for-windows/19647/4
$ docker run -it --privileged --pid=host ubuntu nsenter -t 1 -m -u -i sh
# We want to find out the directory of docker101tutorial container. We are looking for:
# `"Image":"sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb"`
# in /var/lib/docker/containers/*/config.v2.json
$ grep -rl --include=config.v2.json fff0a4b22d /var/lib/docker/containers/
/var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/config.v2.json
# edit it
$ vi /var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/hostconfig.json
i
for insert mode."HostPort":"80"
to "HostPort":"8092"
Escape
and write :wq
. Press Enter
.docker101tutorial
now. Otherwise changes to HostPort
will be reverted.8092
.8092
on host.Based on @holdfenytolvaj answer.
A matrix is really just a vector with a dim
attribute (for the dimensions). So you can add dimensions to vec
using the dim()
function and vec
will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49
Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.
I like to use:
make --debug=j
https://linux.die.net/man/1/make
--debug[=FLAGS]
Print debugging information in addition to normal processing. If the FLAGS are omitted, then the behavior is the same as if -d
was specified. FLAGS may be a for all debugging output (same as using -d
), b
for basic debugging, v
for more verbose basic debugging, i
for showing implicit rules, j
for details on invocation of commands, and m
for debugging while remaking makefiles.
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
(this is a simplified explanation, ignoring issues of scope etc.)
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
I'd suggest looking at the source to something like lighthttpd.
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
This was for my own project and I'm sharing it here too.
This one had trouble after 3.2, so the one below may work better for you:
CSS
/* adjust body when menu is open */
body.slide-active {
overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
position: relative;
padding-top: 70px;
left: 0;
}
#page-content.slide-active {
padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
cursor: pointer;
position: relative;
line-height: 0;
float: left;
margin: 0;
width: 30px;
height: 40px;
padding: 10px 0 0 0;
border: 0;
background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
width: 100%;
display: block;
height: 3px;
margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
background: orange
}
.navbar-header {
position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) {
#slide-nav .container {
margin: 0;
padding: 0!important;
}
#slide-nav .navbar-header {
margin: 0 auto;
padding: 0 15px;
}
#slide-nav .navbar.slide-active {
position: absolute;
width: 80%;
top: -1px;
z-index: 1000;
}
#slide-nav #slidemenu {
background: #f7f7f7;
left: -100%;
width: 80%;
min-width: 0;
position: absolute;
padding-left: 0;
z-index: 2;
top: -8px;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav {
min-width: 0;
width: 100%;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
min-width: 0;
width: 80%;
white-space: normal;
}
#slide-nav {
border-top: 0
}
#slide-nav.navbar-inverse #slidemenu {
background: #333
}
/* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
#slide-nav #navbar-height-col {
position: fixed;
top: 0;
height: 100%;
width: 80%;
left: -80%;
background: #eee;
}
#slide-nav.navbar-inverse #navbar-height-col {
background: #333;
z-index: 1;
border: 0;
}
#slide-nav .navbar-form {
width: 100%;
margin: 8px 0;
text-align: center;
overflow: hidden;
/*fast clearfixer*/
}
#slide-nav .navbar-form .form-control {
text-align: center
}
#slide-nav .navbar-form .btn {
width: 100%
}
}
@media (min-width:768px) {
#page-content {
left: 0!important
}
.navbar.navbar-fixed-top.slide-active {
position: fixed
}
.navbar-header {
left: 0!important
}
}
HTML
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
<div class="container">
<div class="navbar-header">
<a class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="slidemenu">
<form class="navbar-form navbar-right" role="form">
<div class="form-group">
<input type="search" placeholder="search" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link test long title goes here</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
jQuery
$(document).ready(function () {
//stick in the fixed 100% height behind the navbar but don't wrap it
$('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));
// Enter your ids or classes
var toggler = '.navbar-toggle';
var pagewrapper = '#page-content';
var navigationwrapper = '.navbar-header';
var menuwidth = '100%'; // the menu inside the slide menu itself
var slidewidth = '80%';
var menuneg = '-100%';
var slideneg = '-80%';
$("#slide-nav").on("click", toggler, function (e) {
var selected = $(this).hasClass('slide-active');
$('#slidemenu').stop().animate({
left: selected ? menuneg : '0px'
});
$('#navbar-height-col').stop().animate({
left: selected ? slideneg : '0px'
});
$(pagewrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(navigationwrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(this).toggleClass('slide-active', !selected);
$('#slidemenu').toggleClass('slide-active');
$('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');
});
var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';
$(window).on("resize", function () {
if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
$(selected).removeClass('slide-active');
}
});
});
Try this
<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>
Or just use the command line command:
Eventcreate
Why not use index or rindex?
array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')
index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index
rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex
Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!
I had the same issue now:
Solved it by:
Just reloading the local weblink in which the Python is running
http://localhost:8888/notebooks/sec%201/Untitled.ipynb
Well, everyone seems to put his one-liner here so here goes mine:
const encoded = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.
This script is now slightly edited to support command line args.
@echo off
:: BatchGotAdmin
::-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
::--------------------------------------
::ENTER YOUR CODE BELOW:
According to WikiPedia, you can specify which favicon file to load using the link
tag in the head
section, with a parameter of rel="icon"
.
For example:
<link rel="icon" type="image/png" href="/path/image.png">
I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.
You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.
This should work:
$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`
Here is a safe and reusable function for adding script to head section if its not already exist there.
see working example here: Example
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<style>
</style>
</head>
<body>
<input type="button" id="" style='width:250px;height:50px;font-size:1.5em;' value="Add Script" onClick="addScript('myscript')"/>
<script>
function addScript(filename)
{
// house-keeping: if script is allready exist do nothing
if(document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
{
alert("script is allready exist in head tag!")
}
else
{
// add the script
loadScript('/',filename + ".js");
}
}
function loadScript(baseurl,filename)
{
var node = document.createElement('script');
node.src = baseurl + filename;
document.getElementsByTagName('head')[0].appendChild(node);
alert("script added");
}
</script>
</body>
</html>
$('title').text();
returns all the title
but if you just want the page title then use
document.title
You can just give your top child view (the TextView @+id/TextView) an attribute:
android:layout_weight="1"
.
This will force all other elements below it to the bottom.
Currently (on 2018/04/23), you need to download a development release. The GA ones do not work.
I was not able to connect with the latest GA version (6.3.10).
It worked with mysql-workbench-community-8.0.11-rc-winx64.msi
(from https://dev.mysql.com/downloads/workbench/, tab Development Releases).
A slightly less verbose way of declaring named enumerations:
object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
type WeekDay = Value
val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}
WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString // returns Fri
Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.
There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)
So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.
[RoutePrefix("api/customers")]
public class MyController : Controller
{
[HttpGet]
public List<Customer> Get()
{
//gets all customer logic
}
[HttpGet]
[Route("currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer
}
[HttpGet]
[Route("{id}")]
public Customer GetCustomerById(string id)
{
//gets a single customer by specified id
}
[HttpGet]
[Route("customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
//gets customer by its username
}
}
You need multiple LIKE clauses connected by OR.
SELECT * FROM table WHERE
column LIKE 'Text%' OR
column LIKE 'Link%' OR
column LIKE 'Hello%' OR
column LIKE '%World%' OR
I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden
, so when setting my pictures to width: 100%
the pictures would look vertically cut, and so I forced them to be visible with !important
and to avoid showing the slide animation out of the box I set overflow: hidden
to the container div of the slide. Hope it works for you.
UPDATE - New Solution:
Original problem -> http://jsfiddle.net/xMddf/1/
(Even if I use overflow-y: visible
it becomes "auto" and actually "scroll".)
#content {
height: 100px;
width: 200px;
overflow-x: hidden;
overflow-y: visible;
}
The new solution -> http://jsfiddle.net/xMddf/2/
(I found a workaround using a wrapper div to apply overflow-x
and overflow-y
to different DOM elements as James Khoury advised on the problem of combining visible
and hidden
to a single DOM element.)
#wrapper {
height: 100px;
overflow-y: visible;
}
#content {
width: 200px;
overflow-x: hidden;
}
The trick is a second .box-inner
inside, which is larger in width than the original .box
, and the box-shadow
is applied to that.
Then, added more padding to the .text
to make up for the added width.
Use max width for .inner-box
to not cause .box
to get wider, and overflow
to make sure the remaining is clipped:
.box {
max-width: 100% !important;
overflow: hidden;
}
110% is wider than the parent which is 100% in a child's context (should be the same when the parent .box
has a fixed width, for example).
Negative margins make up for the width and cause the element to be centered (instead of only the right part hiding):
.box-inner {
width: 110%;
margin-left:-5%;
margin-right: -5%;
-webkit-box-shadow: inset 0px 5px 10px 1px #000000;
box-shadow: inset 0px 5px 10px 1px #000000;
}
And add some padding on the X axis to make up for the wider .inner-box
:
.text {
padding: 20px 40px;
}
If you inspect the Fiddle, you'll see:
The easiest solution would be in CSS. Add something like...
.dropdown:hover .dropdown-menu {
display: block;
margin-top: 0; // remove the gap so it doesn't close
}
As from Android developer guide :
"orientation" The screen orientation has changed — the user has rotated the device. Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.
"screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). Added in API level 13.
So, in the AndroidManifest.xml file, we can put:
<activity
android:name=".activities.role_activity.GeneralViewPagerActivity"
android:label="@string/title_activity_general_view_pager"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
>
</activity>
Isn't the 'date' command much simpler? No need for awk, stat, etc.
date -r <filename>
Also, consider looking at the man page for date formatting; for example with common date and time format:
date -r <filename> "+%m-%d-%Y %H:%M:%S"
This works pretty well
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");
foreach (String s in list)
{
Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}
O(1) means the time to access something is independent of the number of items in the collection.
O(N) would mean the time to access an item is a proportional to the number (N) of items in the collection.
That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.
What you should do is;
You're ready to go.
In your Django view,
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes
@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):
def post(self, request, format=None):
thumbnail = request.FILES["file"]
info = json.loads(request.data['info'])
...
return HttpResponse()
This works with my IP camera:
import cv2
#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")
while True:
#print('About to start the Read command')
ret, frame = cap.read()
#print('About to show frame of Video.')
cv2.imshow("Capturing",frame)
#print('Running..')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I found the Stream URL in the Camera's Setup screen:
Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)
There 3 functions you want to look at here:
I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:
=LARGE($B$2:$B$11, A13)
=INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
Just to clarify what yalestar said, this will give you the relative path:
Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"
Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.
For example, I have a DEV_DB tablespace with all my actual 'databases' within them:
SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;
Resulting in:
SYSTEM SYSAUX UNDOTBS1 TEMP USERS EXAMPLE DEV_DB
It is also possible to query the users in all tablespaces:
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;
Or within a specific tablespace (using my DEV_DB tablespace as an example):
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';
ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB
Swift 3 & IOS 10.2
UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
Swift 3 & IOS 10.2
If you are looking to reduce the size using coding itself, you can follow this code in php.
<?php
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = 'source.jpg';
$destination_img = 'destination .jpg';
$d = compress($source_img, $destination_img, 90);
?>
$d = compress($source_img, $destination_img, 90);
This is just a php function that passes the source image ( i.e., $source_img
), destination image ( $destination_img
) and quality for the image that will take to compress ( i.e., 90 ).
$info = getimagesize($source);
The getimagesize()
function is used to find the size of any given image file and return the dimensions along with the file type.
I think there may be problem that you haven't added click listener for ok positive button.
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Templates (<template>
, or <ng-template>
since 4.x) are added as embedded views and get passed a context.
With let-col
the context property $implicit
is made available as col
within the template for bindings.
With let-foo="bar"
the context property bar
is made available as foo
.
For example if you add a template
<ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
See also this answer and ViewContainerRef#createEmbeddedView.
*ngFor
also works this way. The canonical syntax makes this more obvious
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
where NgFor
adds the template as embedded view to the DOM for each item
of items
and adds a few values (item
, index
, odd
) to the context.
IMHO, fs.readFile()
should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.
The easiest way to read a text file is to read it line by line. I recommend a BufferedReader:
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();
For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).
-O
is the option to specify the path of the file you want to download to:
wget <uri> -O /path/to/file.ext
-P
is prefix where it will download the file in the directory:
wget <uri> -P /path/to/folder
if you want to use truncate
use this:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table $table_name;
SET FOREIGN_KEY_CHECKS = 1;
You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
Using keySet-
id1.keySet().stream()
.filter(x -> x == 1)
.map(x -> id1.get(x))
.collect(Collectors.toList())
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
To add the myriad of other potential sources... I had updated all the libraries in my project's lib
folder but then Eclipse "helpfully" reinstalled all the original libraries. There was no longer any reference inside Eclipse to these libraries but the external dex-maker program just grabbed all the files in the lib
directory and thus got two versions of several library .jar
files.
git status
identified the new files and git clean -f
got rid of them for me (though I sometimes had to wait or restart Eclipse on Windows because it still had the files open from the copy).
awk is very cool, but why not keep it simple?
num=$(echo $var | grep -o "," | wc -l)
here is a simple function to seperate multiple words and numbers from a string of any length, the re method only seperates first two words and numbers. I think this will help everyone else in the future,
def seperate_string_number(string):
previous_character = string[0]
groups = []
newword = string[0]
for x, i in enumerate(string[1:]):
if i.isalpha() and previous_character.isalpha():
newword += i
elif i.isnumeric() and previous_character.isnumeric():
newword += i
else:
groups.append(newword)
newword = i
previous_character = i
if x == len(string) - 2:
groups.append(newword)
newword = ''
return groups
print(seperate_string_number('10in20ft10400bg'))
# outputs : ['10', 'in', '20', 'ft', '10400', 'bg']
Non-python data is best bundled inside your Python modules using the package_data
support in setuptools. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in com.yourcompany.yourproject
(and being able to have a shared com.yourcompany.utils
namespace).
Re branching and merging, if you use a good enough source control system it will handle merges even through renames; Bazaar is particularly good at this.
Contrary to some other answers here, I'm +1 on having a src
directory top-level (with doc
and test
directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; Sphinx, for instance, has its own conventions which its quickstart tool supports.
Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using package_data
).
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
Here is the best way to find out Foreign Key Relationship in all Database.
exec sp_helpconstraint 'Table Name'
and one more way
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME='Table Name'
--and left(CONSTRAINT_NAME,2)='FK'(If you want single key)
You must know the full path of your angular installation. For example: C:\Users\\AppData\Roaming\npm\node_modules@angular\cli\bin\ng . Type in cmd, powershell or bash
alias ng="C:\Users\<your username>\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng"
The Array.prototype
property represents the prototype for the Array
constructor and allows you to add new properties
and methods
to all Array
objects. we can create a prototype for this purpose
Array.prototype.has_element = function(element) {
return $.inArray( element, this) !== -1;
};
And then use it like this
var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false
See the Demo below
Array.prototype.has_element = function(element) {_x000D_
return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Try "vash" - asp.net mvc like razor syntax for node.js
https://github.com/kirbysayshi/Vash
also checkout: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
// sample
var tmpl = vash.compile('<hr/>@model.a,@model.b<hr/>');
var html = tmpl({"a": "hello", "b": "world"});
res.write(html);
Found a comparison of the 2 techniques (query string vs file name) here:
Version as a querystring has two problems.
First, it may not always be a browser that implements caching through which we need to bust. It is said that certain (possibly older) proxies do ignore the querystring with respect to their caching behavior.
Second, in certain more complex deployment scenarios, where you have multiple frontend and/or multiple backend servers, an upgrade is anything but instantaneous. You need to be able to serve both the old and the new version of your assets at the same time. See for example how this affects you when using Google App Engine.
Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);