It could have to do with the z-index master list on variables.less. In general, be sure that your variables.less file is correct and up-to-date.
No need to trying reinvent the wheel, as this is common greatest-n-per-group problem. Very nice solution is presented.
I prefer the most simplistic solution (see SQLFiddle, updated Justin's) without subqueries (thus easy to use in views):
SELECT t1.*
FROM lms_attendance AS t1
LEFT OUTER JOIN lms_attendance AS t2
ON t1.user = t2.user
AND (t1.time < t2.time
OR (t1.time = t2.time AND t1.Id < t2.Id))
WHERE t2.user IS NULL
This also works in a case where there are two different records with the same greatest value within the same group - thanks to the trick with (t1.time = t2.time AND t1.Id < t2.Id)
. All I am doing here is to assure that in case when two records of the same user have same time only one is chosen. Doesn't actually matter if the criteria is Id
or something else - basically any criteria that is guaranteed to be unique would make the job here.
Another way to use gson:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
It can be used when you don't have the bean as in susemi99's post.
Create your own confirm box:
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
Create your own confirm()
method:
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
You'll need to add CSS to style and position your confirm box appropriately.
Working demo: jsfiddle.net/Xtreu
Summary:
PagingAndSortingRepository extends CrudRepository
JpaRepository extends PagingAndSortingRepository
The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.
The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.
Finally the JpaRepository add some more functionality that is specific to JPA.
Currently from MySQL 8
you can set the following to a DATE
column:
In MySQL Workbench
, in the Default
field next to the column, write: (curdate())
If you put just curdate()
it will fail. You need the extra (
and )
at the beginning and end.
If you are using Jekyll or octopress following will also work.
{% comment %}
These commments will not include inside the source.
{% endcomment %}
The Liquid tags {% comment %}
are parsed first and removed before the MarkDown processor even gets to it. Visitors will not see when they try to view source from their browser.
if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )
You can do like this
SELECT something
FROM
(a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'
You seem to be misunderstanding how import
searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules
); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:
import package.subpackage.module
from package.subpackage import module
from module import attribute1
The second line looks for a package called package.subpackage
and imports module
from that package. This line has no effect on the third line. The third line just looks for a module called module
and doesn't find one. It doesn't "re-use" the object called module
that you got from the line above.
In other words from someModule import ...
doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.
It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1
and be done with it. You need never worry about the long package.subpackage.module
once you've imported the name you want from it.
If you do want to have access to the module to access other names later, then you can do from package.subpackage import module
and, as you've seen you can then do module.attribute1
and so on as much as you like.
If you want both --- that is, if you want attribute1
directly accessible and you want module
accessible, just do both of the above:
from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works
If you don't like typing package.subpackage
even twice, you can just manually create a local reference to attribute1:
from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works
The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking
For example :
$git rev-list --count --left-right "@{upstream}"...HEAD >4 12
will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:
>error: No upstream branch found for ''
origin
(your forked repo on github) and upstream
(the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.Your
.git/config
reads :[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = [email protected]:myusername/reponame.git [remote "upstream"] fetch = +refs/heads/*:refs/remotes/upstream/* url = [email protected]:authorname/reponame.git
it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.
It's the branch you fetch/pull from whenever you issue a plain
git fetch
/git pull
, without arguments.
Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :
$ git branch --set-upstream master origin/master > Branch master set up to track remote branch master from origin.
This adds 2 parameters in
.git/config
:[branch "master"] remote = origin merge = refs/heads/master
now try (provided 'upstream' remote has a 'dev' branch)
$ git branch --set-upstream master upstream/dev > Branch master set up to track remote branch dev from upstream.
.git/config
now reads:[branch "master"] remote = upstream merge = refs/heads/dev
-u --set-upstream
For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see
branch.<name>.merge
in git-config(1).branch.<name>.merge
Defines, together with
branch.<name>.remote
, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)branch.<name>.remote
When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.
take a look at git-config(1)
Manual Page
git config --global push.default upstream git config --global push.default tracking (deprecated)
This is to prevent accidental pushes to branches which you’re not ready to push yet.
Add
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
before
mail->send()
and replace
require "mailer/class.phpmailer.php";
with
require "mailer/PHPMailerAutoload.php";
The way to store dates in SQLite is:
yyyy-mm-dd hh:mm:ss.xxxxxx
SQLite also has some date and time functions you can use. See SQL As Understood By SQLite, Date And Time Functions.
test.split("\\|",999);
Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"
But test.split("\\|");
will return different length strings arrays for the same examples.
use reference: link
The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?
It's a mechanism to invoke an API in an asynchrounous way. The sequence is the following
So you can invoke the api and tell your user the request is "processing" or "acquired" for example, and then update the status when you receive the response from the api.
Hope it makes sense. -G
Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.
<asp:GridView
ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true">
<Columns>
<asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid" />
<asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
<asp:BoundField DataField="writer" HeaderText="WRITER" />
<asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook" />
<asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
if (DT != null) {
DataView dataView = new DataView(DT);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string GridViewSortDirection {
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string ConvertSortDirectionToSql(SortDirection sortDirection) {
switch (GridViewSortDirection) {
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
}
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef
is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos
as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline
keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this
where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c
to b
, and the resulting value b
is then assigned to a
. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const
and one that is not?
A const
member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const
member functions can be invoked against const
objects, or const
references and pointers. For example, your operator +()
does not modify your local object and thus should be declared as const
. Your operator =()
clearly modifies the local object, and therefore the operator should not be const
.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
For this purpose, you can create your own function. For example:
$ echo 'mkfile() { mkdir -p "$(dirname "$1")" && touch "$1" ; }' >> ~/.bashrc
$ source ~/.bashrc
$ mkfile ./fldr1/fldr2/file.txt
Explanation:
~/.bashrc
file using the echo
command-p
flag is for creating the nested folders, such as fldr2
~/.bashrc
file with the source
commandmkfile
function to create the fileType info variables
to list "All global and static variable names".
Type info locals
to list "Local variables of current stack frame" (names and values), including static variables in that function.
Type info args
to list "Arguments of the current stack frame" (names and values).
Here is an extension method based on a previous answer that will let you truncate to any resolution...
Usage:
DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)
Class:
public static class DateTimeUtils
{
/// <summary>
/// <para>Truncates a DateTime to a specified resolution.</para>
/// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
/// </summary>
/// <param name="date">The DateTime object to truncate</param>
/// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
/// <returns>Truncated DateTime</returns>
public static DateTime Truncate(this DateTime date, long resolution)
{
return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
}
}
Things seem to have changed since Angular 2.0.0
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
The .next()
function will be called on your subscriber.
The app token can be found from this url.
I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?
The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.
print(extracted_features.shape)
print(extracted_features)
(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']
I have the following list/NumPy array extracted_features
, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use
dataset[extracted_features]
And you will end up with this
This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.
Here is my real life example how to loop lines of another program output, check for substrings, drop double quotes from variable, use that variable outside of the loop. I guess quite many is asking these questions sooner or later.
##Parse FPS from first video stream, drop quotes from fps variable
## streams.stream.0.codec_type="video"
## streams.stream.0.r_frame_rate="24000/1001"
## streams.stream.0.avg_frame_rate="24000/1001"
FPS=unknown
while read -r line; do
if [[ $FPS == "unknown" ]] && [[ $line == *".codec_type=\"video\""* ]]; then
echo ParseFPS $line
FPS=parse
fi
if [[ $FPS == "parse" ]] && [[ $line == *".r_frame_rate="* ]]; then
echo ParseFPS $line
FPS=${line##*=}
FPS="${FPS%\"}"
FPS="${FPS#\"}"
fi
done <<< "$(ffprobe -v quiet -print_format flat -show_format -show_streams -i "$input")"
if [ "$FPS" == "unknown" ] || [ "$FPS" == "parse" ]; then
echo ParseFPS Unknown frame rate
fi
echo Found $FPS
Declare variable outside of the loop, set value and use it outside of loop requires done <<< "$(...)" syntax. Application need to be run within a context of current console. Quotes around the command keeps newlines of output stream.
Loop match for substrings then reads name=value pair, splits right-side part of last = character, drops first quote, drops last quote, we have a clean value to be used elsewhere.
This page might interest you: http://msdn.microsoft.com/en-us/magazine/dd722812.aspx
You can generate the XML documentation file using either the command-line compiler or through the Visual Studio interface. If you are compiling with the command-line compiler, use options /doc or /doc+. That will generate an XML file by the same name and in the same path as the assembly. To specify a different file name, use /doc:file.
If you are using the Visual Studio interface, there's a setting that controls whether the XML documentation file is generated. To set it, double-click My Project in Solution Explorer to open the Project Designer. Navigate to the Compile tab. Find "Generate XML documentation file" at the bottom of the window, and make sure it is checked. By default this setting is on. It generates an XML file using the same name and path as the assembly.
You could use the validation plugin for jQuery: http://docs.jquery.com/Plugins/Validation
It happens to have an accept() rule that does exactly what you need: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension
Note that controlling file extension is not bullet proof since it is in no way related to the mimetype of the file. So you could have a .png that's a word document and a .doc that's a perfectly valid png image. So don't forget to make more controls server-side ;)
Here is my answer.
function array2Html($array, $table = true)
{
$out = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
if (!isset($tableHeader)) {
$tableHeader =
'<th>' .
implode('</th><th>', array_keys($value)) .
'</th>';
}
array_keys($value);
$out .= '<tr>';
$out .= array2Html($value, false);
$out .= '</tr>';
} else {
$out .= "<td>$value</td>";
}
}
if ($table) {
return '<table>' . $tableHeader . $out . '</table>';
} else {
return $out;
}
}
However, your table headers have to be a part of the array, which is pretty common when it comes from a database. e.g.
$shop = array(
array(
'title' => 'rose',
'price' => 1.25,
'number' => 15,
),
array(
'title' => 'daisy',
'price' => 0.75,
'number' => 25,
),
array(
'title' => 'orchid',
'price' => 1.15,
'number' => 7,
),
);
print arrayToHtml($shop);
Hope it helps ;)
what about using materialDesign HintAssist ? i'm using this which also you can add floating hint too :
<TextBox Width="150" Height="40" Text="hello" materialDesign:HintAssist.Hint="address" materialDesign:HintAssist.IsFloating="True"></TextBox>
i installed Material Design with Nuget Package there is installation guide in documentation link
If file filename.tar.gz
gives this message: POSIX tar archive,
the archive is a tar, not a GZip archive.
Unpack a tar without the z
, it is for gzipped (compressed), only:
mv filename.tar.gz filename.tar # optional
tar xvf filename.tar
Or try a generic Unpacker like unp
(https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.
determine the file type:
$ file ~/Downloads/filename.tbz2
/User/Name/Downloads/filename.tbz2: bzip2 compressed data, block size = 400k
setting direction CSS property to rtl should work with you. I guess it isn't supported on IE6.
e.g
<ul style="direction:rtl;">
<li> item </li>
<li> item </li>
</ul>
You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.
SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name
Without subshells in Linux to delete .svn
folders:
find . -name .svn -exec rm -r -f {} +
rm = remove
-r = recursive (folders)
-f = force, avoids a lot of "a your sure you want to delete file XY".
The solution of Rohan will fix the problem as the error message will not be shown but the emulator will not use the hardware acceleration and thus be again very slow.
I recommend instead to install the Intel Hardware Accelerated Execution Manager as described here:
Use float() in place of int() so that your program can handle decimal points. Also, don't use next
as it's a built-in Python function, next().
Also you code as posted is missing import sys
and the definition for dead
Thank you for your script!
I have work quite a long on it to make everything working... So I'm sharing it here
makeMask function is not working! Only working for /8,/16,/24
Ex:
bits = "21" ; socket.inet_ntoa(struct.pack('=L',(2L << int(bits)-1) - 1))
'255.255.31.0' whereas it should be 255.255.248.0
So I have used another function calcDottedNetmask(mask) from http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/
Ex:
#!/usr/bin/python
>>> calcDottedNetmask(21)
>>> '255.255.248.0'
#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
>>>True which is completely WRONG!!
So my new addressInNetwork function looks-like:
#!/usr/bin/python
import socket,struct
def addressInNetwork(ip,net):
'''This function allows you to check if on IP belogs to a Network'''
ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(bits)))[0]
network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def calcDottedNetmask(mask):
bits = 0
for i in xrange(32-int(mask),32):
bits |= (1 > 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))
And now, answer is right!!
#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
False
I hope that it will help other people, saving time for them!
Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius
void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for (i = 0; i <= triangleAmount; i++) {
glVertex2f(
x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.
Getting rJava to work depends heavily on your computers configuration:
If you use 64bit version make sure, that you do not set JAVA_HOME as a enviorment variable. If this variable is set, rJava will not work for whatever reason (at least for me). You can check easily within R is JAVA_HOME is set with
Sys.getenv("JAVA_HOME")
If you need to have JAVA_HOME set (e.g. you need it for maven or something else), you could deactivate it within your R-session with the following code before loading rJava:
if (Sys.getenv("JAVA_HOME")!="")
Sys.setenv(JAVA_HOME="")
library(rJava)
This should do the trick in most cases. Furthermore this will fix issue Using the rJava package on Win7 64 bit with R, too. I borrowed the idea of unsetting the enviorment variable from R: rJava package install failing.
A.replaceWith(span)
- No parent neededGeneric form:
target.replaceWith(element)
Way better/cleaner than the previous method.
For your use case:
A.replaceWith(span)
...
).Examples:
// Initially [child1, target, child3]
target.replaceWith(span, "foo") // [child1, span, "foo", child3]
const list = ["bar", span]
target.replaceWith(...list, "fizz") // [child1, "bar", span, "fizz", child3]
null
targetIf your target has a chance to be null, you can consider using the newish ?.
optional chaining operator. Nothing will happen if target doesn't exist. Read more here.
target?.replaceWith(element)
Supported Browsers - 94% Apr 2020
Que:Is there a way to programmatically scroll a scroll view to a specific edittext?
Ans:Nested scroll view in recyclerview last position added record data.
adapter.notifyDataSetChanged();
nested_scroll.setScrollY(more Detail Recycler.getBottom());
Is there a way to programmatically scroll a scroll view to a specific edit text?
Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.
The problem is, that if you have that problem, the database-schema is denormalized.
You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.
So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.
So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.
And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...
Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO
CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
@in_RM_ApertureID uniqueidentifier
,@in_DatumVon AS datetime
,@in_DatumBis AS datetime
,@in_Status AS integer
)
RETURNS bit
AS
BEGIN
DECLARE @bNoCheckForThisCustomer AS bit
DECLARE @bIsInvalidValue AS bit
SET @bNoCheckForThisCustomer = 'false'
SET @bIsInvalidValue = 'false'
IF @in_Status = 99
RETURN 'false'
IF @in_DatumVon > @in_DatumBis
BEGIN
RETURN 'true'
END
IF @bNoCheckForThisCustomer = 'true'
RETURN @bIsInvalidValue
IF NOT EXISTS
(
SELECT
T_Raum.RM_UID
,T_Raum.RM_Status
,T_Raum.RM_DatumVon
,T_Raum.RM_DatumBis
,T_Raum.RM_ApertureID
FROM T_Raum
WHERE (1=1)
AND T_Raum.RM_ApertureID = @in_RM_ApertureID
AND @in_DatumVon >= T_Raum.RM_DatumVon
AND @in_DatumBis <= T_Raum.RM_DatumBis
AND T_Raum.RM_Status <> 99
)
SET @bIsInvalidValue = 'true' -- IF !
RETURN @bIsInvalidValue
END
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
CHECK
(
NOT
(
dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1
)
)
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
Difficult question to answer - as with most technology solutions, it really depends on your situation and since you have not described the problem you are trying to solve, how can anyone propose a solution?
You need to test them both to see which of them satisfied your needs.
With that said, MongoDB does not require any expensive hardware. Like any other database solution, it will work better with more CPU and memory but is certainly not a requirement - especially for early development purposes.
Since Horse
is a subclass of Animal
, you can just change
print(Animal.SIZES[1])
with
print(self.SIZES[1])
Still, you need to remember that SIZES[1]
means "big", so probably you could improve your code by doing something like:
class Animal:
SIZE_HUGE="Huge"
SIZE_BIG="Big"
SIZE_MEDIUM="Medium"
SIZE_SMALL="Small"
class Horse(Animal):
def printSize(self):
print(self.SIZE_BIG)
Alternatively, you could create intermediate classes: HugeAnimal
, BigAnimal
, and so on. That would be especially helpful if each animal class will contain different logic.
use "python manage.py sqlflush" command in windows 10 for others type manage.py
I use scoop as command-liner installer for Windows... scoop rocks!
The quick answer (use PowerShell):
PS C:\Users\myuser> scoop install ruby
Longer answer:
Just searching for ruby:
PS C:\Users\myuser> scoop search ruby
'main' bucket:
jruby (9.2.7.0)
ruby (2.6.3-1)
'versions' bucket:
ruby19 (1.9.3-p551)
ruby24 (2.4.6-1)
ruby25 (2.5.5-1)
Check the installation info :
PS C:\Users\myuser> scoop info ruby
Name: ruby
Version: 2.6.3-1
Website: https://rubyinstaller.org
Manifest:
C:\Users\myuser\scoop\buckets\main\bucket\ruby.json
Installed: No
Environment: (simulated)
GEM_HOME=C:\Users\myuser\scoop\apps\ruby\current\gems
GEM_PATH=C:\Users\myuser\scoop\apps\ruby\current\gems
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\bin
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\gems\bin
Output from installation:
PS C:\Users\myuser> scoop install ruby
Updating Scoop...
Updating 'extras' bucket...
Installing 'ruby' (2.6.3-1) [64bit]
rubyinstaller-2.6.3-1-x64.7z (10.3 MB) [============================= ... ===========] 100%
Checking hash of rubyinstaller-2.6.3-1-x64.7z ... ok.
Extracting rubyinstaller-2.6.3-1-x64.7z ... done.
Linking ~\scoop\apps\ruby\current => ~\scoop\apps\ruby\2.6.3-1
Persisting gems
Running post-install script...
Fetching rake-12.3.3.gem
Successfully installed rake-12.3.3
Parsing documentation for rake-12.3.3
Installing ri documentation for rake-12.3.3
Done installing documentation for rake after 1 seconds
1 gem installed
'ruby' (2.6.3-1) was installed successfully!
Notes
-----
Install MSYS2 via 'scoop install msys2' and then run 'ridk install' to install the toolchain!
'ruby' suggests installing 'msys2'.
PS C:\Users\myuser>
I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.
Any <input type="file">
based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)
public static string FromSqlType(string sqlTypeString)
{
if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
{
throw new Exception("sql type not found");
}
switch (typeCode)
{
case Enums.SQLType.varbinary:
case Enums.SQLType.binary:
case Enums.SQLType.filestream:
case Enums.SQLType.image:
case Enums.SQLType.rowversion:
case Enums.SQLType.timestamp://?
return "byte[]";
case Enums.SQLType.tinyint:
return "byte";
case Enums.SQLType.varchar:
case Enums.SQLType.nvarchar:
case Enums.SQLType.nchar:
case Enums.SQLType.text:
case Enums.SQLType.ntext:
case Enums.SQLType.xml:
return "string";
case Enums.SQLType.@char:
return "char";
case Enums.SQLType.bigint:
return "long";
case Enums.SQLType.bit:
return "bool";
case Enums.SQLType.smalldatetime:
case Enums.SQLType.datetime:
case Enums.SQLType.date:
case Enums.SQLType.datetime2:
return "DateTime";
case Enums.SQLType.datetimeoffset:
return "DateTimeOffset";
case Enums.SQLType.@decimal:
case Enums.SQLType.money:
case Enums.SQLType.numeric:
case Enums.SQLType.smallmoney:
return "decimal";
case Enums.SQLType.@float:
return "double";
case Enums.SQLType.@int:
return "int";
case Enums.SQLType.real:
return "Single";
case Enums.SQLType.smallint:
return "short";
case Enums.SQLType.uniqueidentifier:
return "Guid";
case Enums.SQLType.sql_variant:
return "object";
case Enums.SQLType.time:
return "TimeSpan";
default:
throw new Exception("none equal type");
}
}
public enum SQLType
{
varbinary,//(1)
binary,//(1)
image,
varchar,
@char,
nvarchar,//(1)
nchar,//(1)
text,
ntext,
uniqueidentifier,
rowversion,
bit,
tinyint,
smallint,
@int,
bigint,
smallmoney,
money,
numeric,
@decimal,
real,
@float,
smalldatetime,
datetime,
sql_variant,
table,
cursor,
timestamp,
xml,
date,
datetime2,
datetimeoffset,
filestream,
time,
}
You can use setScale()
to reduce the number of fractional digits to zero. Assuming value
holds the value to be rounded:
BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);
Using round()
is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:
BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);
(Note that BigDecimal
objects are immutable; both setScale
and round
will return a new object.)
Prepend the url prefix git+
(See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /
.
Just rebuild and clean project, then run project.
YOu can also rewrite it like this
FROM Resource r WHERE r.ResourceNo IN
(
SELECT m.ResourceNo FROM JobMember m
JOIN Job j ON j.JobNo = m.JobNo
WHERE j.ProjectManagerNo = @UserResourceNo
OR
j.AlternateProjectManagerNo = @UserResourceNo
Union All
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
Also a return table is expected in your RETURN statement
void myFunc(char* str, char c)
{
char* ptr;
int index;
ptr = strchr(str, c);
if (ptr == NULL)
{
printf("Character not found\n");
return;
}
index = ptr - str;
printf("The index is %d\n", index);
ASSERT(str[index] == c); // Verify that the character at index is the one we want.
}
This code is currently untested, but it demonstrates the proper concept.
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1
SELECT ID
FROM A
WHERE ID NOT IN (
SELECT ID
FROM B);
SELECT ID
FROM A a
WHERE NOT EXISTS (
SELECT 1
FROM B b
WHERE b.ID = a.ID)
SELECT a.ID
FROM A a
LEFT OUTER JOIN B b
ON a.ID = b.ID
WHERE b.ID IS NULL
DELETE
FROM A
WHERE ID NOT IN (
SELECT ID
FROM B)
Here is the source of these column flags
http://dev.mysql.com/doc/workbench/en/wb-table-editor-columns-tab.html
For versions of .Net where you can use LINQ OrderBy
and ThenBy
(or ThenByDescending
if needed):
using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();
Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.
I've tried many solutions and came up with this.
Options and selections of the dropdown are cleared using this only
$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();
But the interface is not updated. So you have to do this
$('#my-multi').multiselect('rebuild');
Hence, the final code is
$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();
$('#my-multi').multiselect('rebuild');
Suggestions and improvements are welcome.
It's possible, as addressed in Issue #7396:
When you do want to insert a
<br />
break tag using Markdown, you end a line with two or more spaces, then type return or Enter.
Fiddle: http://jsfiddle.net/uenrX/1/
The opacity property of the outer DIV cannot be undone by the inner DIV. If you want to achieve transparency, use rgba
or hsla
:
Outer div:
background-color: rgba(255, 255, 255, 0.9); /* Color white with alpha 0.9*/
Inner div:
background-color: #FFF; /* Background white, to override the background propery*/
EDIT
Because you've added filter:alpha(opacity=90)
to your question, I assume that you also want a working solution for (older versions of) IE. This should work (-ms-
prefix for the newest versions of IE):
/*Padded for readability, you can write the following at one line:*/
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
/*Similarly: */
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
I've used the Gradient filter, starting with the same start-
and end-color
, so that the background doesn't show a gradient, but a flat colour. The colour format is in the ARGB hex format. I've written a JavaScript snippet to convert relative opacity values to absolute alpha-hex values:
var opacity = .9;
var A_ofARGB = Math.round(opacity * 255).toString(16);
if(A_ofARGB.length == 1) A_ofARGB = "0"+a_ofARGB;
else if(!A_ofARGB.length) A_ofARGB = "00";
alert(A_ofARGB);
If you have Spring in you classpath then the following will do it.
Find all classes in a package that are annotated with XmlRootElement:
private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (isCandidate(metadataReader)) {
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
}
return candidates;
}
private String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
try {
Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
if (c.getAnnotation(XmlRootElement.class) != null) {
return true;
}
}
catch(Throwable e){
}
return false;
}
This is the way I got it working for me:
Tasks:
- name: checking if the file 1 exists
stat:
path: /path/to/foo abc.xts
register: stat_result
- name: moving file 1
command: mv /path/to/foo abc.xts /tmp
when: stat_result.stat.exists == True
the playbook above, will check if file abc.xts exists before move the file to tmp folder.
In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.
you can fetch location name easily by implementing this following function
const fetchLocationName = async (lat,lng) => {
await fetch(
'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
)
.then((response) => response.json())
.then((responseJson) => {
console.log(
'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
);
});
};
_x000D_
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of
This is the approach to do this: -
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'DBName' AND
TABLE_SCHEMA = 'SchemaName' AND
TABLE_NAME = 'TableName' AND
COLUMN_NAME = 'ColumnName')
BEGIN
ALTER TABLE DBName.SchemaName.TableName ALTER COLUMN ColumnName [data type] NULL
END
If you don't have any schema then delete the schema line because you don't need to give the default schema.
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
I can think of a workaround that can help if the classes you want to extend include only methods.
Write these classes as interfaces. In Java, you can implements any number of interfaces, and implement the methods as default methods in the interfaces.
Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5
EDIT: According to this post it is a known issue.
And this could be the solution you're looking for :)
You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState
function and you need to serialize and deserialize the objects put into local storage.
constructor(props) {
super(props);
this.state = {
allProjects: JSON.parse(localStorage.getItem('allProjects')) || []
}
}
addProject = (newProject) => {
...
this.setState({
allProjects: this.state.allProjects.concat(newProject)
},() => {
localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))
});
}
This can be achieve by creating object of List data structure, as follows
List list = new ArrayList();
For more information refer this link
Not out of the box, but many libraries have similar:
Commons Lang:
org.apache.commons.lang.StringUtils.join(list, conjunction);
Spring:
org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);
I had similar problem with regex = "?"
. It happens for all special characters that have some meaning in a regex. So you need to have "\\"
as a prefix to your regex.
String [] separado = line.split("\\*");
Use time.sleep
or Event().wait
like this:
from threading import Event
from time import sleep
delay_in_sec = 2
# Use time.sleep like this
sleep(delay_in_sec) # Returns None
print(f'slept for {delay_in_sec} seconds')
# Or use Event().wait like this
Event().wait(delay_in_sec) # Returns False
print(f'waited for {delay_in_sec} seconds')
Use threading.Timer
like this:
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start() # Returns None
print("Started")
Outputs:
Started
function called after 2 seconds
timer_obj.cancel()
.I believe the official way is still to go thorugh codecvt
facets (you need some sort of locale-aware translation), as in
resultCode = use_facet<codecvt<char, wchar_t, ConversionState> >(locale).
in(stateVar, scratchbuffer, scratchbufferEnd, from, to, toLimit, curPtr);
or something like that, I don't have working code lying around. But I'm not sure how many people these days use that machinery and how many simply ask for pointers to memory and let ICU or some other library handle the gory details.
I had the same error but I had the CommonModule imported. Instead I left a comma where it shouldn't be because of copy/paste when splitting a module:
@NgModule({
declarations: [
ShopComponent,
ShoppingEditComponent
],
imports: [
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: 'shop', component: ShopComponent }, <--- offensive comma
])
]
})
Here's what you can do using font-awesome library.
button.btn.add::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
Option 1
Open a different console and run
jupyter notebook stop [PORT]
The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run
jupyter notebook stop
If it is on port 9000, then
jupyter notebook stop 9000
Option 2 (Source)
Check runtime folder location
jupyter --paths
Remove all files in the runtime folder
rm -r [RUNTIME FOLDER PATH]/*
Use top
to find any Jupyter Notebook running processes left and if so kill their PID.
top | grep jupyter &
kill [PID]
One can boilt it down to
TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")
Note: If one wants to launch one's Notebook on a specific IP/Port
jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &
Just so for people doing it in SQL server: use STRING_AGG
to get similar results.
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
I have Windows 8 installed on my machine, and the aspnet_regiis.exe tool did not worked for me either.
The solution that worked for me is posted on this link, on the answer by Neha: System.ServiceModel.Activation.HttpModule error
Everywhere the problem to this solution was mentioned as re-registering aspNet by using aspnet_regiis.exe. But this did not work for me.
Though this is a valid solution (as explained beautifully here)
but it did not work with Windows 8.
For Windows 8 you need to Windows features and enable everything under ".Net Framework 3.5" and ".Net Framework 4.5 Advanced Services".
Thanks Neha
You can try this. its working for me 'name' is a property in arr.
repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index
Here is the simplest way to do this
static void Main(string[] args)
{
Task t = MainAsync(args);
t.Wait();
}
static async Task MainAsync(string[] args)
{
await ...
}
FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.
Theres a reason that ASP.Net does not look into your nested controls recursively by default:
Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.
The onBlur
event is fired when you have moved away from an object without necessarily having changed its value.
The onChange
event is only called when you have changed the value of the field and it loses focus.
You might want to take a look at quirksmode's intro to events. This is a great place to get info on what's going on in your browser when you interact with it. His book is good too.
DateTime.Now will not work, use DateTime.Today instead.
Just access the element and append it to the value.
<input
type="button"
onclick="document.getElementById('myTextArea').value += '•'"
value="Add •">
See a live demo.
For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.
Also it needs to be a UTF8 character.
Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.
From Python's collections
library documentation:
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Check for package-lock.json file at C:\Windows\system32
.
If it doesn't exist, run cmd
as admin and execute the following commands:
Set EXPO_DEBUG=true
npm config set package-lock false
npm install
when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.
// works for any Object Including JSON(key value pair) or Array.
// var arr = [];
// var jsonObj = {};
if (jQuery.isEmptyObject(anyObjectIncludingJSON))
{
console.log("Empty Object");
}
For a shopping cart situation here's what I recommend. I'm gonna break it down into it's simplest form.
Assuming we start with this(a list view with 2 colums, 2 buttons, and a label):
First things first, removing the items, to do that we'll enter our remove button:
private void button2_Click(object sender, EventArgs e)
{
listView1.Items.Remove(listView1.SelectedItems[0]);
label1.Text = updateCartTotal().ToString();
}
Now the second line is updating our labels total using the next function i'll post to addup all the total of column 2 in the listview:
private decimal updateCartTotal()
{
decimal runningTotal = 0;
foreach(ListViewItem l in listView1.Items)
{
runningTotal += Convert.ToDecimal(l.SubItems[1].Text);
}
return runningTotal;
}
You don't have to use decimal like I did, you can use float or int if you don't have decimals. So let's break it down. We use a for loop to total all the items in the column 2(SubItems[1].Text). Add that to a decimal we declared prior to the foreach loop to keep a total. If you want to do tax you can do something like:
return runningTotal * 1.15;
or whatever your tax rate is.
Long and short of it, using this function you can retotal your listview by just calling the function. You can change the labels text like I demo'd prior if that's what you're after.
You don't need to use an indexer (since it a bit less typesafe). You have two options :
interface EnumServiceItem {
id: number; label: string; key: any
}
interface EnumServiceItems extends Array<EnumServiceItem>{}
// Option A
var result: EnumServiceItem[] = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
// Option B
var result: EnumServiceItems = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
]
Personally I recommend Option A (simpler migration when you are using classes not interfaces).
Good news everybody! Craigslist has actually released a bulk posting api now!
Replace your domain with domainname.com
, it's working with me .
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]
Dispatching and action inside of reducer seems occurs bug.
I made a simple counter example using useReducer
which "INCREASE" is dispatched then "SUB" also does.
In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt
to -1 and then
continue "INCREASE" action to set cnt
to 0, but it was -1 ("INCREASE" was ignored)
See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154
let listener = () => {
console.log("test");
};
const middleware = (action) => {
console.log(action);
if (action.type === "INCREASE") {
listener();
}
};
const counterReducer = (state, action) => {
middleware(action);
switch (action.type) {
case "INCREASE":
return {
...state,
cnt: state.cnt + action.payload
};
case "SUB":
return {
...state,
cnt: state.cnt - action.payload
};
default:
return state;
}
};
const Test = () => {
const { cnt, increase, substract } = useContext(CounterContext);
useEffect(() => {
listener = substract;
});
return (
<button
onClick={() => {
increase();
}}
>
{cnt}
</button>
);
};
{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1
You should use as_json
method which converts ActiveRecord objects to Ruby Hashes despite its name
tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json
# You can now add new records and return the result as json by calling `to_json`
tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
Just use NavLink
rather than Link
. It will add .active
class automatically.
<Nav className="mr-auto">
<Nav.Link as={NavLink} to="/home">Home</Nav.Link>
<Nav.Link as={NavLink} to="/users">Users</Nav.Link>
</Nav>
I know that this is an old question, but exp1orer's answer is very slow for datasets with a large number unique groups (probably because of the lambda). I built off of their answer to turn it into an array calculation so now it's super fast! Below is the example code:
Create the test dataframe with 50,000 unique groups
import random
import string
import pandas as pd
import numpy as np
np.random.seed(0)
# This is the total number of groups to be created
NumberOfGroups = 50000
# Create a lot of groups (random strings of 4 letters)
Group1 = [''.join(random.choice(string.ascii_uppercase) for _ in range(4)) for x in range(NumberOfGroups/10)]*10
Group2 = [''.join(random.choice(string.ascii_uppercase) for _ in range(4)) for x in range(NumberOfGroups/2)]*2
FinalGroup = [''.join(random.choice(string.ascii_uppercase) for _ in range(4)) for x in range(NumberOfGroups)]
# Make the numbers
NumbersForPercents = [np.random.randint(100, 999) for _ in range(NumberOfGroups)]
# Make the dataframe
df = pd.DataFrame({'Group 1': Group1,
'Group 2': Group2,
'Final Group': FinalGroup,
'Numbers I want as percents': NumbersForPercents})
When grouped it looks like:
Numbers I want as percents
Group 1 Group 2 Final Group
AAAH AQYR RMCH 847
XDCL 182
DQGO ALVF 132
AVPH 894
OVGH NVOO 650
VKQP 857
VNLY HYFW 884
MOYH 469
XOOC GIDS 168
HTOY 544
AACE HNXU RAXK 243
YZNK 750
NOYI NYGC 399
ZYCI 614
QKGK CRLF 520
UXNA 970
TXAR MLNB 356
NMFJ 904
VQYG NPON 504
QPKQ 948
...
[50000 rows x 1 columns]
Array method of finding percentage:
# Initial grouping (basically a sorted version of df)
PreGroupby_df = df.groupby(["Group 1","Group 2","Final Group"]).agg({'Numbers I want as percents': 'sum'}).reset_index()
# Get the sum of values for the "final group", append "_Sum" to it's column name, and change it into a dataframe (.reset_index)
SumGroup_df = df.groupby(["Group 1","Group 2"]).agg({'Numbers I want as percents': 'sum'}).add_suffix('_Sum').reset_index()
# Merge the two dataframes
Percents_df = pd.merge(PreGroupby_df, SumGroup_df)
# Divide the two columns
Percents_df["Percent of Final Group"] = Percents_df["Numbers I want as percents"] / Percents_df["Numbers I want as percents_Sum"] * 100
# Drop the extra _Sum column
Percents_df.drop(["Numbers I want as percents_Sum"], inplace=True, axis=1)
This method takes about ~0.15 seconds
Top answer method (using lambda function):
state_office = df.groupby(['Group 1','Group 2','Final Group']).agg({'Numbers I want as percents': 'sum'})
state_pcts = state_office.groupby(level=['Group 1','Group 2']).apply(lambda x: 100 * x / float(x.sum()))
This method takes about ~21 seconds to produce the same result.
The result:
Group 1 Group 2 Final Group Numbers I want as percents Percent of Final Group
0 AAAH AQYR RMCH 847 82.312925
1 AAAH AQYR XDCL 182 17.687075
2 AAAH DQGO ALVF 132 12.865497
3 AAAH DQGO AVPH 894 87.134503
4 AAAH OVGH NVOO 650 43.132050
5 AAAH OVGH VKQP 857 56.867950
6 AAAH VNLY HYFW 884 65.336290
7 AAAH VNLY MOYH 469 34.663710
8 AAAH XOOC GIDS 168 23.595506
9 AAAH XOOC HTOY 544 76.404494
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
You can try this one as well;
tup = (1,2,3)
print("this is a tuple {something}".format(something=tup))
You can't use %something
with (tup)
just because of packing and unpacking concept with tuple.
The following is a very simple C++ example that shows that if you want to use a function to set a pointer to point to an object, you need a pointer to a pointer. Otherwise, the pointer will keep reverting to null.
(A C++ answer, but I believe it's the same in C.)
(Also, for reference: Google("pass by value c++") = "By default, arguments in C++ are passed by value. When an argument is passed by value, the argument's value is copied into the function's parameter.")
So we want to set the pointer b
equal to the string a
.
#include <iostream>
#include <string>
void Function_1(std::string* a, std::string* b) {
b = a;
std::cout << (b == nullptr); // False
}
void Function_2(std::string* a, std::string** b) {
*b = a;
std::cout << (b == nullptr); // False
}
int main() {
std::string a("Hello!");
std::string* b(nullptr);
std::cout << (b == nullptr); // True
Function_1(&a, b);
std::cout << (b == nullptr); // True
Function_2(&a, &b);
std::cout << (b == nullptr); // False
}
// Output: 10100
What happens at the line Function_1(&a, b);
?
The "value" of &main::a
(an address) is copied into the parameter std::string* Function_1::a
. Therefore Function_1::a
is a pointer to (i.e. the memory address of) the string main::a
.
The "value" of main::b
(an address in memory) is copied into the parameter std::string* Function_1::b
. Therefore there are now 2 of these addresses in memory, both null pointers. At the line b = a;
, the local variable Function_1::b
is then changed to equal Function_1::a
(= &main::a
), but the variable main::b
is unchanged. After the call to Function_1
, main::b
is still a null pointer.
What happens at the line Function_2(&a, &b);
?
The treatment of the a
variable is the same: within the function, Function_2::a
is the address of the string main::a
.
But the variable b
is now being passed as a pointer to a pointer. The "value" of &main::b
(the address of the pointer main::b
) is copied into std::string** Function_2::b
. Therefore within Function_2, dereferencing this as *Function_2::b
will access and modify main::b
. So the line *b = a;
is actually setting main::b
(an address) equal to Function_2::a
(= address of main::a
) which is what we want.
If you want to use a function to modify a thing, be it an object or an address (pointer), you have to pass in a pointer to that thing. The thing that you actually pass in cannot be modified (in the calling scope) because a local copy is made.
(An exception is if the parameter is a reference, such as std::string& a
. But usually these are const
. Generally, if you call f(x)
, if x
is an object you should be able to assume that f
won't modify x
. But if x
is a pointer, then you should assume that f
might modify the object pointed to by x
.)
Options -Indexes perfectly works for me ,
here is .htaccess
file :
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes <---- This Works for Me :)
</IfModule>
....etc stuff
</IfModule>
After :
This has worked for me :
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
//args[0] ="http://hostname:port/xyz/zbc";
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->"+output);
}
catch(Exception e){
System.out.println("Exception"+e);
}
}
This site seems to keep a complete list that's still maintained
iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).
You do need to assemble the full user-agent string out of the information listed in the page's columns.
I have created some sample code which creates new variables using a variety of ways that I can think of. It looks like the first 3 ways create values, and the last two create references.
package main
import "fmt"
type Config struct {
host string
port float64
}
func main() {
//value
var c1 Config
c2 := Config{}
c3 := *new(Config)
//reference
c4 := &Config{}
c5 := new(Config)
fmt.Println(&c1 == nil)
fmt.Println(&c2 == nil)
fmt.Println(&c3 == nil)
fmt.Println(c4 == nil)
fmt.Println(c5 == nil)
fmt.Println(c1, c2, c3, c4, c5)
}
which outputs:
false
false
false
false
false
{ 0} { 0} { 0} &{ 0} &{ 0}
You can use one of the following options:
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >
<link href="{{ URL::asset('css/app.css') }}" rel="stylesheet" type="text/css" >
{!! Html::style( asset('css/app.css')) !!}
Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).
arrayOrObjWithData = ['1'] || {id: 1}
<h1 *ngxIfNotEmpty="arrayOrObjWithData">
You will see it
</h1>
or
// store the result of async pipe in variable
<h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
{{obj.id}}
</h1>
or
noData = [] || {}
<h1 *ngxIfHasItems="noData">
You will NOT see it
</h1>
.aspx
uses a full lifecycle (Init
, Load
, PreRender
) and can respond to button clicks etc.
An .ashx
has just a single ProcessRequest
method.
mine would like magic.
html, body {
height: 100%;
}
.flex-container{
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-ms-flex-align: center;
-ms-flex-pack: center;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
}
<div class="flex-container">
<div>Content</div>
</div>
For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui
files.
Initially I tried to use ui->setWindowTitle
, but that doesn't exist. ui
is not a QDialog
or a QMainWindow
.
The owner of the ui
is the QDialog
or QMainWindow
, the .ui
just describes how to lay it out. In that case, you would use:
this->setWindowTitle("New Title");
I hope this helps someone else.
Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;
Also this looks wierd to me :
@ContextConfiguration("classpath*:conf/components.xml")
Here is an example that works fine for me :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {
@Autowired
OwnerService ownerService;
@Before
public void setup() {
ownerService.cleanList();
}
@Test
public void testOwners() {
Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
owner = ownerService.createOwner(owner);
assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
assertTrue("Check that Id exist: ", owner.getId() > 0);
owner.setLastName("Larsson");
ownerService.updateOwner(owner);
owner = ownerService.getOwner(owner.getId());
assertEquals("Name is changed", "Larsson", owner.getLastName());
}
rubysspi-1.3.1 worked for me on Windows 7, using the instructions from this page:
HEAD
is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.
master
is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).
origin
is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.
It works if you remove flexDirection: row
from descriptionContainerVer
and descriptionContainerVer2
respectively.
UPDATE (see comments)
I made a few changes to achieve what I think you're after. First of all I removed the descriptionContainerHor
component. Then I set the flexDirection
of the vertical views to row
and added alignItems: 'center'
and justifyContent: 'center'
. Since the vertical views are now in fact stacked along the horizontal axis I removed the Ver
part from the name.
So now you have a wrapper view that should vertically and horizontally align it's content and stack it along the x-axis. I then simply put two invisible View
components on the left and right side of the Text
component to do the padding.
Like this:
<View style={styles.descriptionContainer}>
<View style={styles.padding}/>
<Text style={styles.descriptionText} numberOfLines={5} >
Here is a really long text that you can do nothing about, its gonna be long wether you like it or not, so be prepared for it to go off screen. Right? Right..!
</Text>
<View style={styles.padding}/>
</View>
And this:
descriptionContainer:{
flex:0.5, //height (according to its parent),
flexDirection: 'row',
backgroundColor: 'blue',
alignItems: 'center',
justifyContent: 'center',
// alignSelf: 'center',
},
padding: {
flex: 0.1
},
descriptionText: {
backgroundColor: 'green',//Colors.transparentColor,
fontSize: 16,
flex: 0.8,
color: 'white',
textAlign: 'center',
flexWrap: 'wrap'
},
Then you get what I believe you were after.
FURTHER IMPROVEMENTS
Now if you would like to stack multiple text areas within the blue and orange views you can do something like this:
<View style={styles.descriptionContainer2}>
<View style={styles.padding}/>
<View style={styles.textWrap}>
<Text style={styles.descriptionText} numberOfLines={5} >
Some other long text which you can still do nothing about.. Off the screen we go then.
</Text>
<Text style={styles.descriptionText} numberOfLines={5} >
Another column of text.
</Text>
</View>
<View style={styles.padding}/>
</View>
Where textWrap
is styled like this:
textWrap: {
flexDirection: 'column',
flex: 0.8
},
Hope this helps!
In order to use special characters, such as '>' on Windows with echo, you need to place a special escape character before it.
For instance
echo A->B
will not work since '>' has to be escaped by '^':
echo A-^>B
See also escape sequences.
There is a short batch file, which prints a basic set of special character and their escape sequences.
You will be much happier using a dictionary instead:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
For knowing any version of the python library then if your library is installed using the pip then use the following command.
pip show tensorflow
The Output of the above command will be shown below:-
Name: tensorflow
Version: 2.3.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.6/dist-packages
Requires: astunparse, wheel, keras-preprocessing, gast, tensorflow-estimator, opt-einsum, tensorboard, protobuf, absl-py, six, wrapt, termcolor, numpy, grpcio, scipy, google-pasta, h5py
Required-by: fancyimpute
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
In my python interpreter exit
is actually a string and not a function -- 'Use Ctrl-D (i.e. EOF) to exit.'
. You can check on your interpreter by entering type(exit)
In active python what is happening is that exit is a function. If you do not call the function it will print out the string representation of the object. This is the default behaviour for any object returned. It's just that the designers thought people might try to type exit to exit the interpreter, so they made the string representation of the exit function a helpful message. You can check this behaviour by typing str(exit)
or even print exit
.
import-module IISAdministration;
function StartSite{
param($sitename)
try{
Start-IISSite -Name $sitename;
Write-Host "Site was started";
}
catch{
Write-Error "Error while staring the IISSite";
}
}
function StopSite{
param($sitename)
try{
Stop-IISSite -Name $sitename -confirm:$False; # Supress interaction inputs
Write-Host "Site was stopped";
}
catch{
Write-Error "Error while stopping the IISSite";
}
}
function ReplaceSiteFiles{
try{
Get-ChildItem -Path A:\APPS\CreditApp -Recurse | Foreach-Object {Remove-Item -Recurse -Path $_.FullName} # Remove file from AppPool Directory
Expand-Archive A:\Staging\LTA\Installers\CreditApp\CreditApp.zip -DestinationPath A:\APPS\ # Extract files from zip
Write-Host "Site files replaced successfully!";
}
catch [System.SystemException]{
Write-Host "Error while replacing the site files";
Write-Host $_
}
}
## Start Here
$site=Get-IISSite -Name "Default Web Site";
Write-Host $site
if($site.length -eq 1){
$siteState = $site.state;
Write-Host "The Site Exists with state: ${siteState}";
switch ($siteState)
{
'started' {
StopSite -sitename $site.name;
ReplaceSiteFiles;
StartSite -sitename $site.name;
}
'stopped' {
ReplaceSiteFiles;
StartSite -sitename $site.name;
}
default { "Deployment failed! Site state could not be determined.";}
}
}
else{
Write-Error "Invalid! Site does not exists";
}
## End Here
system ('/usr/bin/pdfcrop filename.pdf');
Simple answer
If you want to match single character, put it inside those brackets [ ]
Examples
...and so on. You can check your regular expresion online on this site: https://regex101.com/
(updated based on comment)
The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.
Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.
So this is not possible. If you want to respond to https links, then you need an ssl certificate.
You can use
hdfs fsck /
to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with
hdfs fsck / | egrep -v '^\.+$' | grep -v eplica
which ignores lines with nothing but dots and lines talking about replication.
Once you find a file that is corrupt
hdfs fsck /path/to/corrupt/file -locations -blocks -files
Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.
You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.
Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.
Once you determine what happened and you cannot recover any more blocks, just use the
hdfs fs -rm /path/to/file/with/permanently/missing/blocks
command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.
var indices = [];
var IDs = [0, 1, 2, 3, 4];
for(var i = 0, len = array.length; i < len; i++) {
for(var j = 0; j < IDs.length; j++) {
if(array[i].id == ID) indices.push(i);
}
}
Here is another way to use SQL SELECT
statement in VBA:
sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'"
Set rs = CurrentDb.OpenRecordset(sSQL)
On Error GoTo resultsetError
dbValue = rs!Variable
MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
select from_unixtime(column,'%Y-%m-%d') from myTable;
Those may help.
You can use the WinSPC program. Its access to any server is pretty easy. The program gives its guide too. I hope it's helpfull.
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
I love TextMate on OSX.
There is a kind of TextMate clone for Windows called simply "E" (e-texteditor.com). Its author promised that there will be a Linux version soon. Even if you already picked your favourite, TextMate (or E) is worth a look, simply because it is different.
I would say that there are mainly four different families of text editors:
You can differenciate between these families by their different paradigms of usage:
Emacs and TextMate are also easily extensible by user-created scripts in Lisp (Emacs) or any other command-line-language (TextMate). (Classic editors and VI are also extendable, but the effort is usually considerably bigger)
I would recommend that everyone tried at least one good example of each of these families (if possible) and find out what suits them best.
class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}
This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:
dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))
By the way, I suppose you are using /bin/bash.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
The solution I use in my SpringMVC webapps is to create a simple DefaultController
class like the following: -
@Controller
public class DefaultController {
private final String redirect;
public DefaultController(String redirect) {
this.redirect = redirect;
}
@RequestMapping(value = "/")
public ModelAndView redirectToMainPage() {
return new ModelAndView("redirect:/" + redirect);
}
}
The redirect can be injected in using the following spring configuration: -
<bean class="com.adoreboard.farfisa.controller.DefaultController">
<constructor-arg name="redirect" value="${default.redirect:loginController}"/>
</bean>
The ${default.redirect:loginController}
will default to loginController
but can be changed by inserting default.redirect=something_else
into a spring properties file / setting an environment variable etc.
As @Mike has mentioned above I have also: -
<welcome-file-list> ... </welcome-file-list>
section in the web.xml
file.index.html
, index.jsp
, default.html
, etc)This solution lets Spring worry more about redirects which may or may not be what you like.
I had an onpremises HA installation, a master and a worker stopped working returning a NOTReady status. Checking the kubelet logs on the nodes I found out this problem:
failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false
Disabling swap on nodes with
swapoff -a
and restarting the kubelet
systemctl restart kubelet
did the work.
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
The jQuery way to click a link is
$('#LinkID').click();
For mailTo link, you have to write the following code
$('#LinkID')[0].click();
For docker compose version: "3.4"
It works for me:
services:
my-service:
hostname: my_host_name
Don't need to use dns. Just use hostname. Compose file version 3 reference
By their nature, a small sample of random numbers doesn't have to be uniformly distributed. They're random, after all. I agree that if a random number generator is generating numbers that consistently appear to be grouped, then there is probably something wrong with it.
But keep in mind that randomness isn't necessarily uniform.
Edit: I added "small sample" to clarify.
Short answer
Add the route entry for register
in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'/routeTo/register'
];
and clear the cache and the cache route with the commands:
php artisan cache:clear && php artisan route:clear
Details
Every time you access a Laravel site, a token is generated, even if the session has not been started. Then, in each request, this token (stored in the cookies) will be validated against its expiration time, set in the SESSION_LIFETIME
field on config/session.php
file.
If you keep the site open for more than the expiration time and try to make a request, this token will be evaluated and the expiration error will return. So, to skip this validation on forms that are outside the functions of authenticated users (such as register or login) you can add the except route in app/Http/Middleware/VerifyCsrfToken.php
.
If your coloumn is text
and not varchar
, then you can use this:
SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))
To fix this issue, you need to change the ownership of the directory to the unix user that the webserver uses.
Even though I created the project within the VM using the VM user, the folder belonged to the user in the real computer; so, when trying to
Now it's working.
Thanks to all those that helped me figure this thing out
EDIT:
Actually, it still wasn't working, it still gave me a "permission denied" problem.
Here's what I did, I modified my Vagrantfile like this:
config.vm.synced_folder "./app","/var/www/", create:true,
:owner => "vagrant",
:group => "www-data",
:mount_options => ["dmode=775","fmode=664"]
country.code
is not in your group by
statement, and is not an aggregate (wrapped in an aggregate function).
According to pytest documentation, version 3 of pytest can temporary disable capture in a test:
def test_disabling_capturing(capsys):
print('this output is captured')
with capsys.disabled():
print('output not captured, going directly to sys.stdout')
print('this output is also captured')
You can always check this out for more custom solutions:
x => ({}[x.name] = x);
Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH
Just supply -s to your read call like so:
$ read -s PASSWORD
$ echo $PASSWORD
Assuming the connection is established and is available in global scope;
//Check if a value exists in a table
function record_exists ($table, $column, $value) {
global $connection;
$query = "SELECT * FROM {$table} WHERE {$column} = {$value}";
$result = mysql_query ( $query, $connection );
if ( mysql_num_rows ( $result ) ) {
return TRUE;
} else {
return FALSE;
}
}
Usage: Assuming that the value to be checked is stored in the variable $username;
if (record_exists ( 'employee', 'username', $username )){
echo "Username is not available. Try something else.";
} else {
echo "Username is available";
}
JavaScript solution without sort, 100% score and O(N) runtime. It builds a hash set of the positive numbers while finding the max number.
function solution(A) {
set = new Set()
let max = 0
for (let i=0; i<A.length; i++) {
if (A[i] > 0) {
set.add(A[i])
max = Math.max(max, A[i])
}
}
for (let i=1; i<max; i++) {
if (!set.has(i)) {
return i
}
}
return max+1
}
SELECT *
FROM sys.all_sql_modules
WHERE definition LIKE '%CreatedDate%'
Solution of unchecking comment at first column
is partially working, because it works for line comments, but not block comments.
So, with lines like:
/* first line
* second line
* ...
*/
or
// line 1
// line 2
// line 3
...
they are indented with "Auto reformat", but lines like:
/* first line
second line
...
*/
the identation will not be fixed.
So you should:
*
or //
before each line of commentsKeep when reformatting -> comment at first column
Auto reformat
. After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?
If not please let me know where you get stuck.
Install Common Dependencies
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev
Install NumArray 1.5.2
wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install
Install Numeric 23.8
wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install
Install HDF5 1.6.5
wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make
sudo make install
Install Nanoengineer
git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install
Troubleshooting
On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc
is inserted in CFLAGS
and gcc
will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...
touch sim/src/x86_64-linux-gnu-gcc
If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...
output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);
If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running
export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install
If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:
#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";
If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py
that look like this:
from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB
to look like this:
from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB
I also found an additional troubleshooting text file that has been removed, but you can find it here
After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
It's not possible to make reference types Nullable. Only value types can be used in a Nullable structure. Appending a question mark to a value type name makes it nullable. These two lines are the same:
int? a = null;
Nullable<int> a = null;
I also had the same issue. I've tried all described here solutions but they didn't help me. Then I've removed all emulators in the Android Virtual Device Manager and created new ones. The problem was in CPU/ABI system image configuration of the Android Virtual Device Manager. On my Windows10 machine emulator with system image x86
always is offline where emulator with system image x86_64
is working fine as expected. Just be aware of this
How about access
?
#include <io.h>
if (_access(filename, 0) == -1)
{
// File does not exist
}
My Understanding - Basically, svn client comes by default on Mac os. While installing in eclipse we should match svn plugin to the mac plugin and javaHL wont be missing. There is a lengthy process to update by installing xcode and then by using homebrew or macports which you can find after googling but if you are in hurry use simply the steps below.
1) on your mac terminal shell
$ svn --version
Note down the version e.g. 1.7.
2) open the link below
http://subclipse.tigris.org/wiki/JavaHL
check which version of subclipse you need corresponding to it. e.g.
Subclipse Version SVN/JavaHL Version 1.8.x 1.7.x
3) ok, pick up url corresponding to 1.8.x from
http://subclipse.tigris.org/servlets/ProjectProcess?pageID=p4wYuA
and add to your eclipse => Install new Software under help
select whatever you need, svn client or subclipse or mylyn etc and it will ask for restart of STS/eclipse thats it you are done. worked for me.
NOTE: if you already have multiple versions installed inside your eclipse then its best to uninstall all subclipse or svn client versions from eclipse plugins and start fresh with steps listed above.
This works fine for 2 tables. I have 3 tables and on clause has to link 2 conditions from 3 tables. My code:
from p in _dbContext.Products join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId join jpr in leftJoinQuery on new { VariantId = pv.Vid, ProductId = p.ProduktId } equals new { VariantId = jpr.Prices.VariantID, ProductId = jpr.Prices.ProduktID } into lj
But its showing error at this point: join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId
Error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.
I used the AdminClient api.
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try (AdminClient client = KafkaAdminClient.create(properties))
{
ListTopicsResult topics = client.listTopics();
Set<String> names = topics.names().get();
if (names.isEmpty())
{
// case: if no topic found.
}
return true;
}
catch (InterruptedException | ExecutionException e)
{
// Kafka is not available
}
let count=0;_x000D_
let text = document.getElementById('heading');_x000D_
let btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
if(count%2==0){_x000D_
text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Welcome to Javascript </>"; _x000D_
text.style.color="forestgreen";_x000D_
}//end of if_x000D_
else{ text.style.opacity="0.1";_x000D_
unfade(text);_x000D_
text.innerText="Hello javascript"; _x000D_
text.style.color="blueviolet";_x000D_
}//end of else_x000D_
count++;//for toggling the text_x000D_
});_x000D_
//function for fade effect--------_x000D_
function unfade(element) {_x000D_
var op = 0.1; // initial opacity_x000D_
element.style.display = 'block';_x000D_
var timer = setInterval(function () {_x000D_
if (op >= 1){_x000D_
clearInterval(timer);_x000D_
}_x000D_
element.style.opacity = op;_x000D_
element.style.filter = 'alpha(opacity=' + op * 100 + ")";_x000D_
op += op * 0.1;_x000D_
}, 30);_x000D_
}
_x000D_
<h1 style="color:blueviolet" id="heading">Hello javascript</h1>_x000D_
<button id="btn">Click me</button>
_x000D_
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
Do not create separate lists; create a list of lists:
results = []
with open('inputfile.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split(','))
or better still, use the csv
module:
import csv
results = []
with open('inputfile.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
results.append(row)
Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.
Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append()
just process that line right there.
Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:
import csv
with open('inputfile.txt', newline='') as inputfile:
results = list(csv.reader(inputfile))
I had the same issue in Visual Studio 2013. I'm not sure what caused this for my project, but I was able to fix it by cleaning the solution and rebuilding it.
With sqldf
:
# Example by Mehdi Nellen
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)
Solution:
library(sqldf)
sqldf('SELECT DISTINCT * FROM df')
Output:
a b
1 A 1
2 A 2
3 B 4
4 B 1
5 C 2
try using -U
(aka --update-snapshots
) when you run maven
And make sure the dependency definition is correct
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
Maybe this can help:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: basic-auth-server.herokuapp.com
schemes:
- http
- https
securityDefinitions:
Bearer:
type: apiKey
name: Authorization
in: header
paths:
/:
get:
security:
- Bearer: []
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.
There are also several examples in the swagger editor web with more complex security configurations which could help you.
Python >= 3.9:
'abcdc.com'.removesuffix('.com')
Python < 3.9:
def remove_suffix(text, suffix):
if text.endswith(suffix):
text = text[:-len(suffix)]
return text
remove_suffix('abcdc.com', '.com')
If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:
h1 {
flex-basis: 100%; // forces this element to take up any remaining space
}
img {
margin: 0 5px; // small margin between images
height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}
Here's what that will look like (only relavent CSS was included in snippet above)
On the subject of ugly hacks, you can always use a combination of exec
and a regular function to define a multiline function like this:
f = exec('''
def mlambda(x, y):
d = y - x
return d * d
''', globals()) or mlambda
You can wrap this into a function like:
def mlambda(signature, *lines):
exec_vars = {}
exec('def mlambda' + signature + ':\n' + '\n'.join('\t' + line for line in lines), exec_vars)
return exec_vars['mlambda']
f = mlambda('(x, y)',
'd = y - x',
'return d * d')
If you would like to use thumbnail through pure js/jquery no api, you can use this tool to capture a frame from the video and voila! Insert url thumb in which ever source you like.
Here is a code pen :
<img src="https://i.vimeocdn.com/video/531141496_640.jpg"` alt="" />
Here is the site to get thumbnail:
Here is my solution: a combination of the working ones below.
var checkInput = function(e) {
if (!e) {
e = window.event;
}
var code = e.keyCode || e.which;
if (!e.ctrlKey) {
//46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
return true;
//35..39 - home, end, left, right
if (code >= 35 && code <= 39)
return true;
//numpad numbers
if (code >= 96 && code <= 105)
return true;
//keyboard numbers
if (isNaN(parseInt(String.fromCharCode(code), 10))) {
e.preventDefault();
return false;
}
}
return true;
};
Yes we can work without body-parser
. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.
Or you can use body-parser
, as the express team is maintaining it .
What body-parser can do for you: It simplifies the request.
How to use it: Here is example:
Install npm install body-parser --save
This how to use body-parser in express:
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Link.
https://github.com/expressjs/body-parser.
And then you can get body and headers in root request object . Example
app.post("/posturl",function(req,res,next){
console.log(req.body);
res.send("response");
})
You can use Collections#sort
to sort things alphabetically.
in my case it didn't work like following
@Query("select count(e)>0 from MyEntity e where ...")
You can return it as boolean value with following
@Query(value = "SELECT CASE WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")
Well here is a simple function which will return the left justified string version of an integer:
character(len=20) function str(k)
! "Convert an integer to string."
integer, intent(in) :: k
write (str, *) k
str = adjustl(str)
end function str
And here is a test code:
program x
integer :: i
do i=1, 100
open(11, file='Output'//trim(str(i))//'.txt')
write (11, *) i
close (11)
end do
end program x
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
date -d @1278999698 +'%Y-%m-%d %H:%M:%S'
Where the number behind @
is the number in seconds
Simple one :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]
order deny,allow
replace your url with example.com
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.
The end result is that the operation is amortized O(n).
e.g.
s = ""
for i in range(n):
s+=str(i)
used to be O(n^2), but now it is O(n).
From the source (bytesobject.c):
void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
PyBytes_Concat(pv, w);
Py_XDECREF(w);
}
/* The following function breaks the notion that strings are immutable:
it changes the size of a string. We get away with this only if there
is only one module referencing the object. You can also think of it
as creating a new string object and destroying the old one, only
more efficiently. In any case, don't use this if the string may
already be known to some other part of the code...
Note that if there's not enough memory to resize the string, the original
string object at *pv is deallocated, *pv is set to NULL, an "out of
memory" exception is set, and -1 is returned. Else (on success) 0 is
returned, and the value in *pv may or may not be the same as on input.
As always, an extra byte is allocated for a trailing \0 byte (newsize
does *not* include that), and a trailing \0 byte is stored.
*/
int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
register PyObject *v;
register PyBytesObject *sv;
v = *pv;
if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
*pv = 0;
Py_DECREF(v);
PyErr_BadInternalCall();
return -1;
}
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference(v);
*pv = (PyObject *)
PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
if (*pv == NULL) {
PyObject_Del(v);
PyErr_NoMemory();
return -1;
}
_Py_NewReference(*pv);
sv = (PyBytesObject *) *pv;
Py_SIZE(sv) = newsize;
sv->ob_sval[newsize] = '\0';
sv->ob_shash = -1; /* invalidate cached hash value */
return 0;
}
It's easy enough to verify empirically.
$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'" 1000000 loops, best of 3: 1.85 usec per loop $ python -m timeit -s"s=''" "for i in xrange(100):s+='a'" 10000 loops, best of 3: 16.8 usec per loop $ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 10000 loops, best of 3: 158 usec per loop $ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 1000 loops, best of 3: 1.71 msec per loop $ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 14.6 msec per loop $ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'" 10 loops, best of 3: 173 msec per loop
It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .
$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'" 10000 loops, best of 3: 90.8 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'" 1000 loops, best of 3: 896 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 100 loops, best of 3: 9.03 msec per loop $ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 10 loops, best of 3: 89.5 msec per loop
So far so good, but then,
$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 12.8 sec per loop
ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.
realpath <path to the symlink file>
should do the trick.
Possible in IE and chrome although it does not work in firefox:
<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>
<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
No, as of Notepad++ 5.6.2, this doesn't seem to be possible. Although column selection (Alt+Selection) is possible, multiple selections are obviously not implemented and thus also not supported by the search function.
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
Adds a fading gradient to an overflowing HTML table element to better indicate there is more content to be scrolled.
See the live example below:
$("#scrolltable").html("<table id='cell'><tbody></tbody></table>");_x000D_
$("#cell").append("<thead><tr><th><div>First col</div></th><th><div>Second col</div></th></tr></thead>");_x000D_
_x000D_
for (var i = 0; i < 40; i++) {_x000D_
$("#scrolltable > table > tbody").append("<tr><td>" + "foo" + "</td><td>" + "bar" + "</td></tr>");_x000D_
}
_x000D_
/* Table with fixed header */_x000D_
_x000D_
table,_x000D_
thead {_x000D_
width: 100%;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
#scrolltable {_x000D_
margin-top: 50px;_x000D_
height: 120px;_x000D_
overflow: auto;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
#scrolltable table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
#scrolltable tr:nth-child(even) {_x000D_
background: #EEE;_x000D_
}_x000D_
_x000D_
#scrolltable th div {_x000D_
position: absolute;_x000D_
margin-top: -30px;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom scrollbar */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
width: 8px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-track {_x000D_
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);_x000D_
border-radius: 10px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
border-radius: 10px;_x000D_
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
_x000D_
/* Overflow scroll gradient */_x000D_
_x000D_
.overflow-scroll-gradient {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.overflow-scroll-gradient::after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 240px;_x000D_
height: 25px;_x000D_
background: linear-gradient( rgba(255, 255, 255, 0.001), white);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="overflow-scroll-gradient">_x000D_
<div id="scrolltable">_x000D_
</div>_x000D_
</div>
_x000D_
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}
How about the good old Command-Q?
The easiest way to change the background color of the jumbotron
If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.
HTML Code:
<div class="jumbotron myclass">
<h1>My Heading</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
CSS Code:
<style>
.myclass{
background-color: red;
}
</style>
To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i
) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.
The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.
Use .val()
instead of .innerHTML
for getting value of selected option
Use .text()
for getting text of selected option
Thanks for correcting :)
String 1:
$input =~ /'^\S+'/;
$s1 = $&;
String 2:
$input =~ /\(.*\)/;
$s2 = $&;
String 3:
$input =~ /\*?$/;
$s3 = $&;