Also you can use
Object myObj = Class.forName("your.cClass").newInstance();
My guess is that you don't really want to GROUP BY
some_product.
The answer to: "Is there a way to GROUP BY
a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY
a column alias.
The SELECT
clause, where column aliases are assigned, is not processed until after the GROUP BY
clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.
Inline view:
select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... ) T
group by some_product ...
CTE:
with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... )
select ...
from T
group by some_product ...
You can find standard sizes for everything in Google's style guide.
Here are the values they use for for buttons:
Buttons
English: Medium 14sp, all caps
Dense: Medium 15sp, all caps
Tall: Bold 15sp
I was facing this issue in Grafana and all I had to do was go to the config file and change allow_embedding to true and restart the server :)
It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
Depending on your requirements, you might use a Generic class like the one below to make access easier:
import java.util.ArrayList;
class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
public void addToInnerArray(int index, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
this.get(index).add(element);
}
public void addToInnerArray(int index, int index2, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
ArrayList<T> inner = this.get(index);
while (index2 >= inner.size()) {
inner.add(null);
}
inner.set(index2, element);
}
}
I found the most supported way to do this, without worrying about a third party library, was by using getTimezoneOffset
to calculate the appropriate timestamp, or update the time then use the normal methods to get the necessary date and time.
var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);
// ET timezone offset in hours.
var timezone = -5;
// Timezone offset in minutes + the desired offset in minutes, converted to ms.
// This offset should be the same for ALL date calculations, so you should only need to calculate it once.
var offset = (mydate.getTimezoneOffset() + (timezone * 60)) * 60 * 1000;
// Use the timestamp and offset as necessary to calculate min/sec etc, i.e. for countdowns.
var timestamp = mydate.getTime() + offset,
seconds = Math.floor(timestamp / 1000) % 60,
minutes = Math.floor(timestamp / 1000 / 60) % 60,
hours = Math.floor(timestamp / 1000 / 60 / 60);
// Or update the timestamp to reflect the timezone offset.
mydate.setTime(mydate.getTime() + offset);
// Then Output dates and times using the normal methods.
var date = mydate.getDate(),
hour = mydate.getHours();
EDIT
I was previously using UTC
methods when performing the date transformations, which was incorrect. With adding the offset to the time, using the local get
functions will return the desired results.
Below are two solutions to select the range A1.
Cells(1,1).Select '(row 1, column 1)
Range("A1").Select
Also check out this link;
We strongly recommend that you use Range instead of Cells to work with cells and groups of cells. It makes your sentences much clearer and you are not forced to remember that column AE is column 31.
The only time that you will use Cells is when you want to select all the cells of a worksheet. For example: Cells.Select To select all cells and then empty all cells of values or formulas you will use: Cells.ClearContents
--
"Cells" is particularly useful when setting ranges dynamically and looping through ranges by using counters. Defining ranges using letters as column numbers may be more transparent on the short run, but it will also make your application more rigid since they are "hard coded" representations - not dynamic.
Thanks to Kim Gysen
<style>
.left-column
{
float:left;
width:30%;
background-color:red;
}
.right-column
{
float:right;
width:30%;
background-color:green;
}
.center-column
{
margin:auto;
width:30%;
background-color:blue;
}
</style>
<div id="container">
<section class="left-column">THIS IS COLUMN 1 LEFT</section>
<section class="right-column">THIS IS COLUMN 3 RIGHT</section>
<section class="center-column">THIS IS COLUMN 2 CENTER</section>
</div>
the advantage of this way is you can set each column width independant of the other as long as you keep it under 100%, if you use 3 x 30% the remaining 10% is split as a 5% divider space between the collumns
TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.
For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.
However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b
to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe
, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.
if the current thread is killed and you use Thread.Sleep
and it is executing then you might get a ThreadAbortException
.
With Task.Delay
you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay
. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx
I also agree efficiency is not paramount in this case.
Try to add domains without http://
and https://
e.g. example.com
In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:
$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")
Clarification: small files only folks! Please don't try this on your 40 GB log file :)
Half a second is 500,000,000 nanoseconds, so your code should read:
tim.tv_sec = 0;
tim.tv_nsec = 500000000L;
As things stand, you code is sleeping for 1.0000005s (1s + 500ns).
Actually, a parent window can communicate with child or sibling windows or frames that have their own execution threads running.
By postfixing the URL with ?WSDL
If the URL is for example:
http://webservice.example:1234/foo
You use:
http://webservice.example:1234/foo?WSDL
And the wsdl will be delivered.
check this same effect with less code
$(".item").mouseover(function(){
$('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
});
toolbar.setTitle(null);
// remove the title
This still needs more refining however works with all simple references, without killing existing local names.
Type GlobalNamesToLocalNames_Type
Name As String
Sheet As String
Ref As String
End Type
Sub GlobalNamesToLocalNames(Optional Void As Variant)
Dim List() As GlobalNamesToLocalNames_Type
Dim Count As Long
Dim Name As Name
Dim Dat() As String
Dim X As Long
' count the size
For Each Name In ActiveWorkbook.Names
Count = Count + 1
Next
ReDim List(Count - 1)
Count = 0
' Collecect all name data
For Each Name In ActiveWorkbook.Names
With List(Count)
' Pick up only the name
If InStr(Name.Name, "!") > 0 Then
Dat = Split(Name.Name, "!")
.Name = Dat(1)
Else
.Name = Name.Name
End If
' pick up the sheet and refer
Dat = Split(Name.RefersTo, "!")
.Sheet = Mid(Dat(0), 2)
.Ref = Dat(1)
' make local sheet name
.Name = .Sheet & "!" & .Name
End With
Count = Count + 1
Next
' Delete all names
For Each Name In ActiveWorkbook.Names
Name.Delete
Next
'rebuild all the names
For X = 0 To Count - 1
With List(X)
If Left(.Ref, 1) <> "#" Then
ActiveWorkbook.Names.Add Name:=.Name, RefersToLocal:="=" & .Sheet & "!" & .Ref
End If
End With
Next
End Sub
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
I have stopped on the script like below (as I have only one non-clustered unique index in this table):
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command nvarchar(1000)
set @table_name = N'users'
set @col_name = N'login'
select @Command = 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name
from sys.tables t join sys.indexes d on d.object_id = t.object_id
where t.name = @table_name and d.type=2 and d.is_unique=1
--print @Command
execute (@Command)
Has anyone comments if this solution is acceptable? Any pros and cons?
Thanks.
I'm using XAMPP, in which there are several php.ini files.
You can find the line in the php.ini files:
;extension=php_curl.dll
Please remove ;
at the beginning of this line. And you may need to restart apache server.
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
One more made from the core jQuery functionality(it could be better):
function blink( el ) {
if (!el) {
el = this
}
$(el).animate( { opacity: 0.5 },1200, function() {
$(this).animate( {opacity: 1 }, 1200, blink );
} );
}
You can tweak the animation opacity change(0.5- 1) and delay(1200) to get a better "blink". This one is less annoying than the blink of the 90es :-)
`
require_once('functions.php');
$errors = FALSE;
$errorMessage = "";
if(mysqli_connect_error()){
$errors = TRUE;
$errorMessage .= "There was a connection error <br/>";
errorDisplay($errorMessage);
die($errors);
} else if($errors != "TRUE"){
$errors .= FALSE;
}
if(isset(mysqli_real_escape_string($_POST['search']))){
$search = mysqli_real_escape_string($_POST['search']);
search(search);
}
?>
<?php
//This is functions.php
function search($searchQuery){
echo "<div class="col-md-10 col-md-offset-1">";
$searchTerm
$query = query("SELECT * FROM `index` WHERE `keywords` LIKE '".$searchTerm."' ");
while($row = mysqli_fetch_array($query)){
$results = <<< DELIMITER
<div class="result col-md-12">
<a href="index.php?search={$row['id']}"> {$row['Title']} </a>
<p class="searchDesc">{$row['description']}</p>
</div>
DELIMITER;
echo $results;
}
echo "</div>";
}
function errorDisplay($msg){
if(!isset($_SESSION['errors'])){
$_SESSION['errors'] = $msg;
showError($msg);
} else if() {
$_SESSION['errors'] .= $msg . "<br>";
showError($msg);
}
}
function showError($msg) {
return $msg;
unset($_SESSION['errors']);
}
?>`
Perhaps That Helps?
What is the right approach for doing this?
There are a lot of "right" approaches, you just have decide which one best suites your needs. It appears as though you're misunderstanding how to use node_modules
...
If you're familiar with NuGet you should think of npm as its client-side counterpart. Where the node_modules
directory is like the bin
directory for NuGet. The idea is that this directory is just a common location for storing packages, in my opinion it is better to take a dependency
on the packages you need as you have done in the package.json
. Then use a task runner like Gulp
for example to copy the files you need into your desired wwwroot
location.
I wrote a blog post about this back in January that details npm, Gulp and a whole bunch of other details that are still relevant today. Additionally, someone called attention to my SO question I asked and ultimately answered myself here, which is probably helpful.
I created a Gist
that shows the gulpfile.js
as an example.
In your Startup.cs
it is still important to use static files:
app.UseStaticFiles();
This will ensure that your application can access what it needs.
There is a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.
public class Sample {
private readonly string ro;
public Sample() {
ro = "set";
}
public Sample(string value) : this() {
ro = value; // this works even though it was set in the no-arg ctor
}
}
the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :
df = df.query("columnNameA <= @x or columnNameB == @y")
with x and y are declared variables which you can refer to with @
$("#myTable").parent().html();
Perhaps I'm not understanding your question properly, but this will get the selected element's parent element's html.
Is that what you're after?
This can be caused by a cached https redirect, and can be fixed by clearing the cache manually as in Adiyat Mubarak's answer.
But if you are visiting localhost you likely are a developer, in which case you will find a cache clearing chrome extension such as "classic cache killer" (see e.g. https://chrome.google.com/webstore/search/classic%20cache%20killer?hl=en) useful in a variety of situations, and likely already have one installed.
So the quick fix is: Install a cache killer (if you don't have one already), turn it on, and reload the page. Done!
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")
It's probably optimized heavily at the C level.
Edit: I randomly generated a large list.
In [8]: len(a)
Out[8]: 6339347
In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop
Edit edit: This could be done with collections.Counter
a = Counter(your_list)
print a['1']
Using the same list in my last timing example
In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop
My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.
Here is some profiling
In [24]: profile.run("a.count('1')")
3 function calls in 0.091 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.091 0.091 <string>:1(<module>)
1 0.091 0.091 0.091 0.091 {method 'count' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
In [25]: profile.run("b = Counter(a); b['1']")
6339356 function calls in 2.143 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.143 2.143 <string>:1(<module>)
2 0.000 0.000 0.000 0.000 _weakrefset.py:68(__contains__)
1 0.000 0.000 0.000 0.000 abc.py:128(__instancecheck__)
1 0.000 0.000 2.143 2.143 collections.py:407(__init__)
1 1.788 1.788 2.143 2.143 collections.py:470(update)
1 0.000 0.000 0.000 0.000 {getattr}
1 0.000 0.000 0.000 0.000 {isinstance}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
6339347 0.356 0.000 0.356 0.000 {method 'get' of 'dict' objects}
try this code
textview.setText((Html.fromHtml("<strike>hello world!</strike>")));
Fun new approach to "one-lining" the case of an anonymously split
thing such that you don't split it twice, but do all the work in one line is using the walrus operator, :=
, to perform assignment as an expression, allowing both:
first, last = (split_str := a.split("-"))[0], split_str[-1]
and:
first, last = (split_str := a.split("-"))[::len(split_str)-1]
Mind you, in both cases it's essentially exactly equivalent to doing on one line:
split_str = a.split("-")
then following up with one of:
first, last = split_str[0], split_str[-1]
first, last = split_str[::len(split_str)-1]
including the fact that split_str
persists beyond the line it was used and accessed on. It's just technically meeting the requirements of one-lining, while being fairly ugly. I'd never recommend it over unpacking or itemgetter
solutions, even if one-lining was mandatory (ruling out the non-walrus versions that explicitly index or slice a named variable and must refer to said named variable twice).
One of the most memorable bugs I had was to do with an inline function that used alloca
. It manifested itself as a stack overflow (because it allocates on the stack) at random points of the program's execution.
In the header file:
void DoSomething() {
wchar_t* pStr = alloca(100);
//......
}
In the implementation file:
void Process() {
for (i = 0; i < 1000000; i++) {
DoSomething();
}
}
So what happened was the compiler inlined DoSomething
function and all the stack allocations were happening inside Process()
function and thus blowing the stack up. In my defence (and I wasn't the one who found the issue; I had to go and cry to one of the senior developers when I couldn't fix it), it wasn't straight alloca
, it was one of ATL string conversion macros.
So the lesson is - do not use alloca
in functions that you think might be inlined.
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
You can achieve cool static reflection features for structs with BOOST_HANA_DEFINE_STRUCT from the Boost::Hana library.
Hana is quite versatile, not only for the usecase you have in mind but for a lot of template metaprogramming.
Here's a solution for POST
ed JSON
body that doesn't require any middleware or extensions, all you need is to override OnActionExecuting
to have access to all of the data set in the body or even the arguments in the URL:
using System.Text.Json;
....
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// You can simply use filterContext.ActionArguments to get whatever param that you have set in the action
// For instance you can get the "json" param like this: filterContext.ActionArguments["json"]
// Or better yet just loop through the arguments and find the type
foreach(var elem in filterContext.ActionArguments)
{
if(elem.Value is JsonElement)
{
// Convert json obj to string
var json = ((JsonElement)elem.Value).GetRawText();
break;
}
}
}
[HttpPost]
public IActionResult Add([FromBody] JsonElement json, string id = 1)
{
return Ok("v1");
}
You could do something like this
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = 6;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
And then strReponse should contain the values returned by your webservice
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
Reorder its work This Way
var tmpOrder = playlist[oldIndex];
playlist.splice(oldIndex, 1);
playlist.splice(newIndex, 0, tmpOrder);
I hope this will work
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
Try this code :
return context.EntitytableName.AsEnumerable().Find(p => p.LoginID.Equals(loginID) && p.Password.Equals(password)).Select(p => new ModelTableName{ FirstName = p.FirstName, UserID = p.UserID });
I had the problem that there were views that had a bad "DEFINER", which is the user that defined the view. The DEFINER used in the view had been removed some time ago as being "root from some random workstation".
Check whether there might be a problem by running:
USE information_schema;
SELECT DEFINER, SECURITY_TYPE FROM views;
I modified the DEFINER (actually, set the DEFINER to root@localhost
and the SQL SECURITY value to INVOKER
so the view is executed with the permissions of the invoking user instead of the defining user, which actually makes more sense) using ALTER VIEW.
This is tricky as you have to construct the appropriate ALTER VIEW
statement from information_schema.views
, so check:
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:
<persons>
<person>
<name>Koen Bok</name>
<age>26</age>
</person>
<person>
<name>Plutor Heidepeen</name>
<age>33</age>
</person>
</persons>
Would become
{'persons': [
{'name': 'Koen Bok', 'age': 26},
{'name': 'Plutor Heidepeen', 'age': 33}]
}
But what would this be:
<persons>
<person name="Koen Bok">
<locations name="defaults">
<location long=123 lat=384 />
</locations>
</person>
</persons>
See what I mean?
Edit: just found this article: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Check my fiddle from this thread: Draw a line connecting two clicked div columns
The layout is different, but basically the idea is to create invisible divs between the boxes and add corresponding borders with jQuery (the answer is only HTML and CSS)
I had another requirement like only few stash have to be removed, below code would be helpful in that case.
#!/bin/sh
for i in `seq 5 8`
do
git stash drop stash@{$i}
done
/* will delete from 5 to 8 index*/
I normally use both -- a datepicker that populates a textfield in the correct format. Advanced users can edit the textfield directly, mouse-happy users can pick using the datepicker.
If you're worried about space, I usually have just the textfield with a little calendar icon next to it. If you click on the calendar icon it brings up the datepicker as a popup.
Also I find it good practice to pre-populate the textfield with text that indicates the correct format (i.e.: "DD/MM/YYYY"). When the user focuses the textfield that text disappears so they can enter their own.
I had this exact problem and this worked:
plt.savefig(output_dir + '/xyz.png', bbox_inches='tight')
Here is the documentation:
[https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html][1]
I wanted to add that if you are using a shared drive, enclose the path in double quotes and keep the backslashes. This is what worked for me:
$cd /path/to/"\\\share\users\username\My Documents\mydirectory\"
If this folder is the first in the command then it won't work with a space in the folder name, so replace the space in the folder name with an underscore.
You cannot execute Pipeline script locally, since its whole purpose is to script Jenkins. (Which is one reason why it is best to keep your Jenkinsfile
short and limited to code which actually deals with Jenkins features; your actual build logic should be handled with external processes or build tools which you invoke via a one-line sh
or bat
step.)
If you want to test a change to Jenkinsfile
live but without committing it, use the Replay feature added in 1.14
JENKINS-33925 tracks the desired for an automated test framework.
Just try to set local date earlier than Feb 14. Works for me! Not a complete solution but temporary solve the problem.
If you're using ASP.net 5 (MVC 6) or later then you can use the new Tag Helpers for a very nice syntax:
<select asp-for="tipo">
<option value="Exemplo1">Exemplo1</option>
<option value="Exemplo2">Exemplo2</option>
<option value="Exemplo3">Exemplo3</option>
</select>
I love empty if-else and while(0) operators.
For example:
#define CMD1(X) do { foo(x); bar(x); } while (0)
#define CMD2(X) if (1) { foo(x); bar(x); } else
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
Slightly better version of the unique2 suggestion is below:
insert overwrite table target_table
select * from
(
select stack(
3, # generating new table with 3 records
'John', 80, # record_1
'Bill', 61 # record_2
'Martha', 101 # record_3
)
) s;
Which does not require the hack with using an already exiting table.
Here is a simple class that handles both raw
and asset
files :
public class ReadFromFile {
public static String raw(Context context, @RawRes int id) {
InputStream is = context.getResources().openRawResource(id);
int size = 0;
try {
size = is.available();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
public static String asset(Context context, String fileName) {
InputStream is = null;
int size = 0;
try {
is = context.getAssets().open(fileName);
AssetFileDescriptor fd = null;
fd = context.getAssets().openFd(fileName);
size = (int) fd.getLength();
fd.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
private static String readFile(int size, InputStream is) {
try {
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
For example :
ReadFromFile.raw(context, R.raw.textfile);
And for asset files :
ReadFromFile.asset(context, "file.txt");
The easiest way I've found to do this is to write in markdown right from the start of the line. Press Ctrl+D
(shortcut for opening the markup input dialog) and type markdown. The normal wiki editor doesn't seem to be very good for precise formatting. It doesn't seem to know much about character styles and only knows paragraph styles.
Starting with .Net 4.5 you can use Task.Run to simply start an action:
void Foo(string args){}
...
Task.Run(() => Foo("bar"));
You don't need to wrap everything in a DIV to achieve basic styling on inputs.
input[type="text"] {margin: 0 0 10px 0;}
will do the trick in most cases.
Semantically, one <br/> tag is okay between elements to position them. When you find yourself using multiple <br/>'s (which are semantic elements) to achieve cosmetic effects, that's a flag that you're mixing responsibilities, and you should consider getting back to basics.
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
Add a container div for the image and the caption:
<div class="item">
<img src=""/>
<span class="caption">Text below the image</span>
</div>
Then, with a bit of CSS, you can make an automatically wrapping image gallery:
div.item {
vertical-align: top;
display: inline-block;
text-align: center;
width: 120px;
}
img {
width: 100px;
height: 100px;
background-color: grey;
}
.caption {
display: block;
}
div.item {_x000D_
/* To correctly align image, regardless of content height: */_x000D_
vertical-align: top;_x000D_
display: inline-block;_x000D_
/* To horizontally center images and caption */_x000D_
text-align: center;_x000D_
/* The width of the container also implies margin around the images. */_x000D_
width: 120px;_x000D_
}_x000D_
img {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
/* Make the caption a block so it occupies its own line. */_x000D_
display: block;_x000D_
}
_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
<img src=""/>_x000D_
<span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>
_x000D_
Updated answer
Instead of using 'anonymous' div and spans, you can also use the HTML5 figure
and figcaption
elements. The advantage is that these tags add to the semantic structure of the document. Visually there is no difference, but it may (positively) affect the usability and indexability of your pages.
The tags are different, but the structure of the code is exactly the same, as you can see in this updated snippet and fiddle:
<figure class="item">
<img src=""/>
<figcaption class="caption">Text below the image</figcaption>
</figure>
figure.item {_x000D_
/* To correctly align image, regardless of content height: */_x000D_
vertical-align: top;_x000D_
display: inline-block;_x000D_
/* To horizontally center images and caption */_x000D_
text-align: center;_x000D_
/* The width of the container also implies margin around the images. */_x000D_
width: 120px;_x000D_
}_x000D_
img {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
/* Make the caption a block so it occupies its own line. */_x000D_
display: block;_x000D_
}
_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
<img src=""/>_x000D_
<figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>
_x000D_
You must sort your data according your needs (es. in reverse order) and use select top query
In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")
This return entity type rather than object type
The problem is probably coming from the fact that Date is deprecated.
Consider using
java.util.Calendar
or
Edit 2015:
Java 8 and later has built-in the new java.time package, which is similar to Joda-Time.
Other answers have shown you how to use JUnit to set up test classes. JUnit is not the only Java test framework. Concentrating on the technical details of using a framework however detracts from the most important concepts that should be guiding your actions, so I will talk about those.
Testing (of all kinds of all kinds of things) compares the actual behaviour of something (The System Under Test, SUT) with its expected behaviour.
Automated testing can be done using a computer program. Because that comparison is being done by an inflexible and unintelligent computer program, the expected behaviour must be precisely and unambiguously known.
What a program or part of a program (a class or method) is expected to do is its specification. Testing software therefore requires that you have a specification for the SUT. This might be an explicit description, or an implicit specification in your head of what is expected.
Automated unit testing therefore requires a precise and unambiguous specification of the class or method you are testing.
But you needed that specification when you set out to write that code. So part of what testing is about actually begins before you write even one line of the SUT. The testing technique of Test Driven Development (TDD) takes that idea to an extreme, and has you create the unit testing code before you write the code to be tested.
Unit testing frameworks test your SUT using assertions. An assertion is a logical expression (an expression with a boolean
result type; a predicate) that must be true
if the SUT is behaving correctly. The specification must therefore be expressed (or re-expressed) as assertions.
A useful technique for expressing a specification as assertions is programming by contract. These specifications are in terms of postconditions. A postcondition is an assertion about the publicly visible state of the SUT after return from a method or a constructor. Some methods have postconditions
that are invariants, which are predicates that are true before and after execution of the method. A class can also be said to have invariants, which are postconditions of every constructor and method of the class, and hence should always be true. Postconditions (And invariants) are expressed only in terms of publicity visible state: public
and protected
fields, the values returned by returned by public
and protected
methods (such as getters), and the publicly visible state of objects passed (by reference) to methods.
Many beginners post questions here asking how they can test some code, presenting the code but without stating the specification for that code. As this discussion shows, it is impossible for anyone to give a good answer to such a question, because at best potential answereres must guess the specification, and might do so incorrectly. The asker of the question evidently does not understand the importance of a specification, and is thus a novice who needs to understand the fundamentals I've described here before trying to write some test code.
setTimeout(func, 5000);
-- it will call the function named func() after the time specified. here, 5000 milli seconds , i.e) after 5 seconds
string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";
string currentDirectory = Path.GetDirectoryName(fileAndPath);
string fullPathOnly = Path.GetFullPath(currentDirectory);
currentDirectory: c:\webserver\public\myCompany\configs
fullPathOnly: c:\webserver\public\myCompany\configs
var xStart, yStart = 0;
document.addEventListener('touchstart', function(e) {
xStart = e.touches[0].screenX;
yStart = e.touches[0].screenY;
});
document.addEventListener('touchmove', function(e) {
var xMovement = Math.abs(e.touches[0].screenX - xStart);
var yMovement = Math.abs(e.touches[0].screenY - yStart);
if((yMovement * 3) > xMovement) {
e.preventDefault();
}
});
Prevents default Safari scrolling and bounce gestures without detaching your touch event listeners.
If you just want to throw away everything in your working folder (eg the results of a failed or aborted merge) and revert to a clean previous commit, do a git reset --hard
.
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
Because Option 2 creates a new List
reference, and then creates an n
element array from the List
(option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use <
(not <=
). Like,
String[] out = new String[n];
for(int i = 0; i < n; i++) {
out[i] = in.get(i);
}
While quicksort is often a better choice than merge sort, there are definitely times when merge sort is thereotically a better choice. The most obvious time is when it's extremely important that your algorithm run faster than O(n^2). Quicksort is usually faster than this, but given the theoretical worst possible input, it could run in O(n^2), which is worse than the worst possible merge sort.
Quicksort is also more complicated than mergesort, especially if you want to write a really solid implementation, and so if you're aiming for simplicity and maintainability, merge sort becomes a promising alternative with very little performance loss.
You can make the pagebreak conditional on knitting to PDF. This worked for me.
```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```
var jArr = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tableData = '<table><tr><td>Id</td><td>Name</td><td>Category</td><td>Color</td></tr>';
$.each(jArr, function(index, data) {
tableData += '<tr><td>'+data.id+'</td><td>'+data.name+'</td><td>'+data.category+'</td><td>'+data.color+'</td></tr>';
});
$('div').html(tableData);
I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew
, but I missed installing gradle
using it.
To save some MBs by downloading it over again using Homebrew, I symlinked the gradle
binary from the downloaded (and extracted) zip archive in the /usr/local/bin/
. This is the same place where Homebrew symlinks all other binaries.
cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle
Now check whether it works or not:
gradle -v
I have been using Mobilizer, which is an awesome free app
Currently it has default simulation for Iphone4, Iphone5, Samsung Galaxt S3, Nokia Lumia, Palm Pre, Blackberry Storm and HTC Evo. Simple straightforward and effective.
Many have mentioned the python.pythonPath
method.
Another way is adding a envFile
in the launch.json
like this:
{
"name": "Run",
"etc": "etc",
"envFile": "${workspaceFolder}/venv"
}
Watch out for zero-byte .plugin files in the {WORKSPACE-DIR}/.metadata/.plugins folder. I just deleted one in there and it fixed my freezing issues.
Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").
I tend to write my module patterns like this:
(function (window) {
// Handle dependencies
var angular = window.angular,
$ = window.$,
document = window.document;
// Your application's code
}(window))
You can get these other performance benefits (explained more here):
window
object declaration gets minified as well. e.g. window.alert()
become m.alert()
.window
object.window
property or method, preventing expensive traversal of the scope chain e.g. window.alert()
(faster) versus alert()
(slower) performance.@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
jsonObject.addProperty(key, requestMapper.get(key)[0]);
}
All params will be stored in jsonObject
.
I have just given width to Label and input type were aligned automatically.
input[type="text"] {_x000D_
width:100px;_x000D_
height:30px;_x000D_
border-radius:5px;_x000D_
background-color: lightblue;_x000D_
margin-left:2px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
label{_x000D_
position:relative;_x000D_
width:300px;_x000D_
border:2px dotted black;_x000D_
margin:20px;_x000D_
padding:5px;_x000D_
font-family:AR CENA;_x000D_
font-size:20px;_x000D_
_x000D_
}
_x000D_
<label>First Name:</label><input type="text" name="fname"><br>_x000D_
<label>Last Name:</label><input type="text" name="lname"><br>
_x000D_
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
This is how a beginner wrapped one's head around Closures like a function is wrapped inside of a functions body also known as Closures.
Definition from the book Speaking JavaScript "A closure is a function plus the connection to the scope in which the function was created" -Dr.Axel Rauschmayer
So what could that look like? Here is an example
function newCounter() {
var counter = 0;
return function increment() {
counter += 1;
}
}
var counter1 = newCounter();
var counter2 = newCounter();
counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3
newCounter closes over increment, counter can be referenced to and accessed by increment.
counter1 and counter2 will keep track of their own value.
Simple but hopefully a clear perspective of what a closure is around all these great and advanced answers.
div {
height: 256px;
width: 256px;
display: table-cell;
text-align: center;
line-height: 256px;
}
The trick is to set the line-height
equal to the height
of the div
.
You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired.
Double d = null;
if (obj instanceof Double) {
d = (Double) obj;
}
Had the same issue, I solved the issue killing the process and then waiting for each process to finish using the PROC filesystem:
while [ -e /proc/${pid} ]; do sleep 0.1; done
As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize()
e.g.
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
So your controller could have a view model as the param e.g.
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
Alternatively if you just want to post some specific values you can do:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
With a controller like:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
If you are a Mac user and have keychain enabled, you to need to remove the authorization information that is stored in the keychain:
- Open up Keychain access
- Click "All items" under category in the left-hand column
- Search for git
- Delete all git entries.
Then you should change your username and email from the terminal using git config
:
$ git config --global user.name "Bob"
$ git config --global user.email "[email protected]"
Now if you try to push to the repository you will be asked for a username and password. Enter the login credentials you are trying to switch to. This problem normally pops up if you signed into GitHub on a browser using a different username and password or previously switched accounts on your terminal.
After studying some jQuery at Codeacademy I found a solution to bind a key with the animate property. The whole idea was to animate without scrolling to jump from one section to another. The example from Codeacademy was to move Mario through the DOM but I applied this for my website sections (CSS with 100% height). Here is a part of the code:
$(document).keydown(function(key) {
switch(parseInt(key.which, 10)) {
case 39:
$('section').animate({top: "-=100%"}, 2000);
break;
case 37:
$('section').animate({top: "+=100%"}, 2000);
break;
default:
break;
}
});
I think you could use this for any letter and property.
Source: http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e
You can try this too:
public class Match
{
[Key]
public int MatchId { get; set; }
[ForeignKey("HomeTeam"), Column(Order = 0)]
public int? HomeTeamId { get; set; }
[ForeignKey("GuestTeam"), Column(Order = 1)]
public int? GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.
In my case, this simple modification solve the problem.
Short answer? Sometimes.
Technically every abstraction has a cost and a programming language is an abstraction for how the CPU works. C however is very close. Years ago I remember laughing out loud when I logged onto my UNIX account and got the following fortune message (when such things were popular):
The C Programming Language -- A language which combines the flexibility of assembly language with the power of assembly language.
It's funny because it's true: C is like portable assembly language.
It's worth noting that assembly language just runs however you write it. There is however a compiler in between C and the assembly language it generates and that is extremely important because how fast your C code is has an awful lot to do with how good your compiler is.
When gcc came on the scene one of the things that made it so popular was that it was often so much better than the C compilers that shipped with many commercial UNIX flavours. Not only was it ANSI C (none of this K&R C rubbish), was more robust and typically produced better (faster) code. Not always but often.
I tell you all this because there is no blanket rule about the speed of C and assembler because there is no objective standard for C.
Likewise, assembler varies a lot depending on what processor you're running, your system spec, what instruction set you're using and so on. Historically there have been two CPU architecture families: CISC and RISC. The biggest player in CISC was and still is the Intel x86 architecture (and instruction set). RISC dominated the UNIX world (MIPS6000, Alpha, Sparc and so on). CISC won the battle for the hearts and minds.
Anyway, the popular wisdom when I was a younger developer was that hand-written x86 could often be much faster than C because the way the architecture worked, it had a complexity that benefitted from a human doing it. RISC on the other hand seemed designed for compilers so noone (I knew) wrote say Sparc assembler. I'm sure such people existed but no doubt they've both gone insane and been institutionalized by now.
Instruction sets are an important point even in the same family of processors. Certain Intel processors have extensions like SSE through SSE4. AMD had their own SIMD instructions. The benefit of a programming language like C was someone could write their library so it was optimized for whichever processor you were running on. That was hard work in assembler.
There are still optimizations you can make in assembler that no compiler could make and a well written assembler algoirthm will be as fast or faster than it's C equivalent. The bigger question is: is it worth it?
Ultimately though assembler was a product of its time and was more popular at a time when CPU cycles were expensive. Nowadays a CPU that costs $5-10 to manufacture (Intel Atom) can do pretty much anything anyone could want. The only real reason to write assembler these days is for low level things like some parts of an operating system (even so the vast majority of the Linux kernel is written in C), device drivers, possibly embedded devices (although C tends to dominate there too) and so on. Or just for kicks (which is somewhat masochistic).
For RHEL-mysql 5.5:
/etc/init.d/mysql stop
/etc/init.d/mysql start --skip-grant-tables
mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
mysql -uroot -pnewpwd
mysql>
Test the return value of grep:
./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
echo "matched"
fi
which is done idiomatically like so:
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
and also:
./somecommand | grep -q 'string' && echo 'matched'
Update your bootstrap process to create a ${HOME}/.gitconfig
with the proper contents, or to copy an existing one from somewhere.
It's rather safe to add @SafeVarargs
annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.
If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>
) input instead of varargs (Type1<Type2>...
).
As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.
To change the default character set and collation of a table including those of existing columns (note the convert to clause):
alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;
Edited the answer, thanks to the prompting of some comments:
Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41
and
That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46
In Bootstrap 4, you can add mx-auto
class to your img
tag.
For instance, if your image has a width of 75%, it should look like this:
<img class="d-block w-75 mx-auto" src="image.jpg" alt="First slide">
Bootstrap will automatically translate mx-auto
to:
ml-auto, .mx-auto {
margin-left: auto !important;
}
.mr-auto, .mx-auto {
margin-right: auto !important;
}
I have another approach for Intellij users, and it is working very fine for me:
Some context that I haven't seen clearly stated in the existing answers (and also a lot has changed since 2012!):
If you can control both the 3rd party iframe and the parent page (i.e. you are able to insert JavaScript on the parent page), then several workarounds are available. I would suggest the most elegant of these is making use of the postMessage API as described by @Frank's answer, as a) this does not require any redirects and b) does not require any user interactions.
If you do NOT control both the 3rd party iframe and the parent page, e.g. you have a widget hosted on a site you do not control, then most of the answers posted here will not work in Safari as of May 2020, and will stop working in Chrome around 2022. That is, unless a user has already visited your domain or interacts with the iframe, you are not able to set cookies. However, there are some commercial services offering solutions to solve this problem, such as CloudCookie.io
I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status
command Git Shell suggested to push changes as
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
I did the same as Git Shell suggested (git push
) and everything is ok now.
Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.
fatal: Not a git repository (or any of the parent directories):
For example if your Project is in D
drive in some folder you have to do something like below as you do in cmd
to change directory.
cd D:\someFolder // if your project is not deep in `D`
And if its within nested folder in D
cd D:\somefolder\someNestedFolder\nestedInNested // if your project is not deep in `D`
If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.
If your class extends Serializable
, you can write and read objects through a ByteArrayOutputStream
, that's what I usually do.
As other users said, cat() is probably the best option.
@krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:
The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.
There is no good reason to use sprintf() over cat or other options.
You can find every file what is created/modified in the last day, use this example:
find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print
for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
With Java 8 you can use stream
and collect
to copy the items:
Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());
Or you can collect to an ImmutableSet
(if you know that the set should not change):
Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
So, take a look here:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
As you can see, requiring json
has magically brought method to_json
to our Hash
.
Some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
Map is interface and Hashmap is a class that implements Map Interface
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if head
is NULL, if yes the list is empty and we just return
Save the head
in a tmp
variable, and make head
point to the next node on your list (this is done in head = head->next
free(tmp)
variable, and head
just points to the rest of the list, go back to step 1 For those checking this around the year 2020:
Microsoft's System.Text.Json namespace is the new king in town. In terms of performance, it is the best as far as I can tell:
var model = new Model
{
Name = "Test Name",
Age = 5
};
string json = JsonSerializer.Serialize(model);
As some others have mentioned, NewtonSoft.Json is a very nice library as well.
You can call a stored procedure using SqlQuery
(See here)
// Prepare the query
var query = context.Functions.SqlQuery(
"EXEC [dbo].[GetFunctionByID] @p1",
new SqlParameter("p1", 200));
// add NoTracking() if required
// Fetch the results
var result = query.ToList();
I met the same problem in Win10 32bit OS. I resolved the problem by changing the DLL from debug to release version.
I think it is because the debug version DLL depends on other DLL, and the release version did not.
For all who search to return something and then for another call throw exception:
when(mockFoo.someMethod())
.thenReturn(obj1)
.thenReturn(obj2)
.thenThrow(new RuntimeException("Fail"));
or
when(mockFoo.someMethod())
.thenReturn(obj1, obj2)
.thenThrow(new RuntimeException("Fail"));
To complement the existing helpful answers:
Using Bash's own regex-matching operator, =~
, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:
set -- '12-34-5678' # set $1 to sample value
kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match
Note, however, that the caveat re using flavor-specific regex constructs such as \d
equally applies:
While =~
supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.
To remain portable (in the context of Bash), stick to the POSIX ERE specification.
Note that =~
even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]}
array variable.
Further notes:
$kREGEX_DATE
is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).
While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \
.
\<
is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes
doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes
does.I've changed variable name REGEX_DATE
to kREGEX_DATE
(k
signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.
Try using input type="tel"
instead. It pops up a keyboard with numbers, and it doesn’t show spin boxes. It requires no JavaScript or CSS or plugins or anything else.
SELECT IF((
SELECT count(*) FROM gdata_calendars
WHERE `group` = ? AND id = ?)
,1,0);
For Detail explanation you can visit here
In My case, it just happens to be that even though i receive the data in the format of a model like myMethod(data:MyModelClass)
object till the received object was of type string.
Which is y in console.log(data) i get the content.
Solution is just to parse the JSON(in my case)
const model:MyMOdelClass=JSON.parse(data);
Thought may be usefull.
Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"
here's a working version for MSSQL 2000. I've modified the 2005 code found here: http://sqlfool.com/2011/01/identity-columns-are-you-nearing-the-limits/
/* Define how close we are to the value limit
before we start throwing up the red flag.
The higher the value, the closer to the limit. */
DECLARE @threshold DECIMAL(3,2);
SET @threshold = .85;
/* Create a temp table */
CREATE TABLE #identityStatus
(
database_name VARCHAR(128)
, table_name VARCHAR(128)
, column_name VARCHAR(128)
, data_type VARCHAR(128)
, last_value BIGINT
, max_value BIGINT
);
DECLARE @dbname sysname;
DECLARE @sql nvarchar(4000);
-- Use an cursor to iterate through the databases since in 2000 there's no sp_MSForEachDB command...
DECLARE c cursor FAST_FORWARD FOR
SELECT
name
FROM
master.dbo.sysdatabases
WHERE
name NOT IN('master', 'model', 'msdb', 'tempdb');
OPEN c;
FETCH NEXT FROM c INTO @dbname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = N'Use [' + @dbname + '];
Insert Into #identityStatus
Select ''' + @dbname + ''' As [database_name]
, Object_Name(id.id) As [table_name]
, id.name As [column_name]
, t.name As [data_type]
, IDENT_CURRENT(Object_Name(id.id)) As [last_value]
, Case
When t.name = ''tinyint'' Then 255
When t.name = ''smallint'' Then 32767
When t.name = ''int'' Then 2147483647
When t.name = ''bigint'' Then 9223372036854775807
End As [max_value]
From
syscolumns As id
Join systypes As t On id.xtype = t.xtype
Where
id.colstat&1 = 1 -- this identifies the identity columns (as far as I know)
';
EXECUTE sp_executesql @sql;
FETCH NEXT FROM c INTO @dbname;
END
CLOSE c;
DEALLOCATE c;
/* Retrieve our results and format it all prettily */
SELECT database_name
, table_name
, column_name
, data_type
, last_value
, CASE
WHEN last_value < 0 THEN 100
ELSE (1 - CAST(last_value AS FLOAT(4)) / max_value) * 100
END AS [percentLeft]
, CASE
WHEN CAST(last_value AS FLOAT(4)) / max_value >= @threshold
THEN 'warning: approaching max limit'
ELSE 'okay'
END AS [id_status]
FROM #identityStatus
ORDER BY percentLeft;
/* Clean up after ourselves */
DROP TABLE #identityStatus;
If you aren't totally sure what you mean by "uncommit" and don't know if you want to use git reset
, please see "Revert to a previous Git commit".
If you're trying to understand git reset
better, please see "Can you explain what "git reset" does in plain English?".
If you know you want to use git reset
, it still depends what you mean by "uncommit". If all you want to do is undo the act of committing, leaving everything else intact, use:
git reset --soft HEAD^
If you want to undo the act of committing and everything you'd staged, but leave the work tree (your files intact):
git reset HEAD^
And if you actually want to completely undo it, throwing away all uncommitted changes, resetting everything to the previous commit (as the original question asked):
git reset --hard HEAD^
The original question also asked it's HEAD^
not HEAD
. HEAD
refers to the current commit - generally, the tip of the currently checked-out branch. The ^
is a notation which can be attached to any commit specifier, and means "the commit before". So, HEAD^
is the commit before the current one, just as master^
is the commit before the tip of the master branch.
Here's the portion of the git-rev-parse documentation describing all of the ways to specify commits (^
is just a basic one among many).
In the URL that you are redirected to (you may have to look in Chrome dev tools for this URL), change the realm from master
to the one you just created, and if you are not using https
, then make sure the redirect_uri is also using http
.
Step 1) Follow this documentation to setup a MySql database. You may also need to refer to the official documentation.
Step 2)
Run the command update REALM set ssl_required = 'NONE' where id = 'master';
Note: At this point, you should technically be able to login, but version 4.0 of Keycloak is using https for the redirect uri even though we just turned off https support. Until Keycloak fixes this, we can get around this with a reverse proxy. A reverse proxy is something we will want to use anyhow to easily create SSL/TLS certificates without having to worry about Java keystores.
Note 2: Keycloak has since come out with their own proxy. I haven't tried this yet, but at this point, you might want to stop following my directions and check out (keycloak gatekeeper)[https://www.keycloak.org/downloads.html]. If you have trouble setting up the Keycloak Gatekeeper, I'll keep my instructions around for setting up a reverse proxy with Apache.
Step 3) Install Apache. We will use Apache as a reverse proxy (I tried NGINX, but NGINX had some limitations that got in the way). See yum installing Apache (CentOs 7), and apt-get install Apache (Ubuntu 16), or find instructions for your specific distro.
Step 4) Run Apache
Use sudo systemctl start httpd
(CentOs) or sudo systemctl start apache2
(Ubuntu)
Use sudo systemctl status httpd
(CentOs) or sudo systemctl status apache2
(Ubuntu) to check if Apache is running. If you see in green text the words active (running)
or if the last entry reads Started The Apache HTTP Server.
then you're good.
Step 5) We will establish a SSL connection with the reverse proxy, and then the reverse proxy will communicate to keyCloak over http. Because this http communication is happening on the same machine, you're still secure. We can use Certbot to setup auto-renewing certificates.
If this type of encryption is not good enough, and your security policy requires end-to-end encryption, you will have to figure out how to setup SSL through WildFly, instead of using a reverse proxy.
Note: I was never actually able to get https to work properly with the admin portal. Perhaps this may have just been a bug in the beta version of Keycloak 4.0 that I'm using. You're suppose to be able to set the SSL level to only require it for external requests, but this did not seem to work, which is why we set https to none in step #2. From here on we will continue to use http over an SSH tunnel to manage the admin settings.
Step 6) Whenever you try to visit the site via https, you will trigger an HSTS policy which will auto-force http requests to redirect to https. Follow these instructions to clear the HSTS rule from Chrome, and then for the time being, do not visit the https version of the site again.
Step 7)
Configure Apache.
First find where your httpd.conf file is located. Your httpd.conf file is probably including config files from a separate directory. In my case, I found all of my config file in a conf.d
directory located adjacent to the folder the httpd.conf file was in.
Once you find your conf files, change out, or add the following, virtual host entries in your conf files. Make sure you don't override the already present SSL options that where generated by certbot. When done, your config file should look something like this.
<VirtualHost *:80>
RewriteEngine on
#change https redirect_uri parameters to http
RewriteCond %{request_uri}\?%{query_string} ^(.*)redirect_uri=https(.*)$
RewriteRule . %1redirect_uri=http%2 [NE,R=302]
#uncomment to force https
#does not currently work
#RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI}
#forward the requests on to keycloak
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>
RewriteEngine on
#Disable HSTS
Header set Strict-Transport-Security "max-age=0; includeSubDomains;" env=HTTPS
#change https redirect_uri parameters to http
RewriteCond %{request_uri}\?%{query_string} ^(.*)redirect_uri=https(.*)$
RewriteRule . %1redirect_uri=http%2 [NE,R=302]
#forward the requests on to keycloak
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
#Leave the items added by certbot alone
#There should be a ServerName option
#And a bunch of options to configure the location of the SSL cert files
#Along with an option to include an additional config file
</VirtualHost>
</IfModule>
Step 8) Restart Apache. Use sudo systemctl restart httpd
(CentOs) or sudo systemctl restart apache2
(Ubuntu).
Step 9) Before you have a chance to try to login to the server, since we told Keycloak to use http, we need to setup another method of connecting securely. This can be done by either installing a VPN service on the keycloak server, or by using SOCKS. I used a SOCKS proxy. In order to do this, you'll first need to setup dynamic port forwarding.
ssh -N -D 9905 [email protected]
Or set it up via Putty.
All traffic sent to port 9905 will now be securely routed through an SSH tunnel to your server. Make sure you whitelist port 9905 on your server's firewall.
Once you have dynamic port forwarding setup, you will need to setup your browser to use a SOCKS proxy on port 9905. Instructions here.
Step 10) You should now be able to login to the Keycloak admin portal. To connect to the website go to http://127.0.0.1, and the SOCKS proxy will take you to the admin console. Make sure you turn off the SOCKS proxy when you're done as it does utilize your server's resources, and will result in a slower internet speed for you if kept on.
Step 11) Don't ask me how long it took me to figure all of this out.
On my linux system to get just the filenames
diff -q /dir1 /dir2|cut -f2 -d' '
You can make extension to just change one color component
static class ColorExtension
{
public static Color ChangeG(Color this color,byte g)
{
return Color.FromArgb(color.A,color.R,g,color.B);
}
}
then you can use this:
yourColor = yourColor.ChangeG(100);
I had the same problem and was solved by running the following in run
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
Well, to answer the immediate question:
>>> s = "http://www.domain.com/?s=some&two=20"
The rfind
method returns the index of right-most substring:
>>> s.rfind("&")
29
You can take all elements up to a given index with the slicing operator:
>>> "foobar"[:4]
'foob'
Putting the two together:
>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'
If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two
from the above query string:
First, parse the URL as a whole:
>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')
Take out just the query string:
>>> query_s = parse_result.query
>>> query_s
's=some&two=20'
Turn it into a dict
:
>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']
Remove the 'two'
key from the dict:
>>> del query_d['two']
>>> query_d
{'s': ['some']}
Put it back into a query string:
>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'
And now stitch the URL back together:
>>> result = urlparse.urlunsplit((
parse_result.scheme, parse_result.netloc,
parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'
The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two
argument, even if it was put earlier in the query string ("two=20&s=some"
), this would still do the right thing. It might be overkill depending on what you want to do.
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub
Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.
position:absolute;
top:0; bottom:0; left:0; right:0;
margin:auto;
If you have url like https://myapp.com/owner/123/show?height=23 then use
combineLatest( [this.route.paramMap, this.route.queryParamMap] )
.subscribe( ([pathParams, queryParams]) => {
let ownerId = pathParams.get('ownerId'); // =123
let height = queryParams.get('height'); // =height
// ...
})
In case when you use this.router.navigate([yourUrl]);
and your query parameters are embedded in yourUrl
string then angular encodes a URL and you get something like this https://myapp.com/owner/123/show%3Fheight%323 - and above solution will give wrong result (queryParams will be empty, and query params can be glued to last path param if it is on the path end). In this case change the way of navigation to this
this.router.navigateByUrl(yourUrl);
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
You can join a table to itself as many times as you require, it is called a self join.
An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.
SELECT a.SelfJoinTableID
FROM dbo.SelfJoinTable a
INNER JOIN dbo.SelfJoinTable b
ON a.SelfJoinTableID = b.SelfJoinTableID
INNER JOIN dbo.SelfJoinTable c
ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE a.Status = 'Status to filter a'
AND b.Status = 'Status to filter b'
AND c.Status = 'Status to filter c'
For Ubuntu (not only?):
see Sergeis Answer but instead of openssl use zlib-flate:
cat appbackup.ab | (dd bs=24 count=0 skip=1; cat) | zlib-flate -uncompress > appbackup.tar
Otherwise openssl will probably throw:
openssl:Error: 'zlib' is an invalid command.
because openssl is not compiled with zlib support in Ubuntu
You can change the port while you open your XAMP control panel, follow the steps:
httpd.conf
, a text file will openlisten:80
,listen:80
replace with listen:8080
andOnce done that, you will be able to start your local server.
If you want to remove all lines in a file from your current line number, use dG
, it will delete all lines (shift g)
mean end of file
The discoverability is dismal, but it's quite clever how Advanced Rest Client handles basic authentication. The shortcut abraham mentioned didn't work for me, but a little poking around revealed how it does it.
The first thing you need to do is add the Authorization
header:
Then, a nifty little thing pops up when you focus the value
input (note the "construct" box in the lower right):
Clicking it will bring up a box. It even does OAuth, if you want!
Tada! If you leave the value field blank when you click "construct," it will add the Basic
part to it (I assume it will also add the necessary OAuth stuff, too, but I didn't try that, as my current needs were for basic authentication), so you don't need to do anything.
Use a DecimalFormat object with a format string of "0.#".
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
1.Go to Windows-->Preferences-->Java-->Installed JREs-->Execution Environments
2.select the java version you are using currently in the "Execution Environments" box. So that in the "Compatible JREs" box, you are able to see as "jre1.8.0_102[perfect match]"(if your java version is 1.8). Then try to build using maven.
You create buttons dynamically because of that you need to call them with .live()
method if you use jquery 1.7
but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:
$(document).on('click', 'selector', function(){
// Your Code
});
For Example
If your html is something like this
<div id="btn-list">
<div class="btn12">MyButton</div>
</div>
You can write your jquery like this
$(document).on('click', '#btn-list .btn12', function(){
// Your Code
});
In this case, to validate Date (DD-MM-YYYY) or (DD/MM/YYYY), with a year between 1900 and 2099,like this with month and Days validation
if (!Regex.Match(txtDob.Text, @"^(0[1-9]|1[0-9]|2[0-9]|3[0,1])([/+-])(0[1-9]|1[0-2])([/+-])(19|20)[0-9]{2}$").Success)
{
MessageBox.Show("InValid Date of Birth");
txtDob.Focus();
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
I know this is an old question, but in Python 3.7 you can do this using asyncio
and aiohttp
.
import asyncio
import aiohttp
from aiohttp import ClientSession, ClientConnectorError
async def fetch_html(url: str, session: ClientSession, **kwargs) -> tuple:
try:
resp = await session.request(method="GET", url=url, **kwargs)
except ClientConnectorError:
return (url, 404)
return (url, resp.status)
async def make_requests(urls: set, **kwargs) -> None:
async with ClientSession() as session:
tasks = []
for url in urls:
tasks.append(
fetch_html(url=url, session=session, **kwargs)
)
results = await asyncio.gather(*tasks)
for result in results:
print(f'{result[1]} - {str(result[0])}')
if __name__ == "__main__":
import pathlib
import sys
assert sys.version_info >= (3, 7), "Script requires Python 3.7+."
here = pathlib.Path(__file__).parent
with open(here.joinpath("urls.txt")) as infile:
urls = set(map(str.strip, infile))
asyncio.run(make_requests(urls=urls))
You can read more about it and see an example here.
If you're on Windows you just probably change filename to lower/upper case like File.txt - file.txt
So check what file you have in git and rename it to what you want:
git status
Then I need file.txt -> but git status gaves me File.txt so just rename it
git mv File.txt file.txt
And problem is solved.
You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:
$(window).resize(function() {
// This will execute whenever the window is resized
$(window).height(); // New height
$(window).width(); // New width
});
You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em
units and percentages and min-width
and max-width
in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.
just use this,
utf8_encode($string);
you've to replace your $arr
with $string
.
I think it will work...try this.
string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
It is cd
for "current directory".
For Arch Linux try this :
sudo vboxreload
Angular 2 provides good support for uploading files. No third party library is required.
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"
You could regex it:
"string".replace(/^\/?|\/?$/, "")
"/installers/services/".replace(/^\/?|\/?$/, "") // -> installers/services
The regex explained:
- Optional first slash: ^/?
, escaped -> ^\/?
(the ^
means beginning of string)
- The pipe ( | ) can be read as or
- Than the option slash at the end -> /?$
, escaped -> \/?$
( the $
means end of string)
Combined it would be ^/?|/$
without escaping. Optional first slash OR optional last slash
diff -r
will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Works for any combination of tbody/thead/tfoot and td/th
table.inner-border {_x000D_
border-collapse: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
table.inner-border > thead > tr > th,_x000D_
table.inner-border > thead > tr > td,_x000D_
table.inner-border > tbody > tr > th,_x000D_
table.inner-border > tbody > tr > td,_x000D_
table.inner-border > tfoot > tr > th,_x000D_
table.inner-border > tfoot > tr > td {_x000D_
border-bottom: 1px solid black;_x000D_
border-right: 1px solid black;_x000D_
}_x000D_
_x000D_
table.inner-border > thead > tr > :last-child,_x000D_
table.inner-border > tbody > tr > :last-child,_x000D_
table.inner-border > tfoot > tr > :last-child {_x000D_
border-right: 0;_x000D_
}_x000D_
_x000D_
table.inner-border > :last-child > tr:last-child > td,_x000D_
table.inner-border > :last-child > tr:last-child > th {_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<table class="inner-border">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>head1,1</th>_x000D_
<td>head1,2</td>_x000D_
<td>head1,3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>head2,1</td>_x000D_
<td>head2,2</td>_x000D_
<th>head2,3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tr>_x000D_
<td>1,1</td>_x000D_
<th>1,2</th>_x000D_
<td>1,3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2,1</td>_x000D_
<td>2,2</td>_x000D_
<td>2,3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3,1</td>_x000D_
<td>3,2</td>_x000D_
<td>3,3</td>_x000D_
</tr>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>foot1,1</th>_x000D_
<td>foot1,2</td>_x000D_
<td>foot1,3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>foot2,1</td>_x000D_
<th>foot2,2</th>_x000D_
<th>foot2,3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".
and install the package. it will resolve the issue for me.
Use the following program for select the multiple values from select box.
multi.php
<?php
print <<<_HTML_
<html>
<body>
<form method="post" action="value.php">
<select name="flower[ ]" multiple>
<option value="flower">FLOWER</option>
<option value="rose">ROSE</option>
<option value="lilly">LILLY</option>
<option value="jasmine">JASMINE</option>
<option value="lotus">LOTUS</option>
<option value="tulips">TULIPS</option>
</select>
<input type="submit" name="submit" value=Submit>
</form>
</body>
</html>
_HTML_
?>
value.php
<?php
foreach ($_POST['flower'] as $names)
{
print "You are selected $names<br/>";
}
?>
I was getting the same error today:
Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.
What I did:
27.1.1
instead of 26.1.0
compileSdkVersion 27
and targetSdkVersion 27
which were 26
earlierAnd com.android.support:support-annotations
error was gone!
For Ref:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).
Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.
What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!
All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.
Try changing your workspace. I am not sure this is the exact solution . I did face the same issue for sometime untill i changed my workspace.
I recommend this library from Hannes Dorfmann. It encapsulates all the logic related to particular view type in a separate object called "AdapterDelegate". https://github.com/sockeqwe/AdapterDelegates
public class CatAdapterDelegate extends AdapterDelegate<List<Animal>> {
private LayoutInflater inflater;
public CatAdapterDelegate(Activity activity) {
inflater = activity.getLayoutInflater();
}
@Override public boolean isForViewType(@NonNull List<Animal> items, int position) {
return items.get(position) instanceof Cat;
}
@NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false));
}
@Override public void onBindViewHolder(@NonNull List<Animal> items, int position,
@NonNull RecyclerView.ViewHolder holder, @Nullable List<Object> payloads) {
CatViewHolder vh = (CatViewHolder) holder;
Cat cat = (Cat) items.get(position);
vh.name.setText(cat.getName());
}
static class CatViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public CatViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
}
}
}
public class AnimalAdapter extends ListDelegationAdapter<List<Animal>> {
public AnimalAdapter(Activity activity, List<Animal> items) {
// DelegatesManager is a protected Field in ListDelegationAdapter
delegatesManager.addDelegate(new CatAdapterDelegate(activity))
.addDelegate(new DogAdapterDelegate(activity))
.addDelegate(new GeckoAdapterDelegate(activity))
.addDelegate(23, new SnakeAdapterDelegate(activity));
// Set the items from super class.
setItems(items);
}
}
mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds | Query | 0 | init | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds | Sleep | 4 | | NULL |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)
mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)
USER 192 :
mysql> SELECT * FROM exept;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query
import java.awt.MouseInfo;
import java.util.concurrent.TimeUnit;
public class Cords {
public static void main(String[] args) throws InterruptedException {
//get cords of mouse code, outputs to console every 1/2 second
//make sure to import and include the "throws in the main method"
while(true == true)
{
TimeUnit.SECONDS.sleep(1/2);
double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
System.out.println("X:" + mouseX);
System.out.println("Y:" + mouseY);
//make sure to import
}
}
}
Whoa. You're really over-complicating it by a very long distance. Try:
>>> print hex(0x12ef ^ 0xabcd)
0xb922
You seem to be ignoring these handy facts, at least:
0x
prefix.hex()
function can be used to convert any number into a hexadecimal string for display.If you already have the numbers as strings, you can use the int()
function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):
>>> print int("12ef", 16)
4874
So you can do two conversions, perform the XOR, and then convert back to hex:
>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
An endpoint is the 'connection point' of a service, tool, or application accessed over a network. In the world of software, any software application that is running and "listening" for connections uses an endpoint as the "front door." When you want to connect to the application/service/tool to exchange data you connect to its endpoint
Track the remote branch
You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:
Edit your .git/config
[branch "master"]
remote = origin
merge = refs/heads/master
Now you can simply git push and git pull.
[source]
You can also use this code in onCreate()
method:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
When You want to open new tab/window (depends on Your browser configuration defaults):
output = 'Hello, World!';
window.open().document.write(output);
When output is an Object
and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)
output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));
Update
Google Chrome (60.0.3112.90) block this code:
Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9
When You want to append some data to existing page
output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;
output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;
:-) Sunday | 0 -> Sun
|
Monday | 1 -> Mon
Tuesday | 2 -> Tue
Wednesday | 3 -> Wed
Thursday | 4 -> Thu
Friday | 5 -> Fri
Saturday | 6 -> Sat
|
:-) Sunday | 7 -> Sun
As you can see above, and as said before, the numbers 0
and 7
are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.
Examples of Number or Abbreviation Use
15 09 * * 5,6,0 command
15 09 * * 5,6,7 command
15 09 * * 5-7 command
15 09 * * Fri,Sat,Sun command
The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.
In Detail
Having two numbers 0
and 7
for Sunday can be useful for writing weekday ranges starting with 0
or ending with 7
. So you can write ranges starting with Sunday or ending with it, like 0-2
or 5-7
for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.
Corrupt Permissions: Regaining access to a folder and its sub-objects
Although most of the answers posted in reply to the question have some merit, IMHO none of them give a complete solution. The following (might be) a perfect solution for Windows 7 if you are locked-out of a folder by corrupted permission settings:
icacls "c:\folder" /remove:d /grant:r Everyone:(OI)(CI)F /T
For Windows 10 the user/SID must be specified after the /remove:d
option:
icacls "c:\folder" /remove:d Everyone /grant:r Everyone:(OI)(CI)F /T
.
Notes:
The command is applied to the specified directory.
Specifying the user "Everyone" sets the widest possible permission, as it includes every possible user.
The option "/remove:d" deletes any explicit DENY settings that may exist, as those override explicit ALLOW settings: a necessary preliminary to creating a new ALLOW setting. This is only a precaution, as there is often no DENY setting present, but better safe than sorry.
The option "/grant" creates a new ALLOW setting, an explicit permission that replaces (":r") any and all explicit ALLOW settings that may exist.
The "F" parameter (i.e. the permission created) makes this a grant of FULL control.
The "/T" parameter adds recursion, applying these changes to all current sub-objects in the specified directory (i.e. files and subfolders), as well as the folder itself.
The "(OI)" and "(CI)" parameters also add recursion, applying these changes to sub-objects created subsequently.
.
ADDENDUM (2019/02/10) -
The Windows 10 command line above was kindly suggested to me today, so here it is. I haven't got Windows 10 to test it, but please try it out if you have (and then will you please post a comment below).
The change only concerns removing the DENY setting as a first step. There might well not be any DENY setting present, so that option might make no difference. My understanding is, on Windows 7, that you don't need to specify a user after /remove:d but I might be wrong about that!
.
ADDENDUM (2019/11/21) -
User astark recommends replacing Everyone with the term *S-1-1-0 in order for the command to be language independent. I only have an English install of Windows, so I can't test this proposal, but it seems reasonable.
This may not be your problem, but I got this error when I accidentally included two identical (but differently named) libraries in the dependencies{} section of the project.
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production
calls my production task and sets a flag for any conditionals.
int i= Array.IndexOf(temp1, temp1.Where(x=>x.Contains("abc")).FirstOrDefault());
I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
In a helper class (HelperMethods) I created the following method:
public static List<string> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
}
When you call this helper you will get the list of item descriptions.
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
/* how to use
MyEnum x = MyEnum.NeedMoreCoffee;
string description = x.GetDescription();
*/
}
one simple workaround is to catch the exception :
try {
alertDialog.show()
}
catch (WindowManager.BadTokenException e) {
//use a log message
}
It's not elegant but sometimes easy when you have to manage async operations and you are not sure wether activity is up or not when you want to show the dialog.
Change branch, discarding all local modifications
git checkout -f 9-sign-in-out
Rename the current branch to master, discarding current master
git branch -M master
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
As nobody published a solution with CountDownLatch. What about:
public class Lockeable {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public void doAfterEvent(){
countDownLatch.await();
doSomething();
}
public void reportDetonatingEvent(){
countDownLatch.countDown();
}
}
dochoffiday's answer is a great starting point, but for me it did not cut it (the CSS part needed a buff) so I made a modified version with several improvements.
See it in action, then come back for the description.
(function ($) {
$.fn.styleTable = function (options) {
var defaults = {
css: 'ui-styled-table'
};
options = $.extend(defaults, options);
return this.each(function () {
$this = $(this);
$this.addClass(options.css);
$this.on('mouseover mouseout', 'tbody tr', function (event) {
$(this).children().toggleClass("ui-state-hover",
event.type == 'mouseover');
});
$this.find("th").addClass("ui-state-default");
$this.find("td").addClass("ui-widget-content");
$this.find("tr:last-child").addClass("last-child");
});
};
})(jQuery);
Differences with the original version:
ui-styled-table
(it sounds more consistent).live
call was replaced with the recommended .on
for jQuery 1.7 upwards.toggleClass
(a terser equivalent)first
on table cells has been removed.last-child
to the last table row is necessary to fix a visual glitch on Internet Explorer 7 and Internet Explorer 8; for browsers that support :last-child
it is not necessary/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }
/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
font-weight: inherit;
*font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}
/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }
/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }
/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }
/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }
/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }
I have tested this on Internet Explorer 7 and upwards, Firefox 11 and Google Chrome 18 and confirmed that it works perfectly. I have not tested reasonably earlier versions of Firefox and Chrome or any version of Opera; however, those browsers are well-known for good CSS support and since we are not using any bleeding-edge functionality here I assume it will work just fine there as well.
If you are not interested in Internet Explorer 7 support there is one CSS attribute (introduced with the star hack) that can go.
If you are not interested in Internet Explorer 8 support either, the CSS and JavaScript related to adding and targeting the last-child
CSS class can go as well.
Using Laravel 4.2 without Carbon
Here's how I grab the recent ten days and count each row with same day created_at timestamp.
$q = Spins::orderBy('created_at', 'desc')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->take(10)
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "views"')
));
foreach ($q as $day) {
echo $day->date. " Views: " . $day->views.'<br>';
}
Hope this helps
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
I run this
var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);
$.ajax({
type: 'GET',
url: 'linkserverApi',
success: function(success) {
console.log('Success!');
console.log(success);
},
error: function() {
console.log('Uh Oh!');
},
jsonp: 'jsonp'
});
And edit header in the response
'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'
'Access-Control-Max-Age' , '3628800'
'Access-Control-Allow-Origin', 'websiteresponseUrl'
'Content-Type', 'text/javascript; charset=utf8'
You are using an adjacent sibling selector (+
) when the elements are not siblings. The label is the parent of the input, not it's sibling.
CSS has no way to select an element based on it's descendents (nor anything that follows it).
You'll need to look to JavaScript to solve this.
Alternatively, rearrange your markup:
<input id="foo"><label for="foo">…</label>
When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.
try
lbnkVidTtile1.Enabled = true;
I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.
Use System.DateTime.Now.ToUniversalTime()
. That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.
I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?
Here's what I did:
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
And annotated each Date field's setter method with this:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
Cause you need to add jQuery library to your file:
jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.
<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>
You add to the back state from the FragmentTransaction
and remove from the backstack using FragmentManager
pop methods:
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();
An easy way of doing it is using this :)
var word = "waffle"
word.endsWith("e")
Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:
Your friend pushes his changes to GitHub:
git push origin <branch>
Clone the remote repository if you haven't already:
git clone https://[email protected]/abc/theproject.git
Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):
git fetch origin
git merge origin/<branch>
Note that git pull
is the same as doing the two steps above:
git pull origin <branch>
On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.
In my case, I had :
Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
rpc error: code = Unknown desc = error pulling image configuration: unknown blob
It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.