EDIT: This answer is correct for version 0.2.10
. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14
.
Another reason to use $state.params
is when you need to extract query parameters like this:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/?yetAnotherParam',
controller: 'ACtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
You can change the labels' text by adorning the property with the DisplayName
attribute.
[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }
Or, you could write the raw HTML explicitly:
<label for="SomekingStatus" class="control-label">Someking Status</label>
From the source code you will be able to view that, ExpectedConditions.elementToBeClickable()
, it will judge the element visible and enabled, so you can use isEnabled()
together with isDisplayed()
. Following is the source code.
public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) {_x000D_
return new ExpectedCondition() {_x000D_
public WebElement apply(WebDriver driver) {_x000D_
WebElement visibleElement = (WebElement) ExpectedConditions.visibilityOf(element).apply(driver);_x000D_
_x000D_
try {_x000D_
return visibleElement != null && visibleElement.isEnabled() ? visibleElement : null;_x000D_
} catch (StaleElementReferenceException arg3) {_x000D_
return null;_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "element to be clickable: " + element;_x000D_
}_x000D_
};_x000D_
}
_x000D_
I managed to fix this by changing settings for new projects:
File -> New Projects Settings -> Settings for New Projects -> Java Compiler -> Set the version
File -> New Projects Settings -> Structure for New Projects -> Project -> Set Project SDK + set language level
Remove the projects
Import the projects
Unless you set Node_PATH, the only other option is to install express in the app directory, like npm install express --save
.
Express may already be installed but node
cannot find it for some reason
It will depend on your environment. If you're running a Swing UI via javaw
for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java
:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in
, which you may want to wrap in a BufferedReader
to read lines, or use Scanner
(again wrapping System.in
).
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue
So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;
public class URLEncodeSample {
public static void main( String [] args ) throws Throwable {
System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
}
}
C:\oreyes\samples\java\URL>javac URLEncodeSample.java
C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
As expected.
What would be the problem with this?
System.exit()
is usually not the best way, but it depends on your application.
The usual way of ending an application is by exiting the main()
method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don't know if that is possible with the AWT or Swing), or invoke System.exit()
.
Let's try to take an example and understand:
I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.
Where Y <commit-id> = <master> branch commits - few commits
Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:
Step 1:
git checkout -b local origin/new
where local is the branch name. Any name can be given.
Step 2:
git merge origin/master --no-ff --stat -v --log=300
Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.
For more information and parameters about Git merge, please refer to:
git merge --help
Also if you need to merge a specific commit, then you can use:
git cherry-pick <commit-id>
Oh. I think you're writing the workbook out 944,000 times. Your wb.write(bos) call is in the inner loop. I'm not sure this is quite consistent with the semantics of the Workbook class? From what I can tell in the Javadocs of that class, that method writes out the entire workbook to the output stream specified. And it's gonna write out every row you've added so far once for every row as the thing grows.
This explains why you're seeing exactly 1 row, too. The first workbook (with one row) to be written out to the file is all that is being displayed - and then 7GB of junk thereafter.
if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the &&
will only be executed if the previous command does not set errorlevel. If mkdir
fails, xcopy
is not executed.
I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions.
I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything.
Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow.
I call it like so:
select delete_cascade('public','my_table','1');
create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
returns integer as $$
declare
rx record;
rd record;
v_sql varchar;
v_recursion_key varchar;
recnum integer;
v_primary_key varchar;
v_rows integer;
begin
recnum := 0;
select ccu.column_name into v_primary_key
from
information_schema.table_constraints tc
join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
and tc.constraint_type='PRIMARY KEY'
and tc.table_name=p_table
and tc.table_schema=p_schema;
for rx in (
select kcu.table_name as foreign_table_name,
kcu.column_name as foreign_column_name,
kcu.table_schema foreign_table_schema,
kcu2.column_name as foreign_table_primary_key
from information_schema.constraint_column_usage ccu
join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema
join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
where ccu.table_name=p_table and ccu.table_schema=p_schema
and TC.CONSTRAINT_TYPE='FOREIGN KEY'
and tc2.constraint_type='PRIMARY KEY'
)
loop
v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
--raise notice '%',v_sql;
--found a foreign key, now find the primary keys for any data that exists in any of those tables.
for rd in execute v_sql
loop
v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
if (v_recursion_key = any (p_recursion)) then
--raise notice 'Avoiding infinite loop';
else
--raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
end if;
end loop;
end loop;
begin
--actually delete original record.
v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
execute v_sql;
get diagnostics v_rows= row_count;
--raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
recnum:= recnum +v_rows;
exception when others then recnum=0;
end;
return recnum;
end;
$$
language PLPGSQL;
Remember to use the period because it tells git to grab all of the files.
This command will reset the head and unstage all of the changes:
$ git reset HEAD .
Then run this to restore all of the files:
$ git checkout .
Then doing a git status, you'll get:
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
I believe the problem is that codecs.BOM_UTF8
is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"
Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:
import codecs
file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()
(That seems to give the right answer - a file with bytes EF BB BF.)
EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
Two lines of thinking, the speed it takes to find any match, versus the speed it takes to find all matches compared to the storage.
For the second case, I wanted to point out a GPU paralleled version which queries the socks for all matches.
If you have multiple properties for which to match, you can make use of grouped tuples and fancier zip iterators and the transform functions of thrust, for simplicity sake though here is a simple GPU based query:
//test.cu
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/count.h>
#include <thrust/remove.h>
#include <thrust/random.h>
#include <iostream>
#include <iterator>
#include <string>
// Define some types for pseudo code readability
typedef thrust::device_vector<int> GpuList;
typedef GpuList::iterator GpuListIterator;
template <typename T>
struct ColoredSockQuery : public thrust::unary_function<T,bool>
{
ColoredSockQuery( int colorToSearch )
{ SockColor = colorToSearch; }
int SockColor;
__host__ __device__
bool operator()(T x)
{
return x == SockColor;
}
};
struct GenerateRandomSockColor
{
float lowBounds, highBounds;
__host__ __device__
GenerateRandomSockColor(int _a= 0, int _b= 1) : lowBounds(_a), highBounds(_b) {};
__host__ __device__
int operator()(const unsigned int n) const
{
thrust::default_random_engine rng;
thrust::uniform_real_distribution<float> dist(lowBounds, highBounds);
rng.discard(n);
return dist(rng);
}
};
template <typename GpuListIterator>
void PrintSocks(const std::string& name, GpuListIterator first, GpuListIterator last)
{
typedef typename std::iterator_traits<GpuListIterator>::value_type T;
std::cout << name << ": ";
thrust::copy(first, last, std::ostream_iterator<T>(std::cout, " "));
std::cout << "\n";
}
int main()
{
int numberOfSocks = 10000000;
GpuList socks(numberOfSocks);
thrust::transform(thrust::make_counting_iterator(0),
thrust::make_counting_iterator(numberOfSocks),
socks.begin(),
GenerateRandomSockColor(0, 200));
clock_t start = clock();
GpuList sortedSocks(socks.size());
GpuListIterator lastSortedSock = thrust::copy_if(socks.begin(),
socks.end(),
sortedSocks.begin(),
ColoredSockQuery<int>(2));
clock_t stop = clock();
PrintSocks("Sorted Socks: ", sortedSocks.begin(), lastSortedSock);
double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
std::cout << "Time elapsed in ms: " << elapsed << "\n";
return 0;
}
//nvcc -std=c++11 -o test test.cu
Run time for 10 million socks: 9 ms
private string ToSeoFriendly(string title, int maxLength) {
var match = Regex.Match(title.ToLower(), "[\\w]+");
StringBuilder result = new StringBuilder("");
bool maxLengthHit = false;
while (match.Success && !maxLengthHit) {
if (result.Length + match.Value.Length <= maxLength) {
result.Append(match.Value + "-");
} else {
maxLengthHit = true;
// Handle a situation where there is only one word and it is greater than the max length.
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
}
match = match.NextMatch();
}
// Remove trailing '-'
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
return result.ToString();
}
Short ES6 code
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}
I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.
Just having final
will have the intended effect.
final int x = 5;
...
x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
JSTool is the best for stability.
Steps:
Reference:
Essentially, a List<>
in .NET is a wrapper over an array. A LinkedList<>
is a linked list. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to:
If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.
private void textBox_Enter(object sender, EventArgs e)
{
ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
}
private void textBox_Leave(object sender, EventArgs e)
{
ActiveForm.AcceptButton = null; // remove "return" button behavior
}
With Postgresql 9.5 it can be done by following-
UPDATE test
SET data = data - 'a' || '{"a":5}'
WHERE data->>'b' = '2';
OR
UPDATE test
SET data = jsonb_set(data, '{a}', '5'::jsonb);
Somebody asked how to update many fields in jsonb value at once. Suppose we create a table:
CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );
Then we INSERT a experimental row:
INSERT INTO testjsonb
VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');
Then we UPDATE the row:
UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';
Which does the following:
Selecting the data:
SELECT jsonb_pretty(object) FROM testjsonb;
Will result in:
jsonb_pretty
-------------------------
{ +
"a": 1, +
"c": { +
"c1": "see1", +
"c2": "see2", +
"c3": "see3", +
}, +
"d": 4 +
}
(1 row)
To update field inside, Dont use the concat operator ||
. Use jsonb_set instead. Which is not simple:
UPDATE testjsonb SET object =
jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');
Using the concat operator for {c,c1} for example:
UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';
Will remove {c,c2} and {c,c3}.
For more power, seek power at postgresql json functions documentation. One might be interested in the #-
operator, jsonb_set
function and also jsonb_insert
function.
There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.
I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.
Edit:
After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.
GMTL -
Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.
Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.
Eigen -
Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.
Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).
IMSL -
Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.
Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.
NT2 -
Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.
Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.
LAPACK -
Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.
Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.
Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.
read it in the docs.
If you return anything but an int
or None
it will be printed to stderr
.
To get just stderr while discarding stdout do:
output=$(python foo.py 2>&1 >/dev/null)
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
if you are using GIT for control versions and in some of yours commit you added db.sqlite3, GIT will keep some references of the database, so when you execute 'python manage.py migrate', this reference will be reflected on the new database. I recommend to execute the following command:
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch 'db.sqlite3' HEAD
it worked for me :)
std::string replace(std::string str, std::string substr1, std::string substr2)
{
for (size_t index = str.find(substr1, 0); index != std::string::npos && substr1.length(); index = str.find(substr1, index + substr2.length() ) )
str.replace(index, substr1.length(), substr2);
return str;
}
Short solution where you don't need any extra Libraries.
Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
See C# switch statement limitations - why?
Basically Switches cannot have evaluated statements in the case statement. They must be statically evaluated.
If you don't want to use a download manager then you can use this code
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition
, String mimetype, long contentLength) {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
try {
String address = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ Environment.DIRECTORY_DOWNLOADS + "/" +
fileName;
File file = new File(address);
boolean a = file.createNewFile();
URL link = new URL(url);
downloadFile(link, address);
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void downloadFile(URL url, String outputFileName) throws IOException {
try (InputStream in = url.openStream();
ReadableByteChannel rbc = Channels.newChannel(in);
FileOutputStream fos = new FileOutputStream(outputFileName)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
// do your work here
}
This will download files in the downloads folder in phone storage. You can use threads if you want to download that in the background (use thread.alive() and timer class to know the download is complete or not). This is useful when we download small files, as you can do the next task just after the download.
I am using Typescript with vue-property-decorator and what happened to me is that my IDE auto-completed "MyComponent.vue.js" instead of "MyComponent.vue". That got me this error.
It seems like the moral of the story is that if you get this error and you are using any kind of single-file component setup, check your imports in the router.
This solution is specific for laravel 5.5
You have to change permissions to a few folders: chmod -R -777 storage/logs chmod -R -777 storage/framework for the above folders 775 or 765 did not work for my project
chmod -R 775 bootstrap/cache
Also the ownership of the project folder should be as follows (current user):(web server user)
You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress
has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer
If you are currently not on branch master, that's super easy:
git branch -f master 1258f0d0aae
This does exactly what you want: It points master
at the given commit, and does nothing else.
If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:
git checkout 1258f0d0aae #detach from master
git branch -f master HEAD #exactly as above
#optionally reattach to master
git checkout master
Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f
!
This method is better than the git reset --hard
approach, as it does not destroy anything in the index or working directory.
I think what you may be thinking of is expressions
or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:
width:expression(document.body.clientWidth > 800? "800px": "auto" );
This code makes IE emulate the max-width
property it doesn't support.
All things considered, however, avoid using these. They are a bad, bad thing.
I recently had a similar problem. You can install node_modules
elsewhere and set the NODE_PATH
environment variable.
In the example below I installed node_modules
into /install
FROM node:0.12
RUN ["mkdir", "/install"]
ADD ["./package.json", "/install"]
WORKDIR /install
RUN npm install --verbose
ENV NODE_PATH=/install/node_modules
WORKDIR /worker
COPY . /worker/
redis:
image: redis
worker:
build: ./worker
command: npm start
ports:
- "9730:9730"
volumes:
- worker/:/worker/
links:
- redis
I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js
:
let test = {
foo () { return 'foo' },
bar () { return 'bar' },
baz () { return 'baz' }
}
export default test
All other code remains the same...
Use the map
method:
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
When PowerShell sees a command starting with a string it just evaluates the string, that is, it typically echos it to the screen, for example:
PS> "Hello World"
Hello World
If you want PowerShell to interpret the string as a command name then use the call operator (&) like so:
PS> & 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe'
After that you probably only need to quote parameter/argument pairs that contain spaces and/or quotation chars. When you invoke an EXE file like this with complex command line arguments it is usually very helpful to have a tool that will show you how PowerShell sends the arguments to the EXE file. The PowerShell Community Extensions has such a tool. It is called echoargs. You just replace the EXE file with echoargs - leaving all the arguments in place, and it will show you how the EXE file will receive the arguments, for example:
PS> echoargs -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data>
Arg 2 is <Source=mysource;Integrated>
Arg 3 is <Security=false;User>
Arg 4 is <ID=sa;Pwd=sapass!;Database=mydb;>
Arg 5 is <-dest:dbfullsql=Data>
Arg 6 is <Source=.\mydestsource;Integrated>
Arg 7 is <Security=false;User>
Arg 8 is <ID=sa;Pwd=sapass!;Database=mydb; computername=10.10.10.10 username=administrator password=adminpass>
Using echoargs you can experiment until you get it right, for example:
PS> echoargs -verb:sync "-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;"
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;>
It turns out I was trying too hard before to maintain the double quotes around the connection string. Apparently that isn't necessary because even cmd.exe will strip those out.
BTW, hats off to the PowerShell team. They were quite helpful in showing me the specific incantation of single & double quotes to get the desired result - if you needed to keep the internal double quotes in place. :-) They also realize this is an area of pain, but they are driven by the number of folks are affected by a particular issue. If this is an area of pain for you, then please vote up this PowerShell bug submission.
For more information on how PowerShell parses, check out my Effective PowerShell blog series - specifically item 10 - "Understanding PowerShell Parsing Modes"
UPDATE 4/4/2012: This situation gets much easier to handle in PowerShell V3. See this blog post for details.
AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line. Thus $1, $2...$n are references to the fields of each line ($1 is the first field, $2 is the second field, and so on...).
You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...".
Now consider the answer of Jürgen:
echo "1: " | awk -F ":" '/1/ {print $1}'
Above the field, boundaries are set by ":" so we have two fields $1 which is "1" and $2 which is the empty space. After comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression (I mean 1).
The output of the "echo" command is one line that contains "1", so the filter will work...
When dealing with the following example:
echo "1: " | awk '/1/ -F ":" {print $1}'
The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space, thus outputting "1:" as the first field and there will be not a second field!
The answer of Jürgen contains the good syntax...
It depends on the type of chip you are using, but nowerdays most chips you can write. It also depends on how much power you give your RFID device. To read you dont need allot of power and very little line of sight. To right you need them full insight and longer insight
echo "GenFiltEff=7.092200e-01" | cut -d "=" -f2
clear your cache and cookies in Safari, make sure your device is in provisioning profile and provisioning profile is installed on the device.
If everything mentioned above didn't help, try to create a new build with higher build number and try to distribute your app again
Here's another example that was tested, and will match search & replace patterns:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
Example use:
replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")
Here's an example that you could use :
var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
dddd : Full day Name
Do : day of the Month
MMMM : Full Month name
YYYY : 4 digits Year
For more informations :
Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.
<span style="font-size:1em;text-decoration:underline;">_x000D_
<span style="font-size:1.5em;">_x000D_
Text with big font size and thin underline_x000D_
</span>_x000D_
</span>
_x000D_
I have this error when compiling and bundling TS with WebPack. It compiles export class AppRouterElement extends connect(store, LitElement){....}
into let Sr = class extends (Object(wr.connect) (fn, vr)) {....}
which seems wrong because of missing comma. When bundling with Rollup, no error.
If you're interested in Linux: If you fish out the source code to "currentTimeMillis()", you'll see that, on Linux, if you call this method, it gets a microsecond time back. However Java then truncates the microseconds and hands you back milliseconds. This is partly because Java has to be cross platform so providing methods specifically for Linux was a big no-no back in the day (remember that cruddy soft link support from 1.6 backwards?!). It's also because, whilst you clock can give you back microseconds in Linux, that doesn't necessarily mean it'll be good for checking the time. At microsecond levels, you need to know that NTP is not realigning your time and that your clock has not drifted too much during method calls.
This means, in theory, on Linux, you could write a JNI wrapper that is the same as the one in the System package, but not truncate the microseconds.
I don't think you need/want the timeout.
onhover (hover) would be defined as the time period while "over" something. IMHO
onmouseover = start...
onmouseout = ...end
For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
Generally, this is how you open an OS folder containing a bunch of vdmk files on VMware Player.
the jnr-process project provides this capability.
It is part of the java native runtime used by jruby and can be considered a prototype for a future java-FFI
I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.
import sys
import time
from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
QThreadPool, pyqtSignal)
# Subclassing QThread
# http://qt-project.org/doc/latest/qthread.html
class AThread(QThread):
def run(self):
count = 0
while count < 5:
time.sleep(1)
print("A Increasing")
count += 1
# Subclassing QObject and using moveToThread
# http://blog.qt.digia.com/blog/2007/07/05/qthreads-no-longer-abstract
class SomeObject(QObject):
finished = pyqtSignal()
def long_running(self):
count = 0
while count < 5:
time.sleep(1)
print("B Increasing")
count += 1
self.finished.emit()
# Using a QRunnable
# http://qt-project.org/doc/latest/qthreadpool.html
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QRunnable):
def run(self):
count = 0
app = QCoreApplication.instance()
while count < 5:
print("C Increasing")
time.sleep(1)
count += 1
app.quit()
def using_q_thread():
app = QCoreApplication([])
thread = AThread()
thread.finished.connect(app.exit)
thread.start()
sys.exit(app.exec_())
def using_move_to_thread():
app = QCoreApplication([])
objThread = QThread()
obj = SomeObject()
obj.moveToThread(objThread)
obj.finished.connect(objThread.quit)
objThread.started.connect(obj.long_running)
objThread.finished.connect(app.exit)
objThread.start()
sys.exit(app.exec_())
def using_q_runnable():
app = QCoreApplication([])
runnable = Runnable()
QThreadPool.globalInstance().start(runnable)
sys.exit(app.exec_())
if __name__ == "__main__":
#using_q_thread()
#using_move_to_thread()
using_q_runnable()
This is a great help. The code
UPDATE tbl_b b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM tbl_a a
WHERE b.id = 1
AND a.id = b.id;
works perfectly.
noted that you need a bracket "" in
From "tbl_a" a
to make it work.
If you want to use std::string
reliably, you must #include <string>
.
Also using query builder
DB::table("rates")->get()->sum("rate_value")
To get summation of all rate value inside table rates.
To get summation of user products.
DB::table("users")->get()->sum("products")
You can get an integer representation of your float by passing the float into the Integer initializer method.
Example:
Int(myFloat)
Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.
Just open file by nano /file_name
Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.
Here CTRL+O : is CTRL and O for Orange Not 0 Zero
For Windows users who want to use neovim with the Windows Subsystem for Linux:
git config core.editor "C:/Windows/system32/bash.exe --login -c 'nvim .git/COMMIT_EDITMSG'"
This is not a fool-proof solution as it doesn't handle interactive rebasing (for example). Improvements very welcome!
try this method, working fine for me
position: absolute;
left: 50%;
transform: translateX(-50%);
I have put something like this in my Controller class and it worked:
IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).
I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt
1.7 TTY info in /proc/tty
-------------------------
Information about the available and actually used tty's can be found in the
directory /proc/tty.You'll find entries for drivers and line disciplines in
this directory, as shown in Table 1-11.
Table 1-11: Files in /proc/tty
..............................................................................
File Content
drivers list of drivers and their usage
ldiscs registered line disciplines
driver/serial usage statistic and status of single tty lines
..............................................................................
To see which tty's are currently in use, you can simply look into the file
/proc/tty/drivers:
> cat /proc/tty/drivers
pty_slave /dev/pts 136 0-255 pty:slave
pty_master /dev/ptm 128 0-255 pty:master
pty_slave /dev/ttyp 3 0-255 pty:slave
pty_master /dev/pty 2 0-255 pty:master
serial /dev/cua 5 64-67 serial:callout
serial /dev/ttyS 4 64-67 serial
/dev/tty0 /dev/tty0 4 0 system:vtmaster
/dev/ptmx /dev/ptmx 5 2 system
/dev/console /dev/console 5 1 system:console
/dev/tty /dev/tty 5 0 system:/dev/tty
unknown /dev/tty 4 1-63 console
Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
Check this snip out.
# reading the JSON data using json.load()
file = 'data.json'
with open(file) as train_file:
dict_train = json.load(train_file)
# converting json dataset from dictionary to dataframe
train = pd.DataFrame.from_dict(dict_train, orient='index')
train.reset_index(level=0, inplace=True)
Hope it helps :)
In my case I get the same error title could not resolve all dependencies for configuration
However suberror said, it was due to a linting jar not loaded with its url given saying status 502 received, I ran the deployment command again, this time it succeeded.
After save new file press
Ctrl-6
This is shortcut to alternate file
df.filter(regex='[A-CEG-I]') # does NOT depend on the column order
Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')
df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]
Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B']
, then you could replace 'A':'C'
above with 'A':'B'
.
And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:
df[['A','B','C','E','G','H','I']] # does NOT depend on the column order
A B C E G H I
0 -0.814688 -1.060864 -0.008088 2.697203 -0.763874 1.793213 -0.019520
1 0.549824 0.269340 0.405570 -0.406695 -0.536304 -1.231051 0.058018
2 0.879230 -0.666814 1.305835 0.167621 -1.100355 0.391133 0.317467
hive --version
hadoop version
There are mainly three types of variables in MySQL:
User-defined variables (prefixed with @
):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL
and a type of string.
SELECT @var_any_var_name
You can initialize a variable using SET
or SELECT
statement:
SET @start = 1, @finish = 10;
or
SELECT @start := 1, @finish := 10;
SELECT * FROM places WHERE place BETWEEN @start AND @finish;
User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.
User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.
They can be used in SELECT
queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE
before
accessing it.
They can be used as local variables and the input parameters inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT
clause is missing, the initial value is NULL
.
The scope of a local variable is the BEGIN ... END
block within
which it is declared.
Server System Variables (prefixed with @@
):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL
, SESSION
or BOTH
.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES
statement or SELECT @@var_name
.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT @@sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL
or SET SESSION
:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET @@global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET @@sort_buffer_size=1000000;
SET @@local.sort_buffer_size=10000;
You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.
dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};
No, you can't insert into multiple tables in one MySQL command. You can however use transactions.
BEGIN;
INSERT INTO users (username, password)
VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage)
VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;
Have a look at LAST_INSERT_ID()
to reuse autoincrement values.
Let me elaborate: there are 3 possible ways here:
In the code you see above. This
does it all in MySQL, and the
LAST_INSERT_ID()
in the second
statement will automatically be the
value of the autoincrement-column
that was inserted in the first
statement.
Unfortunately, when the second statement itself inserts rows in a table with an auto-increment column, the LAST_INSERT_ID()
will be updated to that of table 2, and not table 1. If you still need that of table 1 afterwards, we will have to store it in a variable. This leads us to ways 2 and 3:
Will stock the LAST_INSERT_ID()
in
a MySQL variable:
INSERT ...
SELECT LAST_INSERT_ID() INTO @mysql_variable_here;
INSERT INTO table2 (@mysql_variable_here, ...);
INSERT INTO table3 (@mysql_variable_here, ...);
Will stock the LAST_INSERT_ID()
in a
php variable (or any language that
can connect to a database, of your
choice):
INSERT ...
LAST_INSERT_ID()
, either by executing that literal statement in MySQL, or using for example php's mysql_insert_id()
which does that for youINSERT [use your php variable here]
Whatever way of solving this you choose, you must decide what should happen should the execution be interrupted between queries (for example, your database-server crashes). If you can live with "some have finished, others not", don't read on.
If however you decide "either all queries finish, or none finish - I do not want rows in some tables but no matching rows in others, I always want my database tables to be consistent", you need to wrap all statements in a transaction. That's why I used the BEGIN
and COMMIT
here.
Comment again if you need more info :)
Note that according to the CSS3 spec, you do NOT have to wrap your layout in a table-style element. The browser will infer the existence of containing elements if they do not exist.
This worked for me
<input
(input)="$event.target.value = toSnakeCase($event.target.value)"
[(ngModel)]="table.name" />
In Typescript
toSnakeCase(value: string) {
if (value) {
return value.toLowerCase().replace(/[\W_]+/g, "");
}
}
Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.
conda -c conda-forge tensorflow
Then, it worked.
You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:
sudo chmod 777 markers.xml
You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.
The TextBox wasn't receiving the enter key at all in my situation. The first thing I tried was changing the enter key into an input key, but I was still getting the system beep when enter was pressed. So, I subclassed and overrode the ProcessDialogKey() method and sent my own event that I could bind the click handler to.
public class EnterTextBox : TextBox
{
[Browsable(true), EditorBrowsable]
public event EventHandler EnterKeyPressed;
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
EnterKeyPressed?.Invoke(this, EventArgs.Empty);
return true;
}
return base.ProcessDialogKey(keyData);
}
}
This is very old post but if anyone ran into similar problem and need quick answer:
listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
e.Clicks == 2
user
The maximum total length of a user name is 64 characters.
domain
Maximum of 255 characters in the domain part (the one after the “@”)
However, there is a restriction in RFC 2821 reading:
The maximum total length of a reverse-path or forward-path is 256 characters, including the punctuation and element separators”. Since addresses that don’t fit in those fields are not normally useful, the upper limit on address lengths should normally be considered to be 256, but a path is defined as: Path = “<” [ A-d-l “:” ] Mailbox “>” The forward-path will contain at least a pair of angle brackets in addition to the Mailbox, which limits the email address to 254 characters.
I am guessing you are trying to mix Asp code and JS code and at some point it's breaking or not excusing the binding calls correctly.
Perhaps you can try using a delegate instead. It will cut out the complexity of when to bind the click event.
An example would be:
$('body').delegate('.menu li','click',function(){
var $li = $(this);
var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;
if(shouldAddClass){
$li.addClass('active');
}
});
See if that helps, it uses the Attribute Starts With Selector from jQuery.
Chi
Compare returns 1, 0, -1 for greater than, equal to, less than, respectively.
You want:
if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(30)) <= 0)
{
bool matchFound = true;
}
//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");
//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);
//use location header to go back to index.html
header("Location:index.html");
I don't exactly know where u want to show the result.
You miss the class declaration.
public class DerivativeQuiz{
public static void derivativeQuiz(String args[]){ ... }
}
In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.
I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.
We have set up a solution for Team Foundation Server Source Control (not SourceSafe as you mention) similar to what Grant suggests; scheduled TF Get, Search Server Express. However the IFilter used for C# files (text) was not giving the results we wanted, so we convert source files to .htm files. We can now add additional meta-data to the files such as:
We would however prefer a protocolhandler for TFS Source Control, and a dedicated source code IFilter for a much more targeted solution.
_x000D_
_x000D_
.custom-modal-header_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
.custom-modal .modal-content_x000D_
{_x000D_
width:500px;_x000D_
border: none;_x000D_
}_x000D_
.custom-modal_x000D_
{_x000D_
display: block !important;_x000D_
}_x000D_
.custom-fade .modal-dialog {_x000D_
transform: translateY(4%);_x000D_
opacity: 0;_x000D_
-webkit-transition: all .2s ease-out;_x000D_
-o-transition: all .2s ease-out;_x000D_
transition: all .2s ease-out;_x000D_
will-change: transform;_x000D_
}_x000D_
.custom-fade.in .modal-dialog {_x000D_
opacity: 1;_x000D_
transform: translateY(0%);_x000D_
}
_x000D_
<div class="modal custom-modal custom-fade" tabindex="-1" role="dialog"_x000D_
aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<h5 class="modal-title">Title</h5>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>My cat is dope.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-primary" data-dismiss="modal">Sure (Meow)</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Update django-geoposition at least to version 0.2.3 and add this to settings.py:
GEOPOSITION_GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'
One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone
of your chosen upstream repo. So you have effectively a personal checkout
of everything, without putting some 'lock' on those files in the reference repo.
Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
For Mouse lovers! I say right click on resources folder and Add new resource file
, and from Available qualifiers select the orientation
:
But still you can do it manually by say, adding the sub-folder "layout-land" to
"Your-Project-Directory\app\src\main\res"
since then any layout.xml file under this sub-folder will only work for landscape mode automatically.
Use "layout-port" for portrait mode.
Instead of using $http.get('abc/xyz/getSomething') try to use $http.jsonp('abc/xyz/getSomething')
return{
getList:function(){
return $http.jsonp('http://localhost:8080/getNames');
}
}
Try this Code
var app = angular.module('myapp', []);
app.controller('testController', function ($scope, $http) {
$scope.init = function(){
alert($scope.testInput);
};});
<body ng-app="myapp">_x000D_
<div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
</div>_x000D_
</body>
_x000D_
Your code is, I'm sorry to say, very C-like.
A Java String
is not a char[]
. You say you want to remove duplicates from a String
, but you take a char[]
instead.
Is this char[]
\0
-terminated? Doesn't look like it because you take the whole .length
of the array. But then your algorithm tries to \0
-terminate a portion of the array. What happens if the arrays contains no duplicates?
Well, as it is written, your code actually throws an ArrayIndexOutOfBoundsException
on the last line! There is no room for the \0
because all slots are used up!
You can add a check not to add \0
in this exceptional case, but then how are you planning to use this code anyway? Are you planning to have a strlen
-like function to find the first \0
in the array? And what happens if there isn't any? (due to all-unique exceptional case above?).
What happens if the original String
/char[]
contains a \0
? (which is perfectly legal in Java, by the way, see JLS 10.9 An Array of Characters is Not a String)
The result will be a mess, and all because you want to do everything C-like, and in place without any additional buffer. Are you sure you really need to do this? Why not work with String
, indexOf
, lastIndexOf
, replace
, and all the higher-level API of String
? Is it provably too slow, or do you only suspect that it is?
"Premature optimization is the root of all evils". I'm sorry but if you can't even understand what the original code does, then figuring out how it will fit in the bigger (and messier) system will be a nightmare.
My minimal suggestion is to do the following:
String
, i.e. public static String removeDuplicates(String in)
char[] str = in.toCharArray();
return new String(str, 0, tail);
This does use additional buffers, but at least the interface to the rest of the system is much cleaner.
Alternatively, you can use StringBuilder
as such:
static String removeDuplicates(String s) {
StringBuilder noDupes = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String si = s.substring(i, i + 1);
if (noDupes.indexOf(si) == -1) {
noDupes.append(si);
}
}
return noDupes.toString();
}
Note that this is essentially the same algorithm as what you had, but much cleaner and without as many little corner cases, etc.
There is not a really pythonic way of repeating something. However, it is a better way:
map(lambda index:do_something(), xrange(10))
If you need to pass the index then:
map(lambda index:do_something(index), xrange(10))
Consider that it returns the results as a collection. So, if you need to collect the results it can help.
Use Form
, not form
. The capitalization counts.
You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.
So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.
RedirectMatch
uses a regular expression that is matched against the URL path. And your regular expression /contact.php
just means any URL path that contains /contact.php
but not just any URL path that is exactly /contact.php
. So use the anchors for the start and end of the string (^
and $)
:
RedirectMatch 301 ^/contact\.php$ /contact-us.php
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
I combined previous answers and used structure of Win32_PnPEntity class which can be found found here. Got solution like this:
using System.Management;
public static void Main()
{
GetPortInformation();
}
public string GetPortInformation()
{
ManagementClass processClass = new ManagementClass("Win32_PnPEntity");
ManagementObjectCollection Ports = processClass.GetInstances();
foreach (ManagementObject property in Ports)
{
var name = property.GetPropertyValue("Name");
if (name != null && name.ToString().Contains("USB") && name.ToString().Contains("COM"))
{
var portInfo = new SerialPortInfo(property);
//Thats all information i got from port.
//Do whatever you want with this information
}
}
return string.Empty;
}
SerialPortInfo class:
public class SerialPortInfo
{
public SerialPortInfo(ManagementObject property)
{
this.Availability = property.GetPropertyValue("Availability") as int? ?? 0;
this.Caption = property.GetPropertyValue("Caption") as string ?? string.Empty;
this.ClassGuid = property.GetPropertyValue("ClassGuid") as string ?? string.Empty;
this.CompatibleID = property.GetPropertyValue("CompatibleID") as string[] ?? new string[] {};
this.ConfigManagerErrorCode = property.GetPropertyValue("ConfigManagerErrorCode") as int? ?? 0;
this.ConfigManagerUserConfig = property.GetPropertyValue("ConfigManagerUserConfig") as bool? ?? false;
this.CreationClassName = property.GetPropertyValue("CreationClassName") as string ?? string.Empty;
this.Description = property.GetPropertyValue("Description") as string ?? string.Empty;
this.DeviceID = property.GetPropertyValue("DeviceID") as string ?? string.Empty;
this.ErrorCleared = property.GetPropertyValue("ErrorCleared") as bool? ?? false;
this.ErrorDescription = property.GetPropertyValue("ErrorDescription") as string ?? string.Empty;
this.HardwareID = property.GetPropertyValue("HardwareID") as string[] ?? new string[] { };
this.InstallDate = property.GetPropertyValue("InstallDate") as DateTime? ?? DateTime.MinValue;
this.LastErrorCode = property.GetPropertyValue("LastErrorCode") as int? ?? 0;
this.Manufacturer = property.GetPropertyValue("Manufacturer") as string ?? string.Empty;
this.Name = property.GetPropertyValue("Name") as string ?? string.Empty;
this.PNPClass = property.GetPropertyValue("PNPClass") as string ?? string.Empty;
this.PNPDeviceID = property.GetPropertyValue("PNPDeviceID") as string ?? string.Empty;
this.PowerManagementCapabilities = property.GetPropertyValue("PowerManagementCapabilities") as int[] ?? new int[] { };
this.PowerManagementSupported = property.GetPropertyValue("PowerManagementSupported") as bool? ?? false;
this.Present = property.GetPropertyValue("Present") as bool? ?? false;
this.Service = property.GetPropertyValue("Service") as string ?? string.Empty;
this.Status = property.GetPropertyValue("Status") as string ?? string.Empty;
this.StatusInfo = property.GetPropertyValue("StatusInfo") as int? ?? 0;
this.SystemCreationClassName = property.GetPropertyValue("SystemCreationClassName") as string ?? string.Empty;
this.SystemName = property.GetPropertyValue("SystemName") as string ?? string.Empty;
}
int Availability;
string Caption;
string ClassGuid;
string[] CompatibleID;
int ConfigManagerErrorCode;
bool ConfigManagerUserConfig;
string CreationClassName;
string Description;
string DeviceID;
bool ErrorCleared;
string ErrorDescription;
string[] HardwareID;
DateTime InstallDate;
int LastErrorCode;
string Manufacturer;
string Name;
string PNPClass;
string PNPDeviceID;
int[] PowerManagementCapabilities;
bool PowerManagementSupported;
bool Present;
string Service;
string Status;
int StatusInfo;
string SystemCreationClassName;
string SystemName;
}
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.
Assuming the input text is entered in terms of the users's local time:
var expires = moment(date).valueOf();
If the user is instructed actually enter a UTC date/time, then:
var expires = moment.utc(date).valueOf();
Xcode 8.2, iOS 10
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Require the JSON library, and use to_json
.
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(tempHash.to_json)
end
Your temp.json file now looks like:
{"key_a":"val_a","key_b":"val_b"}
Well, this is possible, and the other answers posted are perfectly valid, but you could take a brute force approach and prevent the default behavior of mousedown
on images. Which, is to start dragging the image.
Something like this:
window.onload = function () {
var images = document.getElementsByTagName('img');
for (var i = 0; img = images[i++];) {
img.ondragstart = function() { return false; };
}
};
Here's the Scalatest page on using the runner and the extended discussion on the -t
and -z
options.
This post shows what commands work for a test file that uses FunSpec
.
Here's the test file:
package com.github.mrpowers.scalatest.example
import org.scalatest.FunSpec
class CardiBSpec extends FunSpec {
describe("realName") {
it("returns her birth name") {
assert(CardiB.realName() === "Belcalis Almanzar")
}
}
describe("iLike") {
it("works with a single argument") {
assert(CardiB.iLike("dollars") === "I like dollars")
}
it("works with multiple arguments") {
assert(CardiB.iLike("dollars", "diamonds") === "I like dollars, diamonds")
}
it("throws an error if an integer argument is supplied") {
assertThrows[java.lang.IllegalArgumentException]{
CardiB.iLike()
}
}
it("does not compile with integer arguments") {
assertDoesNotCompile("""CardiB.iLike(1, 2, 3)""")
}
}
}
This command runs the four tests in the iLike
describe block (from the SBT command line):
testOnly *CardiBSpec -- -z iLike
You can also use quotation marks, so this will also work:
testOnly *CardiBSpec -- -z "iLike"
This will run a single test:
testOnly *CardiBSpec -- -z "works with multiple arguments"
This will run the two tests that start with "works with":
testOnly *CardiBSpec -- -z "works with"
I can't get the -t
option to run any tests in the CardiBSpec
file. This command doesn't run any tests:
testOnly *CardiBSpec -- -t "works with multiple arguments"
Looks like the -t
option works when tests aren't nested in describe
blocks. Let's take a look at another test file:
class CalculatorSpec extends FunSpec {
it("adds two numbers") {
assert(Calculator.addNumbers(3, 4) === 7)
}
}
-t
can be used to run the single test:
testOnly *CalculatorSpec -- -t "adds two numbers"
-z
can also be used to run the single test:
testOnly *CalculatorSpec -- -z "adds two numbers"
See this repo if you'd like to run these examples. You can find more info on running tests here.
For Linux: Simple you can run below commands:
1) git config -l
2) git config --global http.postBuffer 524288000
Or set double value 1048576000
3) git config --global https.postBuffer
4) git config --global core.compression -1
5) service apache2 restart
Then again check the config of git
git config -l
now you can run clone command
git clone yourrepo
I hope this will be solved the issue.
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
This will compile all *.c
files upon make
to executables without the .c
extension as in gcc program.c -o program
.
make
will automatically add any flags you add to CFLAGS
like CFLAGS = -g Wall
.
If you don't need any flags CFLAGS
can be left blank (as below) or omitted completely.
SOURCES = $(wildcard *.c)
EXECS = $(SOURCES:%.c=%)
CFLAGS =
all: $(EXECS)
You can check it with for example jQuery:
$("#elementID").css('display');
It will return string with information about display property of this element.
I use Butterknife with switch-case to handle this kind of cases:
@OnClick({R.id.button_bireysel, R.id.button_kurumsal})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button_bireysel:
//Do something
break;
case R.id.button_kurumsal:
//Do something
break;
}
}
But the thing is there is no default case and switch statement falls through
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
Redirect the page on itself and display the counter value on button click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Request.RawUrl.ToString()); // redirect on itself
Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
}
Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">
Or use your own css:
class="search-query input-mysize"
.input-mysize { width: 150px }
i'd suggest shorter and faster approach:
printf("%.2f", ((signed long)(fVal * 100) * 0.01f));
this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.
You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library
" - or whatever version is appropriate.
This code works for me:
private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
Sheets xlSheets = null;
Worksheet xlNewSheet = null;
try {
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
return;
// Uncomment the line below if you want to see what's happening in Excel
// xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlSheets = xlWorkbook.Sheets as Sheets;
// The first argument below inserts the new worksheet as the first one
xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = worksheetName;
xlWorkbook.Save();
xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
xlApp.Quit();
}
finally {
Marshal.ReleaseComObject(xlNewSheet);
Marshal.ReleaseComObject(xlSheets);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}
Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!
Some other links that I found useful when looking into this question:
According to MSDN
To use COM interop, you must have administrator or Power User security permissions.
Hope that helps.
It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .
Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?
Bootstrap leverages HTML5 standards in order to access DOM element attributes easily within javascript.
Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation that may be used by scripts. All such custom data are available via the HTMLElement interface of the element the attribute is set on. The HTMLElement.dataset property gives access to them.
As others have said, you can achieve this through an IFormatProvider. But bear in mind that currency formatting goes well beyond the currency symbol. For example a correctly-formatted price in the US may be "$ 12.50" but in France this would be written "12,50 $" (the decimal point is different as is the position of the currency symbol). You don't want to lose this culture-appropriate formatting just for the sake of changing the currency symbol. And the good news is that you don't have to, as this code demonstrates:
var cultureInfo = Thread.CurrentThread.CurrentCulture; // You can also hardcode the culture, e.g. var cultureInfo = new CultureInfo("fr-FR"), but then you lose culture-specific formatting such as decimal point (. or ,) or the position of the currency symbol (before or after)
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need
var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".
One solution is doing the sum:
=SUM(COUNTIFS(A1:A196,{"yes","no"},B1:B196,"agree"))
or know its not the countifs but the sumproduct will do it in one line:
=SUMPRODUCT(((A1:A196={"yes","no"})*(j1:j196="agree")))
There are two things you can do first undo merge by command
git merge --abort
or
you can go to your previous commit state temporarily by command
git checkout 0d1d7fc32
With next variant I have no reaction:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before
dialog.setContentView(R.layout.logindialog);
So, I try to use next:
dialog.supportRequestWindowFeature(Window.FEATURE_NO_TITLE); //before
dialog.setContentView(R.layout.logindialog);
This variant work excellent.
You can save String and custom array list using Gson library.
=>First you need to create function to save array list to SharedPreferences.
public void saveListInLocal(ArrayList<String> list, String key) {
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
=> You need to create function to get array list from SharedPreferences.
public ArrayList<String> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
=> How to call save and retrieve array list function.
ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
=> Don't forgot to add gson library in you app level build.gradle.
implementation 'com.google.code.gson:gson:2.8.2'
You can use Low Profile mode See here
Just search for SYSTEM_UI_FLAG_LOW_PROFILE
that also dims the navigation buttons if they are present of screen.
To understand get and set, it's all related to how variables are passed between different classes.
The get method is used to obtain or retrieve a particular variable value from a class.
A set value is used to store the variables.
The whole point of the get and set is to retrieve and store the data values accordingly.
What I did in this old project was I had a User class with my get and set methods that I used in my Server class.
The User class's get set methods:
public int getuserID()
{
//getting the userID variable instance
return userID;
}
public String getfirstName()
{
//getting the firstName variable instance
return firstName;
}
public String getlastName()
{
//getting the lastName variable instance
return lastName;
}
public int getage()
{
//getting the age variable instance
return age;
}
public void setuserID(int userID)
{
//setting the userID variable value
this.userID = userID;
}
public void setfirstName(String firstName)
{
//setting the firstName variable text
this.firstName = firstName;
}
public void setlastName(String lastName)
{
//setting the lastName variable text
this.lastName = lastName;
}
public void setage(int age)
{
//setting the age variable value
this.age = age;
}
}
Then this was implemented in the run()
method in my Server class as follows:
//creates user object
User use = new User(userID, firstName, lastName, age);
//Mutator methods to set user objects
use.setuserID(userID);
use.setlastName(lastName);
use.setfirstName(firstName);
use.setage(age);
buf.delete(0, buf.length());
If you use bower.json file to specify your dependencies:
{
"dependencies": {
...
"photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",
#bower 1.4 (tested with that version) can read repositorios with uri format
"photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",
}
}
Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)
Update, as the question description also mention using only a URL and no mention of a github repository.
Another example is to execute this command using the desired url, like:
bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S
that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel
if needed.
Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a
bower ENOTFOUND Package gmapV3MarkerWithLabel not found
Put it in a TRY/CATCH
.
When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block
Reference: MSDN.
EDIT: This works for MSSQL 2005+, but I see that you now have clarified that you are working on MSSQL 2000. I'll leave this here for reference.
What are you going to do with the URI?
If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.
HttpGet get = new HttpGet("http://stackoverflow.com");
By default, an inline definition is only valid in the current translation unit.
If the storage class is extern
, the identifier has external linkage and the inline definition also provides the external definition.
If the storage class is static
, the identifier has internal linkage and the inline definition is invisible in other translation units.
If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.
As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static
and static inline
function definitions.
The inline
specifier (like the register
storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.
inline
and register
are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline
definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register
-qualified variables.
Personally, I use the convention to mark static
function definitions within headers also inline
, as the main reason for putting function definitions in header files is to make them inlinable.
In general, I only use static inline
function and static const
object definitions in addition to extern
declarations within headers.
I've never written an inline
function with a storage class different from static
.
We found the asnwer of at techieshelp..its the htaccess thats the issue...
Demo : http://jsfiddle.net/NbGBj/
$("document").ready(function(){
$("#upload").change(function() {
alert('changed!');
});
});
As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)
Try launching after a click event
1) Don't use gets
! You're introducing a buffer-overflow vulnerability. Use fgets(..., stdin)
instead.
2) In strToLower
you're returning a char
instead of a char
-array. Either return char*
as Autopulated suggested, or just return void
since you're modifying the input anyway. As a result, just write
strToLower(cString1);
strToLower(cString2);
strcasecmp
(Linux & Mac) or stricmp
(Windows).If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.
In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.
Here is a skeleton of how the markup should look:
<ScrollViewer>
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Three slightly different answers depending how you look at the question:
1) Good enough for the exact question asked is Jonathan Leffler's solution, except that to round up to 16-aligned, you only need 15 extra bytes, not 16.
A:
/* allocate a buffer with room to add 0-15 bytes to ensure 16-alignment */
void *mem = malloc(1024+15);
ASSERT(mem); // some kind of error-handling code
/* round up to multiple of 16: add 15 and then round down by masking */
void *ptr = ((char*)mem+15) & ~ (size_t)0x0F;
B:
free(mem);
2) For a more generic memory allocation function, the caller doesn't want to have to keep track of two pointers (one to use and one to free). So you store a pointer to the 'real' buffer below the aligned buffer.
A:
void *mem = malloc(1024+15+sizeof(void*));
if (!mem) return mem;
void *ptr = ((char*)mem+sizeof(void*)+15) & ~ (size_t)0x0F;
((void**)ptr)[-1] = mem;
return ptr;
B:
if (ptr) free(((void**)ptr)[-1]);
Note that unlike (1), where only 15 bytes were added to mem, this code could actually reduce the alignment if your implementation happens to guarantee 32-byte alignment from malloc (unlikely, but in theory a C implementation could have a 32-byte aligned type). That doesn't matter if all you do is call memset_16aligned, but if you use the memory for a struct then it could matter.
I'm not sure off-hand what a good fix is for this (other than to warn the user that the buffer returned is not necessarily suitable for arbitrary structs) since there's no way to determine programatically what the implementation-specific alignment guarantee is. I guess at startup you could allocate two or more 1-byte buffers, and assume that the worst alignment you see is the guaranteed alignment. If you're wrong, you waste memory. Anyone with a better idea, please say so...
[Added:
The 'standard' trick is to create a union of 'likely to be maximally aligned types' to determine the requisite alignment. The maximally aligned types are likely to be (in C99) 'long long
', 'long double
', 'void *
', or 'void (*)(void)
'; if you include <stdint.h>
, you could presumably use 'intmax_t
' in place of long long
(and, on Power 6 (AIX) machines, intmax_t
would give you a 128-bit integer type). The alignment requirements for that union can be determined by embedding it into a struct with a single char followed by the union:
struct alignment
{
char c;
union
{
intmax_t imax;
long double ldbl;
void *vptr;
void (*fptr)(void);
} u;
} align_data;
size_t align = (char *)&align_data.u.imax - &align_data.c;
You would then use the larger of the requested alignment (in the example, 16) and the align
value calculated above.
On (64-bit) Solaris 10, it appears that the basic alignment for the result from malloc()
is a multiple of 32 bytes.
]
In practice, aligned allocators often take a parameter for the alignment rather than it being hardwired. So the user will pass in the size of the struct they care about (or the least power of 2 greater than or equal to that) and all will be well.
3) Use what your platform provides: posix_memalign
for POSIX, _aligned_malloc
on Windows.
4) If you use C11, then the cleanest - portable and concise - option is to use the standard library function aligned_alloc
that was introduced in this version of the language specification.
As cardern has said list will do the job.
Here is how you can use a named range.
Select your range and enter a new name:
Select your cell that you want a drop down to be in and goto data tab -> data validation.
Select 'List' from the 'Allow' Drop down menu.
Enter your named range like this:
Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.
I ran into the problem that some subdependencies couldn't be resolved in IntelliJ 2016.3.X. This could be fixed by changing the Maven home directory
in Settings > Build, Execution, Deployment > Build Tools > Maven from Bundled (Maven 3)
to /usr/share/maven
.
After that all subdependencies got resolved as in previous IntelliJ versions.
you can get the key value pair as
<pre>
function test(){
var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function(key,value) {
alert(key);
alert(value.com);
});
}
</pre>
I have this code snippet run from the ENTRYPOINT
in my docker file:
while true
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run the built docker image as:
docker run -td <image name>
Log in to the container shell:
docker exec -it <container id> /bin/bash
I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:
CREATE FUNCTION [dbo].[Table_exists]
(
@TableName VARCHAR(200)
)
RETURNS BIT
AS
BEGIN
If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
RETURN 1;
RETURN 0;
END
GO
To delete table User
if it exists, call it like so:
IF [dbo].[Table_exists]('User') = 1 Drop table [User]
install -d -m 0777 /your/dir
should give you what you want. Be aware that every user has the right to write add and delete files in that directory.
Presumably, if one wants to use an OnTouchListener
rather than an OnClickListener
, then the extra functionality of the OnTouchListener
is needed. This is a supplemental answer to show more detail of how an OnTouchListener
can be used.
Define the listener
Put this somewhere in your activity or fragment.
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
Set the listener
Set the listener in onCreate
(for an Activity) or onCreateView
(for a Fragment).
myView.setOnTouchListener(handleTouch);
Notes
getX
and getY
give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX
and getRawY
if you want the absolute screen coordinates.x
and y
values to determine things like swipe direction.check out this link and then help yourself out.
the basic code is
#create a temp. file
echo "hi " > t.tmp
# set the file time to 2 hours ago
touch -t 200405121120 t.tmp
# then check for files
find /admin//dump -type f -newer t.tmp -print -exec ls -lt {} \; | pg
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs
module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export
// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
A generic answer on how to handle click
events with KnockoutJS...
Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click
binding from KnockoutJS instead of onclick
. Like this:
function Item(parent, txt) {_x000D_
var self = this;_x000D_
_x000D_
self.doStuff = function(data, event) {_x000D_
console.log(data, event);_x000D_
parent.log(parent.log() + "\n data = " + ko.toJSON(data));_x000D_
};_x000D_
_x000D_
self.doOtherStuff = function(customParam, data, event) {_x000D_
console.log(data, event);_x000D_
parent.log(parent.log() + "\n data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
};_x000D_
_x000D_
self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
var self = this;_x000D_
_x000D_
self.doParentStuff = function(data, event) {_x000D_
console.log(data, event);_x000D_
self.log(self.log() + "\n data = " + ko.toJSON(data));_x000D_
};_x000D_
_x000D_
self.items = ko.observableArray([_x000D_
new Item(self, "John Doe"),_x000D_
new Item(self, "Marcus Aurelius")_x000D_
]);_x000D_
self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
<div class="parent">_x000D_
<span data-bind="text: txt"></span><br>_x000D_
<button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
<button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
<button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
<button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n data = ' + ko.toJSON(data)); }</button><br>_x000D_
<button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
<button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
**A note about the actual question...*
The actual question has one interesting bit:
// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"
Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML
you yourself will be gone forever ever!).
Instead, modify the View Model in your handler instead, and have the View respond. For example:
function RootVm() {_x000D_
var self = this;_x000D_
self.buttonWasClickedOnce = ko.observable(false);_x000D_
self.toggle = function(data, event) {_x000D_
self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
};_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div data-bind="visible: !buttonWasClickedOnce()">_x000D_
<button data-bind="click: toggle">Toggle!</button>_x000D_
</div>_x000D_
<div data-bind="visible: buttonWasClickedOnce">_x000D_
Can be made visible with toggle..._x000D_
<button data-bind="click: toggle">Untoggle!</button>_x000D_
</div>_x000D_
</div>
_x000D_
This task is very easy use following code in html header section
<head> <meta http-equiv="refresh" content="30" /> </head>
It will refresh your page after 30 seconds.
if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:
top
then you can use this code to kill matlab: kill
example: kill 58056
To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The /
seemed to solve this problem for me :)
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink]
, then it should be assigned a name of the property the value of which will be the route it should navigate the user to.
So to fix your issue, replace this routerLink="['/about']"
with routerLink="/about"
in your HTML.
There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:
<nav class="main-nav>
<ul
class="main-nav__list"
ng-sticky
addClass="main-sticky-link"
[ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/">Home</a>
</li>
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/about">About us</a>
</li>
</ul>
</nav>
It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>
, either in your template provided above or in a parent component.
There's another issue with your AppRoutingModule
. You need to export the RouterModule
from there so that it is available to your AppModule
when it imports it. To fix that, export it from your AppRoutingModule
by adding it to the exports
array.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'what', component: WhatwedoComponent },
{ path: 'contacts', component: FooterComponent },
{ path: 'projects', component: ProjectsComponent},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes),
],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
Without wanting to give you the answer here is the logic.
You have 2 possible values in each digit. you have 9 of them.
like in base 10 where you have 10 different values by digit say you have 2 of them (which makes from 0 to 99) : 0 to 99 makes 100 numbers. if you do the calcul you have an exponential function
base^numberOfDigits:
10^2 = 100 ;
2^9 = 512
If you're using Rails 3+, remove the gem from the Gemfile and run bundle install
.
If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install
should do the trick.
alter table [table name] remove [present column name] to [new column name.
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner
Embed the version in setup.py
and have setup.py
generate a module (e.g. version.py
) containing only version info, that's imported by your package, or
The reverse: put the version info in your package itself, and import that to set the version in setup.py
The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.
You should change it to something as follows
SortedMap<String, Double> myMap =
new TreeMap<String, Double>(new Comparator<String>()
{
public int compare(String o1, String o2)
{
return o1.compareTo(o2);
}
});
Update
You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -
List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
You should be able to get an IWin32Window by by using PresentationSource.FromVisual and casting the result to HwndSource which implements IWin32Window.
Also in the comments here:
git rm -r .
git checkout HEAD~3 .
git commit
After the commit, files in the new HEAD
will be the same as they were in the revision HEAD~3
.
In my case ping works from device but not from the emulator. I found this documentation: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
On the topic of "Local Networking Limitations" it says:
"Depending on the environment, the emulator may not be able to support other protocols (such as ICMP, used for "ping") might not be supported. Currently, the emulator does not support IGMP or multicast."
Further information: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297
this is a known limitation of the QEMU user-mode network stack. Quoting from the original doc: Note that ping is not supported reliably to the internet as it would require root privileges. It means you can only ping the local router (10.0.2.2).
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
I think your cron is not correct. According to what you described, you may need to change cron schedule to
*/5 * * * *
What you put in your schedule now mean it will poll the SCM at 5 past of every hour.
I think this one is awesome
ls -1 | awk 'ORS=","'
ORS is the "output record separator" so now your lines will be joined with a comma.
If i am understanding your question, would this work? (you will have to replace with your actual column and table names)
SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).
EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
In App.js
add the below code and try
window.location.pathname
Open command prompt separately and check:
C:\mongodb\bin\mongoimport --db db_name --collection collection_name< filename.json
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
If your margin is set on the body, then setting the background color of the html tag should color the margin area
html { background-color: black; }
body { margin:50px; background-color: white; }
Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color
Forget datalist element that good solution for autocomplete function, but not for combobox feature.
css:
.combobox {
display: inline-block;
position: relative;
}
.combobox select {
display: none;
position: absolute;
overflow-y: auto;
}
html:
<div class="combobox">
<input type="number" name="" value="" min="" max="" step=""/><br/>
<select size="3">
<option value="0"> 0</option>
<option value="25"> 25</option>
<option value="40"> 40</option>
</select>
</div>
js (jQuery):
$('.combobox').each(function() {
var
$input = $(this).find('input'),
$select = $(this).find('select');
function hideSelect() {
setTimeout(function() {
if (!$select.is(':focus') && !$input.is(':focus')) {
$select
.hide()
.css('z-index', 1);
}
}, 20);
}
$input
.focusin(function() {
if (!$select.is(':visible')) {
$select
.outerWidth($input.outerWidth())
.show()
.css('z-index', 100);
}
})
.focusout(hideSelect)
.on('input', function() {
$select.val('');
});
$select
.change(function() {
$input.val($select.val());
})
.focusout(hideSelect);
});
This works properly even when you use text input instead of number.
After some great help from steinar this is what worked for me:
public void ExecuteCommand(string command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process process;
ProcessInfo = new ProcessStartInfo(Application.StartupPath + "\\txtmanipulator\\txtmanipulator.bat", command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = Application.StartupPath + "\\txtmanipulator";
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
process = Process.Start(ProcessInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
ExitCode = process.ExitCode;
MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
process.Close();
}
Below are my personal learning notes on GIT tracking branches, hopefully it will be helpful for future visitors:
To find out who's making inotify instances, try this command (source):
for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr
Mine looked like this:
25 /proc/2857/fd/anon_inode:inotify
9 /proc/2880/fd/anon_inode:inotify
4 /proc/1375/fd/anon_inode:inotify
3 /proc/1851/fd/anon_inode:inotify
2 /proc/2611/fd/anon_inode:inotify
2 /proc/2414/fd/anon_inode:inotify
1 /proc/2992/fd/anon_inode:inotify
Using ps -p 2857
, I was able to identify process 2857 as sublime_text
. Only after closing all sublime windows was I able to run my node script.
A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess
ODP.NET provider, you should forget about things like network\admin
, Oracle client
, Oracle_Home
, etc.
Here is what you need
C:\Program Files (x86)
. With full dev tools, under 60MbAt this point you have 2 options to connect.
a) In the connection string set datasource
in the following format
DataSource=ServerName:Port/SID . . .
or DataSource=IP:Port/SID . . .
b) Create tnsnames.ora
file (only it is going to be different from previous experiences). Have entry in it:
AAA = (DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))
And place this file into your bin folder, where your application is running from.
Now you can connect using your connection name - DataSource=AAA . . .
So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.
To summarize - with managed, no need for heavy Oracle Client, Oracle_home
or knowing depths of oracle installation folders. Everything can be done within your .net application structures.
document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;
where TestToggleRadioButtonList
is the id of the RadioButtonList
.
I Found Very Simple Solution isAdded() method which is one of the fragment method to identify that this current fragment is attached to its Activity or not.
we can use this like everywhere in fragment class like:
if(isAdded())
{
// using this method, we can do whatever we want which will prevent **java.lang.IllegalStateException: Fragment not attached to Activity** exception.
}
NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...
import java.util.concurrent.*;
public class CountDownLatchExample {
public static class ProcessThread implements Runnable {
CountDownLatch latch;
long workDuration;
String name;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name= name;
this.latch = latch;
this.workDuration = duration;
}
public void run() {
try {
System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
Thread.sleep(workDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+ "completed its works");
//when task finished.. count down the latch count...
// basically this is same as calling lock object notify(), and object here is latch
latch.countDown();
}
}
public static void main(String[] args) {
// Parent thread creating a latch object
CountDownLatch latch = new CountDownLatch(3);
new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs
System.out.println("waiting for Children processes to complete....");
try {
//current thread will get notified if all chidren's are done
// and thread will resume from wait() mode.
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All Process Completed....");
System.out.println("Parent Thread Resuming work....");
}
}
This is a pure javascript solution that I've wrapped as an Angular service to implement pagination logic like in google search results.
Working demo on CodePen at http://codepen.io/cornflourblue/pen/KVeaQL/
Details and explanation at this blog post
function PagerService() {
// service definition
var service = {};
service.GetPager = GetPager;
return service;
// service implementation
function GetPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 10
pageSize = pageSize || 10;
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = startIndex + pageSize;
// create an array of pages to ng-repeat in the pager control
var pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
}
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
A friend function is not a member function, so the problem is that you declare operator<<
as a friend of A
:
friend ostream& operator<<(ostream&, A&);
then try to define it as a member function of the class logic
ostream& logic::operator<<(ostream& os, A& a)
^^^^^^^
Are you confused about whether logic
is a class or a namespace?
The error is because you've tried to define a member operator<<
taking two arguments, which means it takes three arguments including the implicit this
parameter. The operator can only take two arguments, so that when you write a << b
the two arguments are a
and b
.
You want to define ostream& operator<<(ostream&, const A&)
as a non-member function, definitely not as a member of logic
since it has nothing to do with that class!
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a.number;
}
use try-catch to see real error occurred on you
try
{
//Your insert code here
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
With AutoEventWireup
which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
For details see the MSDN article.
Put the jquery js link before the bootstrap js link like so:
<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
instead of:
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap
'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.
Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.
The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.
body {_x000D_
font-family: sans-serif;_x000D_
margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
padding: 10px;_x000D_
background: lightgray;_x000D_
}_x000D_
ul {_x000D_
list-style: none;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
padding: 0;/* just to reset */_x000D_
padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
flex: 1 1 auto;_x000D_
margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
<li>a lacinia purus porttitor eget</li>_x000D_
<li>donec ut nunc lorem</li>_x000D_
<li>duis in est dictum</li>_x000D_
<li>tempor metus non</li>_x000D_
<li>dapibus sapien</li>_x000D_
<li>phasellus bibendum tincidunt</li>_x000D_
<li>quam vitae accumsan</li>_x000D_
<li>ut interdum eget nisl in eleifend</li>_x000D_
<li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc()
, or CSS preprocessors which only work when the units are the same, etc.
To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.
GET /cars/_search
{
"size": 0,
"aggs": {
"distinct_by_derivative_id": {
"terms": {
"field": "derivative_id"
},
"aggs": {
"vehicle_type": {
"terms": {
"field": "vehicle_type"
},
"aggs": {
"cheapest_vehicle": {
"top_hits": {
"sort": [
{ "rental": { "order": "asc" } }
],
"_source": { "includes": [ "manufacturer_name",
"rental",
"vehicle_type"
]
},
"size": 1
}
}
}
}
}
}
}
}
Result:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"distinct_by_derivative_id" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "04",
"doc_count" : 3,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "8",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Renault",
"rental" : 89.99
},
"sort" : [
89.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "7",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 99.99
},
"sort" : [
99.99
]
}
]
}
}
}
]
}
},
{
"key" : "01",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "1",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
}
]
}
},
{
"key" : "02",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "4",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 499.99
},
"sort" : [
499.99
]
}
]
}
}
}
]
}
},
{
"key" : "03",
"doc_count" : 1,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "5",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 399.99
},
"sort" : [
399.99
]
}
]
}
}
}
]
}
}
]
}
}
}
try this
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
Look to this, may be help you.
class ScrollView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello world!!"),
//You can add another children
]),
),
);
},
);
}
}
I was playing with this and came up with an alternative.
$ VAR=/home/me/mydir/file.c
$ DIR=`echo $VAR |xargs dirname`
$ echo $DIR
/home/me/mydir
The part I liked is it was easy to extend backup the tree:
$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`
$ echo $DIR
/home
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
This should work. Then just call cls(); whenever you want to clear the screen.
(using the method suggested before.)
#include <stdio.h>
void cls()
{
int x;
for ( x = 0; x < 10; x++ )
{
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
When I installed nodemon using : npm install nodemon -g --save
, my path for the global npm packages was not present in the PATH variable .
If you just add it to the $PATH variable it will get fixed.
Edit the ~/.bashrc
file in your home folder and add this line :-
export PATH=$PATH:~/npm
Here "npm" is the path to my global npm packages . Replace it with the global path in your system