RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
After a restart I could not connect with the local mariadb, a search also brought me to this page and I wanted to share my solution with you.
I noticed that the directory my.cnf.d in /usr/local/etc/ is missing.
This is a known bug with homebrew that is described and solved there. https://github.com/Homebrew/homebrew-core/issues/36801
fast way to fix: mkdir /usr/local/etc/my.cnf.d
None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.
This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreach
loop on the .SelectedItems
, casting each item as a DataRowView
:
if (listView1.SelectedItems.Count > 0)
{
foreach (DataRowView drv in listView1.SelectedItems)
{
string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
// ... do something with these values before they are replaced
// by the next run of the loop that will get the next row
}
}
This will work, whether you have 1 item or many. It's funny that MSDN says to use ListView.SelectedListViewItemCollection
to capture listView1.SelectedItems
and iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'
.
You can truncate all information after the month using date_trunc(text, timestamp)
:
select date_trunc('month',created_at)::date as date
from orders
order by date DESC;
created_at = '2019-12-16 18:28:13'
Output 1:
date_trunc('day',created_at)
// 2019-12-16 00:00:00
Output 2:
date_trunc('day',created_at)::date
// 2019-12-16
Output 3:
date_trunc('month',created_at)::date
// 2019-12-01
Output 4:
date_trunc('year',created_at)::date
// 2019-01-01
You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
The maximum size for an int is 2147483647. You could use an Int64/Long which is far larger.
Simple way:
function displayChange(){
$(content_id).click(function(){
$(elem_id).toggle();}
)}
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
Passing data in the session If the data doesn't need to be passed to the client-side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.
Security Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client-side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?
As you are clearly just getting started here, it is worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!
Here is my batch script that I put together based on the good answers here & in other posts
You can set title timeout & even sleep to schedule it for latter & \n for new line
Name it popup.bat & put it in your windows path folder to work globally on your pc
For example popup Line 1\nLine 2
will produce a 2 line popup box
(type popup /?
for usage)
Here is the code
<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1] set pop.key=Ok
if %pop.key% == [2] set pop.key=Cancel
if %pop.key% == [3] set pop.key=Abort
if %pop.key% == [4] set pop.key=Retry
if %pop.key% == [5] set pop.key=Ignore
if %pop.key% == [6] set pop.key=Yes
if %pop.key% == [7] set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b
-- End CMD -->
<job><script language="VBScript">
'on error resume next
q =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup = 0
Title = "Popup"
Timeout = 0
Mode = 0
Message = ""
Sleep = 0
button = 0
If objArgs.Count = 0 Then
Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then
Usage()
End If
noWait = Not wait()
For Each arg in objArgs
If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch = True
Next
If not haveSwitch Then
Message=joinParam("woq")
Else
For i = 0 To objArgs.Count-1
If IsSwitch(objArgs(i)) Then
S=split(objArgs(i) , ":" , 2)
select case Lcase(S(0))
case "/m","/message"
Message=S(1)
case "/tt","/title"
Title=S(1)
case "/s","/sleep"
If IsNumeric(S(1)) Then Sleep=S(1)*1000
case "/t","/time"
If IsNumeric(S(1)) Then Timeout=S(1)
case "/b","/button"
select case S(1)
case "oc", "1"
button=1
case "ari","2"
button=2
case "ync","3"
button=3
case "yn", "4"
button=4
case "rc", "5"
button=5
case "ctc","6"
button=6
case Else
button=0
end select
case "/i","/icon"
select case S(1)
case "s","x","stop","16"
Mode=16
case "?","q","question","32"
Mode=32
case "!","w","warning","exclamation","48"
Mode=48
case "i","information","info","64"
Mode=64
case Else
Mode=0
end select
end select
End If
Next
End If
Message = Replace(Message,"/\n", "°" )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0
Wscript.Sleep(sleep)
Popup = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup
Function IsSwitch(Val)
IsSwitch = False
If Mid(Val,1,1) = "/" Then
For ii = 3 To 9
If Mid(Val,ii,1) = ":" Then IsSwitch = True
Next
End If
End Function
Function joinParam(quotes)
ReDim ArgArr(objArgs.Count-1)
For i = 0 To objArgs.Count-1
If quotes = "wq" Then
ArgArr(i) = q & objArgs(i) & q
Else
ArgArr(i) = objArgs(i)
End If
Next
joinParam = Join(ArgArr)
End Function
Function wait()
wait=True
If objArgs.Named.Exists("NewProcess") Then
wait=False
Exit Function
ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq")
WScript.Quit 99
End If
End Function
Function Usage()
Wscript.Echo _
vbCrLf&"Usage:" _
&vbCrLf&" popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
&vbCrLf&" To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
&vbCrLf&"" _
&vbCrLf&"Advanced user" _
&vbCrLf&" If any Switch is used then you must use the /m: switch for the message " _
&vbCrLf&" No space allowed between the switch & the value " _
&vbCrLf&" The switches are NOT case sensitive " _
&vbCrLf&"" _
&vbCrLf&" popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
&vbCrLf&"" _
&vbCrLf&" Switch | value |Description" _
&vbCrLf&" -----------------------------------------------------------------------" _
&vbCrLf&" /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
&vbCrLf&" | |" _
&vbCrLf&" /t: /time: | nn |Duration of the popup for n seconds " _
&vbCrLf&" | |<Default> untill key pressed" _
&vbCrLf&" | |" _
&vbCrLf&" /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
&vbCrLf&" | | <Default> Popup" _
&vbCrLf&" | |" _
&vbCrLf&" /s: /sleep: | nn |schedule the popup after n seconds " _
&vbCrLf&" | |" _
&vbCrLf&" /nw /NoWait | |Continue script without the user pressing ok - " _
&vbCrLf&" | | botton option will be defaulted to OK button " _
&vbCrLf&" | |" _
&vbCrLf&" /i: /icon: | ?/q |[question mark]" _
&vbCrLf&" | !/w |[exclamation (warning) mark]" _
&vbCrLf&" | i/info|[information mark]" _
&vbCrLf&" | x/stop|[stop\error mark]" _
&vbCrLf&" | n/none|<Default>" _
&vbCrLf&" | |" _
&vbCrLf&" /b: /button: | o |[OK button] <Default>" _
&vbCrLf&" | oc |[OK and Cancel buttons]" _
&vbCrLf&" | ari |[Abort, Retry, and Ignore buttons]" _
&vbCrLf&" | ync |[Yes, No, and Cancel buttons]" _
&vbCrLf&" | yn |[Yes and No buttons]" _
&vbCrLf&" | rc |[Retry and Cancel buttons]" _
&vbCrLf&" | ctc |[Cancel and Try Again and Continue buttons]" _
&vbCrLf&" ---> | ---> |The output will be saved in variable ""pop.key""" _
&vbCrLf&"" _
&vbCrLf&"Example:" _
&vbCrLf&" popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
&vbCrLf&"" _
&vbCrLf&" v1.9 By RDR @ 2020"
Wscript.Quit
End Function
</script></job>
So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.
simplejson.dumps(data) comes back with
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
Which is a json array, which is what you want, since you gave this a python array.
If you want to get an "object" type syntax you would instead do
>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
which is javascript will come out as an object.
Form correlation matrix, in my case zdf is the dataframe which i need perform correlation matrix.
corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()
# Writing the output to a html file.
with open('test.html', 'w') as f:
print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)
Then we can take screenshot. or convert html to an image file.
if you have options
return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })
I found this solution on the web
SET @row := 0;
SELECT @row := @row + 1 as row, t.*
FROM some_table t, (SELECT @row := 0) r
Single query, fast, and does exactly what I wanted: now I can "number" the "selections" found from a complex query with unique numbers starting at 1 and incrementing once for each row in the result.
I think this will also work for the issue listed above: adjust the initial starting value for @row
and add a limit clause to set the maximum.
BTW: I think that the "r" is not really needed.
ddsp
Tensorflow upgrade -Python3
>> pip3 install --upgrade tensorflow --user
if you got this
"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."
Upgrade grpcio
>> pip3 install --upgrade grpcio --user
I'm running Chrome version 60 and none of the previous CSS answers worked.
I found that Chrome was adding the blue highlight via the outline
style. Adding the following CSS fixed it for me:
:focus {
outline: none !important;
}
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()
.
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
For those who need the same feature in IE 8, this is how I solved the problem:
var myImage = $('<img/>');
myImage.attr('width', 300);
myImage.attr('height', 300);
myImage.attr('class', "groupMediaPhoto");
myImage.attr('src', photoUrl);
I could not force IE8 to use object in constructor.
The at
command exists specifically for this purpose (unlike cron
which is intended for scheduling recurring tasks).
at $(cat file) </path/to/script
In Bash, you can use parameter expansion to modify a string to all lower-/upper-case:
var1=TesT
var2=tEst
echo ${var1,,} ${var2,,}
echo ${var1^^} ${var2^^}
For Android Studion version 3.3.2
1) I updated the gradle distribution URL to distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip in gradle-wrapper.properties file
2) Within the top-level build.gradle file updated the gradle plugin to version 3.3.2
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.2.0'
}
Well, this question was asked and answered way back in 2011, but there is nullptr
in C++11. That's all I'm using currently.
You can read more from Stack Overflow and also from this article.
Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
The advantage of using SendInput is that
Note, it's important to include the "{Raw}" in the SendInput command, in case the clipboard happens to contain "!", "+", "^" or "#".
Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!
In your new code,
int func(int *B){
*B[0] = 5;
}
B
is a pointer to int
, thus B[0]
is an int
, and you can't dereference an int
. Just remove the *
,
int func(int *B){
B[0] = 5;
}
and it works.
In the initialisation
int B[10] = {NULL};
you are initialising anint
with a void*
(NULL
). Since there is a valid conversion from void*
to int
, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.
int B[10] = {0};
is the proper way to 0-initialise an int[10]
.
I am also facing the same problem in Safari Browser
var date = new Date("2011-02-07");
console.log(date) // IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’
Here the solution:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC
As this is one of the top questions about external redirect in WebView, here is a "modern" solution on Kotlin:
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url = request?.url ?: return false
//you can do checks here e.g. url.host equals to target one
startActivity(Intent(Intent.ACTION_VIEW, url))
return true
}
}
You can use private as well and you can call private methods with reflection. If you're using Visual Studio Team Suite it has some nice functionality that will generate a proxy to call your private methods for you. Here's a code project article that demonstrates how you can do the work yourself to unit test private and protected methods:
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
In terms of which access modifier you should use, my general rule of thumb is start with private and escalate as needed. That way you will expose as little of the internal details of your class as are truly needed and it helps keep the implementation details hidden, as they should be.
Swift 3/4
Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell):
let separatorLine = UIView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2))
separatorLine.backgroundColor = .blue
addSubview(separatorLine)
in viewDidLoad method:
tableView.separatorStyle = .none
You can use the fixed
CSS position property to accomplish this. There is a basic tutorial on this here.
EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.
There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?
For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour
!
Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:
Click on the right top corner red button
Select "Disable Issue Type" (for example)
it's easy to export mylib.so
to env:
$ export LD_PRELOAD=/path/mylib.so
$ ./mybin
to disable :
$ export LD_PRELOAD=
Well, the documentation does actually state that
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
as the very first thing, which obviusly means that you need to do a new server request. A redirect, a refresh, a link or some other mean to send the user to the next request.
Why use flashdata if you are using it in the same request, anyway? You'd might as well not use flashdata or use a regular session.
The permgen space is the area of heap that holds all the reflective data of the virtual machine itself, such as class and method objects.
I suggest using Render, as the ElementRef API doc suggests:
... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal.
Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers.
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer) {
renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value');
}
}
It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive.
You can use
git log -p filename
to let git generate the patches for each log entry.
See
git help log
for more options - it can actually do a lot of nice things :) To get just the diff for a specific commit you can
git show HEAD
or any other revision by identifier. Or use
gitk
to browse the changes visually.
I had The same problem like you have. I try this code and it works just fine: When you create your object put this object.is_ob = true
function loadOBJFile(objFile){
/* material of OBJ model */
var OBJMaterial = new THREE.MeshPhongMaterial({color: 0x8888ff});
var loader = new THREE.OBJLoader();
loader.load(objFile, function (object){
object.traverse (function (child){
if (child instanceof THREE.Mesh) {
child.material = OBJMaterial;
}
});
object.position.y = 0.1;
// add this code
object.is_ob = true;
scene.add(object);
});
}
function addEntity(object) {
loadOBJFile(object.name);
}
And then then you delete your object try this code:
function removeEntity(object){
var obj, i;
for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
obj = scene.children[ i ];
if ( obj.is_ob) {
scene.remove(obj);
}
}
}
Try that and tell me if that works, it seems that three js doesn't recognize the object after added to the scene. But with this trick it works.
You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.
Instead, I would recommend using Downloadify:
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.
You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.
The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a
as well as an indexed array arr
.
If we set
a=apple # a simple variable
arr=(apple) # an indexed array with a single element
and then echo
the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.
# | Expression | Result | Comments |
---|---|---|---|
1 | "$a" |
apple |
variables are expanded inside "" |
2 | '$a' |
$a |
variables are not expanded inside '' |
3 | "'$a'" |
'apple' |
'' has no special meaning inside "" |
4 | '"$a"' |
"$a" |
"" is treated literally inside '' |
5 | '\'' |
invalid | can not escape a ' within '' ; use "'" or $'\'' (ANSI-C quoting) |
6 | "red$arocks" |
red |
$arocks does not expand $a ; use ${a}rocks to preserve $a |
7 | "redapple$" |
redapple$ |
$ followed by no variable name evaluates to $ |
8 | '\"' |
\" |
\ has no special meaning inside '' |
9 | "\'" |
\' |
\' is interpreted inside "" but has no significance for ' |
10 | "\"" |
" |
\" is interpreted inside "" |
11 | "*" |
* |
glob does not work inside "" or '' |
12 | "\t\n" |
\t\n |
\t and \n have no special meaning inside "" or '' ; use ANSI-C quoting |
13 | "`echo hi`" |
hi |
`` and $() are evaluated inside "" (backquotes are retained in actual output) |
14 | '`echo hi`' |
echo hi | `` and $() are not evaluated inside '' (backquotes are retained in actual output) |
15 | '${arr[0]}' |
${arr[0]} |
array access not possible inside '' |
16 | "${arr[0]}" |
apple |
array access works inside "" |
17 | $'$a\'' |
$a' |
single quotes can be escaped inside ANSI-C quoting |
18 | "$'\t'" |
$'\t' |
ANSI-C quoting is not interpreted inside "" |
19 | '!cmd' |
!cmd |
history expansion character '!' is ignored inside '' |
20 | "!cmd" |
cmd args |
expands to the most recent command matching "cmd" |
21 | $'!cmd' |
!cmd |
history expansion character '!' is ignored inside ANSI-C quotes |
See also:
getElementById
returns a reference to the element using its id
. The element is the input
in the first case and the paragraph in the second case.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
I think this is just what you'er looking for:
ls | xargs -I {} mv {} Unix_{}
Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)
I answered this question: How to secure an ASP.NET Web API 4 years ago using HMAC.
Now, lots of things changed in security, especially that JWT is getting popular. In this answer, I will try to explain how to use JWT in the simplest and basic way that I can, so we won't get lost from jungle of OWIN, Oauth2, ASP.NET Identity... :)
If you don't know about JWT tokens, you need to take a look at:
https://tools.ietf.org/html/rfc7519
Basically, a JWT token looks like this:
<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1NzI0LCJleHAiOjE0Nzc1NjY5MjQsImlhdCI6MTQ3NzU2NTcyNH0.6MzD1VwA5AcOcajkFyKhLYybr3h13iZjDyHm9zysDFQ
A JWT token has three sections:
If you use the website jwt.io with the token above, you can decode the token and see it like below:
Technically, JWT uses a signature which is signed from headers and claims with security algorithm specified in the headers (example: HMACSHA256). Therefore, JWT must be transferred over HTTPs if you store any sensitive information in its claims.
Now, in order to use JWT authentication, you don't really need an OWIN middleware if you have a legacy Web Api system. The simple concept is how to provide JWT token and how to validate the token when the request comes. That's it.
In the demo I've created (github), to keep the JWT token lightweight, I only store username
and expiration time
. But this way, you have to re-build new local identity (principal) to add more information like roles, if you want to do role authorization, etc. But, if you want to add more information into JWT, it's up to you: it's very flexible.
Instead of using OWIN middleware, you can simply provide a JWT token endpoint by using a controller action:
public class TokenController : ApiController
{
// This is naive endpoint for demo, it should use Basic authentication
// to provide token or POST request
[AllowAnonymous]
public string Get(string username, string password)
{
if (CheckUser(username, password))
{
return JwtManager.GenerateToken(username);
}
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
public bool CheckUser(string username, string password)
{
// should check in the database
return true;
}
}
This is a naive action; in production you should use a POST request or a Basic Authentication endpoint to provide the JWT token.
username
?You can use the NuGet package called System.IdentityModel.Tokens.Jwt
from Microsoft to generate the token, or even another package if you like. In the demo, I use HMACSHA256
with SymmetricKey
:
/// <summary>
/// Use the below code to generate symmetric Secret Key
/// var hmac = new HMACSHA256();
/// var key = Convert.ToBase64String(hmac.Key);
/// </summary>
private const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";
public static string GenerateToken(string username, int expireMinutes = 20)
{
var symmetricKey = Convert.FromBase64String(Secret);
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, username)
}),
Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(symmetricKey),
SecurityAlgorithms.HmacSha256Signature)
};
var stoken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
return token;
}
The endpoint to provide the JWT token is done.
In the demo, I have built
JwtAuthenticationAttribute
which inherits from IAuthenticationFilter
(more detail about authentication filter in here).
With this attribute, you can authenticate any action: you just have to put this attribute on that action.
public class ValueController : ApiController
{
[JwtAuthentication]
public string Get()
{
return "value";
}
}
You can also use OWIN middleware or DelegateHander if you want to validate all incoming requests for your WebAPI (not specific to Controller or action)
Below is the core method from authentication filter:
private static bool ValidateToken(string token, out string username)
{
username = null;
var simplePrinciple = JwtManager.GetPrincipal(token);
var identity = simplePrinciple.Identity as ClaimsIdentity;
if (identity == null)
return false;
if (!identity.IsAuthenticated)
return false;
var usernameClaim = identity.FindFirst(ClaimTypes.Name);
username = usernameClaim?.Value;
if (string.IsNullOrEmpty(username))
return false;
// More validate to check whether username exists in system
return true;
}
protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
string username;
if (ValidateToken(token, out username))
{
// based on username to get more information from database
// in order to build local identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
// Add more claims if needed: Roles, ...
};
var identity = new ClaimsIdentity(claims, "Jwt");
IPrincipal user = new ClaimsPrincipal(identity);
return Task.FromResult(user);
}
return Task.FromResult<IPrincipal>(null);
}
The workflow is to use the JWT library (NuGet package above) to validate the JWT token and then return back ClaimsPrincipal
. You can perform more validation, like check whether user exists on your system, and add other custom validations if you want.
The code to validate JWT token and get principal back:
public static ClaimsPrincipal GetPrincipal(string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
if (jwtToken == null)
return null;
var symmetricKey = Convert.FromBase64String(Secret);
var validationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
};
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
return principal;
}
catch (Exception)
{
//should write log
return null;
}
}
If the JWT token is validated and the principal is returned, you should build a new local identity and put more information into it to check role authorization.
Remember to add config.Filters.Add(new AuthorizeAttribute());
(default authorization) at global scope in order to prevent any anonymous request to your resources.
You can use Postman to test the demo:
Request token (naive as I mentioned above, just for demo):
GET http://localhost:{port}/api/token?username=cuong&password=1
Put JWT token in the header for authorized request, example:
GET http://localhost:{port}/api/value
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1MjU4LCJleHAiOjE0Nzc1NjY0NTgsImlhdCI6MTQ3NzU2NTI1OH0.dSwwufd4-gztkLpttZsZ1255oEzpWCJkayR_4yvNL1s
The demo can be found here: https://github.com/cuongle/WebApi.Jwt
set your property using below code at the time of model creation i think your problem will be solved..and the time are not appear in database.you dont need to add any annotation.
private DateTime? dob;
public DateTime? DOB
{
get
{
if (dob != null)
{
return dob.Value.Date;
}
else
{
return null;
}
}
set { dob = value; }
}
I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.
You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = myListView.GetItemAt(e.X, e.Y)
// Do something here
}
Update (thanks to @chaost for pointing this update out):
Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"
Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/
I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.
Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.
So instead of doing this...
public static class IntExtensions
{
public static bool Even(this int value)
{
return value % 2 == 0;
}
}
We'll be finally able to do it like so...
public extension IntExtension extends int
{
public bool Even => this % 2 == 0;
}
Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/
Yes, here is an example in jsfiddle: http://jsfiddle.net/bfQeJ/
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
The example is a pie chart but you can just fill the series with all the colors to your heart's content =)
Alternatively, you may use FillDown
Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown
To work around this problem, use SQL statements to make the changes to the metadata structure of a table.
This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.
Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"
You should use NMAP:
nmap -T5 -sP 192.168.0.0-255
My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page
I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing }
character. What's the length of result1
versus result2
? I'll note that result2
as you've quoted it has 169 characters.
GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t
, \n
, \r
, and space count as whitespace. In particular, note that trailing NUL (\0
) characters do not count as whitespace and will cause this error.
If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
I faced same error. I reverted the commit version while creating patch. it worked as earlier patch was in reverse way.
[mrdubey@SNF]$ git log 65f1d63 commit 65f1d6396315853f2b7070e0e6d99b116ba2b018 Author: Dubey Mritunjaykumar
commit e377ab50081e3a8515a75a3f757d7c5c98a975c6 Author: Dubey Mritunjaykumar Date: Mon Jan 21 23:05:48 2019 +0530
Earlier commad used: git diff new_commit_id..prev_commit_id > 1 diff
Got error: patch failed: filename:40
working one: git diff prev_commit_id..latest_commit_id > 1.diff
Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.
You can use an ALTER TABLE Statement to modify "START WITH" of the identity.
ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);
I looked at the previous answers and they seem like they're working too hard. Maybe scripting support has simply improved. I think the function is expressed like this:
function lastValue(myRange) {
lastRow = myRange.length;
for (; myRange[lastRow - 1] == "" && lastRow > 0; lastRow--)
{ /*nothing to do*/ }
return myRange[lastRow - 1];
}
In my spreadsheet I then use:
= lastValue(E17:E999)
In the function, I get an array of values with one per referenced cell and this just iterates from the end of the array backwards until it finds a non-empty value or runs out of elements. Sheet references should be interpreted before the data is passed to the function. Not fancy enough to handle multi-dimensions, either. The question did ask for the last cell in a single column, so it seems to fit. It will probably die on if you run out of data, too.
Your mileage may vary, but this works for me.
If you have the proxies set up correctly, and still cannot reach the internet, it could be the DNS resolution. Check /etc/resolve.conf
on the host Ubuntu VM. If it contains nameserver 127.0.1.1
, that is wrong.
Run these commands on the host Ubuntu VM to fix it:
sudo vi /etc/NetworkManager/NetworkManager.conf
# Comment out the line `dns=dnsmasq` with a `#`
# restart the network manager service
sudo systemctl restart network-manager
cat /etc/resolv.conf
Now /etc/resolv.conf
should have a valid value for nameserver, which will be copied by the docker containers.
You might want also to have a look at jmx4perl. It provides java-less access to a remote Java EE Server's MBeans. However, a small agent servlet needs to be installed on the target platform, which provides a restful JMX Access via HTTP with a JSON payload. (Version 0.50 will add an agentless mode by implementing a JSR-160 proxy).
Advantages are quick startup times compared to launching a local java JVM and ease of use. jmx4perl comes with a full set of Perl modules which can be easily used in your own scripts:
use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias; # Import certains aliases for MBeans
print "Memory Used: ",
JMX::Jmx4Perl
->new(url => "http://localhost:8080/j4p")
->get_attribute(MEMORY_HEAP_USED);
You can also use alias for common MBean/Attribute/Operation combos (e.g. for most MXBeans). For additional features (Nagios-Plugin, XPath-like access to complex attribute types, ...), please refer to the documentation of jmx4perl.
have you tried?
<td title="This is Title">
its working fine here on Firefox v 18 (Aurora), Internet Explorer 8 & Google Chrome v 23x
To check if it has a particular method:
hasattr(object,"method")
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
Here's a complete example in the hope that it helps someone:
git revert -m 1 <commit-hash>
git push -u origin master
Where <commit-hash>
is the commit hash of the merge that you would like to revert, and as stated in the explanation of this answer, -m 1
indicates that you'd like to revert to the tree of the first parent prior to the merge.
The git revert ...
line essentially commits your changes while the second line makes your changes public by pushing them to the remote branch.
Above you'll find all differents ways to iterate over a LIST.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class test1 {
public static void main(String[] args) {
//******* Exercise 1 : Write a Java program to create a new array list, add some colors (string) and print out the collection.
List<String> colors = new ArrayList<String>();
colors.add("Black");
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors);
//******* Exercise 2 : Write a Java program to iterate through all elements in a array list.
System.out.println("//******* Exercise 2");
List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
// iteration type 1 : using FOR loop
System.out.println("// iteration type 1");
for(Integer nb : list2) {
System.out.print(nb + ", ");
}
System.out.println("\n");
// iteration type 2 : using FOR loop
System.out.println("// iteration type 2");
for(int i=0; i < list2.size(); i++) {
System.out.print(list2.get(i) + ", ");
}System.out.println("\n");
// iteration type 3 : using Do-While loop
System.out.println("// iteration type 3");
int index21 = 0;
do {
System.out.print(list2.get(index21) + ", ");
index21++;
}while(index21<list2.size());
System.out.println("\n");
// iteration type 4 : using While loop
System.out.println("// iteration type 4");
int index22 = 0;
while(index22<list2.size()) {
System.out.print(list2.get(index22) + ", ");
index22++;
}
System.out.println("\n");
// iteration type 5 : using Iterable forEach loop
System.out.println("// iteration type 5");
list2.forEach(elt -> {
System.out.print(elt + ", ");
});
System.out.println("\n");
// iteration type 6 : using Iterator
System.out.println("// iteration type 6");
Iterator<Integer> listIterator = list2.iterator();
while(listIterator.hasNext()) {
System.out.print( listIterator.next() + ", ");
}
System.out.println("\n");
// iteration type 7 : using Iterator (From the beginning)
System.out.println("// iteration type 7");
ListIterator<Integer> listIterator21 = list2.listIterator(list2.size());
while(listIterator21.hasPrevious()) {
System.out.print( listIterator21.previous() + ", ");
}
System.out.println("\n");
// iteration type 8 : using Iterator (From the End)
System.out.println("// iteration type 8");
ListIterator<Integer> listIterator22 = list2.listIterator();
while(listIterator22.hasNext()) {
System.out.print( listIterator22.next() + ", ");
}
System.out.println("\n");
}
}
If you have the msvcp110.dll missing file error. You have to download the right .dll or just go here http://www.microsoft.com/es-es/download/confirmation.aspx?id=30679 and install the vcredist_x64.exe and vcredist_x86.exe, it worked for me.
Accordingly to this document for SonarQube 7.1
sonar.exclusions - Comma-delimited list of file path patterns to be excluded from analysis sonar.coverage.exclusions - Comma-delimited list of file path patterns to be excluded from coverage calculations
This document gives some examples on how to create path patterns
# Exclude all classes ending by "Bean"
# Matches org/sonar.api/MyBean.java, org/sonar/util/MyOtherBean.java, org/sonar/util/MyDTO.java, etc.
sonar.exclusions=**/*Bean.java,**/*DTO.java
# Exclude all classes in the "src/main/java/org/sonar" directory
# Matches src/main/java/org/sonar/MyClass.java, src/main/java/org/sonar/MyOtherClass.java
# But does not match src/main/java/org/sonar/util/MyClassUtil.java
sonar.exclusions=src/main/java/org/sonar/*
# Exclude all COBOL programs in the "bank" directory and its sub-directories
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl, bank/data/REM012345.cob
sonar.exclusions=bank/**/*
# Exclude all COBOL programs in the "bank" directory and its sub-directories whose extension is .cbl
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl
sonar.exclusions=bank/**/*.cbl
If you are using Maven for your project, Maven command line parameters can be passed like this for example -Dsonar.coverage.exclusions=**/config/*,**/model/*
I was having problem with excluding single class explicitly. Below my observations:
**/*GlobalExceptionhandler.java - not working for some reason, I was expecting such syntax should work
com/some/package/name/GlobalExceptionhandler.java - not working
src/main/java/com/some/package/name/GlobalExceptionhandler.java - good, class excluded explicitly without using wildcards
Apparently anonymous functions cannot be serialized.
Example
$function = function () {
return "ABC";
};
serialize($function); // would throw error
From your code you are using Closure:
$callback = function () // <---------------------- Issue
{
return 'ZendMail_' . microtime(true) . '.tmp';
};
Solution 1 : Replace with a normal function
Example
function emailCallback() {
return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;
Solution 2 : Indirect method call by array variable
If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html
public function __construct($options = null)
63 {
64 if ($options instanceof Zend_Config) {
65 $options = $options->toArray();
66 } elseif (!is_array($options)) {
67 $options = array();
68 }
69
70 // Making sure we have some defaults to work with
71 if (!isset($options['path'])) {
72 $options['path'] = sys_get_temp_dir();
73 }
74 if (!isset($options['callback'])) {
75 $options['callback'] = array($this, 'defaultCallback'); <- here
76 }
77
78 $this->setOptions($options);
79 }
You can use the same approach to send the callback
$callback = array($this,"aMethodInYourClass");
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.
I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.
So to calculate the column sums do:
colsum = sum(M) % or sum(M, 1)
and for the row sums, simply do
rowsum = sum(M, 2)
My bet is that this is faster than both programming a for loop and converting to cells :)
All this can be found in the matlab help for SUM.
In cell D2 and copied down:
=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))
If you're looking for, say two decimal places..
Float f = (float)12.34;
String s = new DecimalFormat ("#.00").format (f);
You can check the syntax by compiling it:
python -m py_compile script.py
$Y_date = split("-","2068-06-15");
$year = $Y_date[0];
You can use explode also
Using regular expressions, you can represent any whitespace character with the metacharacter "\s"
I think this solves
using System.Linq;
(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };
const char * getTextForEnum( int enumVal )
{
return EnumStrings[enumVal];
}
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
The CPU speed varies due to power saving. I originally noticed this because VMware gave me a helpful tip on my laptop, but this page mentions the same thing:
Quote from : VMWare tips and tricks Power saving (SpeedStep, C-states, P-States,...)
Your power saving settings may interfere significantly with vmware's performance. There are several levels of power saving.
CPU frequency
This should not lead to performance degradation, outside of having the obvious lower performance when running the CPU at a lower frequency (either manually of via governors like "ondemand" or "conservative"). The only problem with varying the CPU speed while vmware is running is that the Windows clock will gain of lose time. To prevent this, specify your full CPU speed in kHz in /etc/vmware/config
host.cpukHz = 2167000
Here is the XSLT function which will work similar to the String.Replace() function of C#.
This template has the 3 Parameters as below
text :- your main string
replace :- the string which you want to replace
by :- the string which will reply by new string
Below are the Template
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Below sample shows how to call it
<xsl:variable name="myVariable ">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="'This is a {old} text'" />
<xsl:with-param name="replace" select="'{old}'" />
<xsl:with-param name="by" select="'New'" />
</xsl:call-template>
</xsl:variable>
You can also refer the below URL for the details.
To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
If you wanted to center it vertically, the canvas element needs to be absolutely positioned:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
If you wanted to center it horizontally and vertically, do:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
For more info visit: https://www.w3.org/Style/Examples/007/center.en.html
The absolutely best way: Just let your activity implement View.OnClickListener
, and write your onClick
method like this:
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.button1:
// your code for button1 here
break;
case R.id.button2:
// your code for button2 here
break;
// even more buttons here
}
}
Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick
:
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.
I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)
If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:
otherClassInstance.textBox1.Text = "hello world";
Splitting URL by .com/ or .net/
url.split(/\.com\/|\.net\//)
Every so often I use this script to figure out which procs to modify, or to figure out what uses a column of a table, or that table at all to remove some old junk. It checks each database on the instance it is ran on by the wonderfully supplied sp_msforeachdb.
if object_id('tempdb..##nothing') is not null
drop table ##nothing
CREATE TABLE ##nothing
(
DatabaseName varchar(30),
SchemaName varchar(30),
ObjectName varchar(100),
ObjectType varchar(50)
)
EXEC master.sys.sp_msforeachdb
'USE ?
insert into ##nothing
SELECT
db_name() AS [Database],
[Scehma]=schema_name(o.schema_id),
o.Name,
o.type
FROM sys.sql_modules m
INNER JOIN sys.objects o
ON o.object_id = m.object_id
WHERE
m.definition like ''%SOME_TEXT%'''
--edit this text
SELECT * FROM ##nothing n
order by OBJECTname
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
Well, you can hide it, by removing the entire system menu:
private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= ~WS_SYSMENU;
return cp;
}
}
Of course, doing so removes the minimize and maximize buttons.
If you keep the system menu but remove the close item then the close button remains but is disabled.
The final alternative is to paint the non-client area yourself. That's pretty hard to get right.
Simply setting the Network Setting to bridged did the trick for me.
Your IP will change when you do this. However, in my case it didn't change immediately. ifconfig
returned the same ip. I rebooted the vm and boom, the ip set itself to one start with 192.* and I was immediately allowed ssh access.
any?
isn't the same as not empty?
in some cases.
>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false
From the documentation:
If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).
If your Internal Server Error information doesn't show up in log files, you probably need to restart the Apache service.
I've found that Apache 2.4 (at least on Windows platform) tends to stubbornly refuse to flush log files—instead, logged data remains in memory for quite a while. It's a good idea from the performance point of view but it can be confusing when developing.
The case is like :
mysql connects will localhost when network is not up.
mysql cannot connect when network is up.
You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):
This should ideally resolve the issue you are facing.
Generally speaking, it is set in the "Project Structure" dialog.
Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".
Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.
Top level await
is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.
There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:
// data.js
const data = await fetch( '/data.json' );
export default data;
Now any file that imports data.js
won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.
My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await
probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.
def extended_string (word, length) :
extra_long_word = word * (length//len(word) + 1)
required_string = extra_long_word[:length]
return required_string
print(extended_string("abc", 7))
Usually this region should contains the constructors of the class
You can use psutil
package:
Install
pip install psutil
Usage:
import psutil
process_name = "chrome"
pid = None
for proc in psutil.process_iter():
if process_name in proc.name():
pid = proc.pid
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
import React, { useState } from 'react';
function App() {
const [apes , setap] = useState('yo');
const handleClick = () =>{
setap(document.getElementById('name').value)
};
return (
<div>
<input id='name' />
<h2> {apes} </h2>
<button onClick={handleClick} />
</div>
);
}
export default App;
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,
Here is the solution that worked for me, (Documentation) (Flag Reference)
Hide Status Bar
// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
View decorView = getWindow().getDecorView();
// Hide Status Bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
Show Status Bar
if (Build.VERSION.SDK_INT < 16) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
View decorView = getWindow().getDecorView();
// Show Status Bar.
int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
decorView.setSystemUiVisibility(uiOptions);
}
From http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx:
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern)
.Replace(@"\*", ".*")
.Replace(@"\?", ".")
+ "$";
}
So something like foo*.xls?
will get transformed to ^foo.*\.xls.$
.
You don't want to have the collision check code inside the painting code. The painting needs to be fast. Collision can go in the game loop. Therefore you need an internal representation of the objects independent of their sprites.
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
To get to a specific committed code, you need the hash code of that commit. You can get that hash code in two ways:
git log
and check your recent commits on that branch. It will show you the hash code of your commit and the message you leaved while you were committing your code. Just copy and then do git checkout commit_hash_code
After moving to that code, if you want to work on it and make changes, you should make another branch with git checkout -b <new-branch-name>
, otherwise, the changes will not be retained.
There are performance consequences to deep-diving an object in your $watch. Sometimes (for example, when changes are only pushes and pops), you might want to $watch an easily calculated value, such as array.length.
Guava has a method Ints.asList()
for creating a List<Integer>
backed by an int[]
array. You can use this with Collections.sort to apply the Comparator to the underlying array.
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Note that the latter is a live list backed by the actual array, so it should be pretty efficient.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
Instead of typedef struct { ... } pos;
you should be doing struct pos { ... };
. The issue here is that you are using the pos
type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name;
pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline
, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline
, the compiler effectively ignores it because the method is already declared inline.
(inline
methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.
So the most convenient way to iterate a map is:
<#list tags>
<ul class="posts">
<#items as tagName, tagCount>
<li>{$tagName} (${tagCount})</li>
</#items>
</ul>
<#else>
<p>No tags found.</p>
</#list>
No more <#if ...>
wrappers.
Just for more fun:
int myInt = Math.Min(hisInt, -hisInt);
int myInt = -(int)Math.Sqrt(Math.Pow(Math.Sin(1), 2) + Math.Pow(Math.Cos(-1), 2))
* Math.Abs(hisInt);
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
You can use setTimeout()
:
var addBg = function(e) {_x000D_
e = e || window.event;_x000D_
e.preventDefault();_x000D_
var el = e.target || e.srcElement;_x000D_
el.className = 'bg';_x000D_
setTimeout(function() {_x000D_
removeBg(el);_x000D_
}, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
el.className = '';_x000D_
};
_x000D_
div {_x000D_
border: 1px solid grey;_x000D_
padding: 5px 7px;_x000D_
display: inline-block;_x000D_
margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
background: orange;_x000D_
}
_x000D_
<body onclick='addBg(event);'>This is body_x000D_
<br/>_x000D_
<div onclick='addBg(event);'>This is div_x000D_
</div>_x000D_
</body>
_x000D_
Using jQuery:
var addBg = function(e) {_x000D_
e.stopPropagation();_x000D_
var el = $(this);_x000D_
el.addClass('bg');_x000D_
setTimeout(function() {_x000D_
removeBg(el);_x000D_
}, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
$(el).removeClass('bg');_x000D_
};_x000D_
_x000D_
$(function() {_x000D_
$('body, div').on('click', addBg);_x000D_
});
_x000D_
div {_x000D_
border: 1px solid grey;_x000D_
padding: 5px 7px;_x000D_
display: inline-block;_x000D_
margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
background: orange;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<body>This is body_x000D_
<br/>_x000D_
<div>This is div</div>_x000D_
</body>
_x000D_
A fast way to convert strings to an integer is to use a bitwise or, like so:
x | 0
While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x
) since it will first cast x
to a number and then perform a very efficient or.
If you really want to do this, create an HttpServletRequestWrapper.
public class AddableHttpRequest extends HttpServletRequestWrapper {
private HashMap params = new HashMap();
public AddableingHttpRequest(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
// if we added one, return that one
if ( params.get( name ) != null ) {
return params.get( name );
}
// otherwise return what's in the original request
HttpServletRequest req = (HttpServletRequest) super.getRequest();
return validate( name, req.getParameter( name ) );
}
public void addParameter( String name, String value ) {
params.put( name, value );
}
}
It happens also if your code is expecting Java Mail 1.4 and your jars are Java Mail 1.3. Happened to me when upgraded Pentaho Kettle
Regards
The reason reset
and revert
tend to come up a lot in the same conversations is because different version control systems use them to mean different things.
In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert
before being told that they actually want reset
.
Similarly, the revert
equivalent in other VCSes is often called rollback
or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset
but not revert
. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.
As for your actual questions about revert...
Okay, you're going to use git revert but how?
git revert first-bad-commit..last-bad-commit
And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??
By default, git revert
prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:
--edit
With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.
--no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.
This is useful when reverting more than one commits' effect to your index in a row.
In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit
to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.
Using -webkit-appearance:none;
will remove also the arrows indicating that this is a dropdown.
See this snippet that makes it work across different browsers an adds custom arrows without including any image files:
select{_x000D_
background: url(data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6IzQ0NDt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPmFycm93czwvdGl0bGU+PHJlY3QgY2xhc3M9ImNscy0xIiB3aWR0aD0iNC45NSIgaGVpZ2h0PSIxMCIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxLjQxIDQuNjcgMi40OCAzLjE4IDMuNTQgNC42NyAxLjQxIDQuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIi8+PC9zdmc+) no-repeat 95% 50%;_x000D_
-moz-appearance: none; _x000D_
-webkit-appearance: none; _x000D_
appearance: none;_x000D_
/* and then whatever styles you want*/_x000D_
height: 30px; _x000D_
width: 100px;_x000D_
padding: 5px;_x000D_
}
_x000D_
<select>_x000D_
<option value="volvo">Volvo</option>_x000D_
<option value="saab">Saab</option>_x000D_
<option value="mercedes">Mercedes</option>_x000D_
<option value="audi">Audi</option>_x000D_
</select>
_x000D_
According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)
Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.
You can use Visual Studio for C, but if you are serious about learning the newest C available, I recommend using something like Code::Blocks with MinGW-TDM version, which you can get a 32 bit version of. I use version 5.1 which supports the newest C and C++. Another benefit is that it is a better platform for creating software that can be easily ported to other platforms. If you were, for example, to code in C, using the SDL library, you could create software that could be recompiled with little to no changes to the code, on Linux, Apple and many mobile devices. The way Microsoft has been going these days, I think this is definitely the better route to take.
As well as making sure that you have first called $("#myForm").validate();
, make sure that your dynamic control has been added to the DOM before adding the validation rules.
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
I also got the same issue of IE9 rendering in IE7 Document standards for local host. I tried many conditional comments tags but unsuccesful. In the end I just removed all conditional tags and just added meta tag immediatly after head like below and it worked like charm.
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
Hope it helps
The difference is in the second argument. The second argument to substring
is the index to stop at (but not include), but the second argument to substr
is the maximum length to return.
Links?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
Since people will be coming from Google, make sure you're in the right database.
Running SQL in the 'master' database will often return this error.
You don't want a "temporary default Python"
You want the 2.7 scripts to start with
/usr/bin/env python2.7
And you want the 3.2 scripts to begin with
/usr/bin/env python3.2
There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.
Remember.
Explicit is better than Implicit.
Using new api fetch:
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
_x000D_
function msToHMS( ms ) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
//alert( hours+":"+minutes+":"+seconds);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var hms = hours+":"+minutes+":"+seconds;
return hms;
}
Apparently, _JAVA_OPTIONS
works on Linux, too:
$ export _JAVA_OPTIONS="-Xmx1g"
$ java -jar jconsole.jar &
Picked up _JAVA_OPTIONS: -Xmx1g
Here's another way.
Here's the one you want. This is lazy [\s\S]*?
The first item:
[\s\S]*?(?:location="[^"]*")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/ZcqcUm/2
For completeness, this gets the last one. This is greedy [\s\S]*
The last item:[\s\S]*(?:location="([^"]*)")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/LXSPDp/3
There's only 1 difference between these two regular expressions and that is the ?
If you want dot/comma separated numbers also, then:
\d*\.?\d*
or
[0-9]*\.?[0-9]*
You can use https://regex101.com/ to test your regexes.
aString = "hello world"
aString.startswith("hello")
More info about startswith
.
Possibly the easiest way is to simply do three separate jobs:
55 23 30 4,6,9,11 * myjob.sh
55 23 31 1,3,5,7,8,10,12 * myjob.sh
55 23 28 2 * myjob.sh
That will run on the 28th of February though, even on leap years so, if that's a problem, you'll need to find another way.
However, it's usually both substantially easier and correct to run the job as soon as possible on the first day of each month, with something like:
0 0 1 * * myjob.sh
and modify the script to process the previous month's data.
This removes any hassles you may encounter with figuring out which day is the last of the month, and also ensures that all data for that month is available, assuming you're processing data. Running at five minutes to midnight on the last day of the month may see you missing anything that happens between then and midnight.
This is the usual way to do it anyway, for most end-of-month jobs.
If you still really want to run it on the last day of the month, one option is to simply detect if tomorrow is the first (either as part of your script, or in the crontab itself).
So, something like:
55 23 28-31 * * [[ "$(date --date=tomorrow +\%d)" == "01" ]] && myjob.sh
should be a good start, assuming you have a relatively intelligent date
program.
If your date
program isn't quite advanced enough to give you relative dates, you can just put together a very simple program to give you tomorrow's day of the month (you don't need the full power of date
), such as:
#include <stdio.h>
#include <time.h>
int main (void) {
// Get today, somewhere around midday (no DST issues).
time_t noonish = time (0);
struct tm *localtm = localtime (&noonish);
localtm->tm_hour = 12;
// Add one day (86,400 seconds).
noonish = mktime (localtm) + 86400;
localtm = localtime (&noonish);
// Output just day of month.
printf ("%d\n", localtm->tm_mday);
return 0;
}
and then use (assuming you've called it tomdom
for "tomorrow's day of month"):
55 23 28-31 * * [[ "$(tomdom)" == "1" ]] && myjob.sh
Though you may want to consider adding error checking since both time()
and mktime()
can return -1
if something goes wrong. The code above, for reasons of simplicity, does not take that into account.
I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.
The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:
function setCookie(name, value, daysToLive = 3650) { // 10 years default
let cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number") {
cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
document.cookie = cookie + ";path=/";
}
}
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1].trim());
}
}
return undefined;
}
function deleteCookie(name) {
setCookie(name, '', -1);
}
The appearance of the scroll bars can be controlled with WebKit's -webkit-scrollbar
pseudo-elements [blog]. You can disable the default appearance and behaviour by setting -webkit-appearance
[docs] to none
.
Because you're removing the default style, you'll also need to specify the style yourself or the scroll bar will never show up. The following CSS recreates the appearance of the hiding scroll bars:
.frame::-webkit-scrollbar {
-webkit-appearance: none;
}
.frame::-webkit-scrollbar:vertical {
width: 11px;
}
.frame::-webkit-scrollbar:horizontal {
height: 11px;
}
.frame::-webkit-scrollbar-thumb {
border-radius: 8px;
border: 2px solid white; /* should match background, can't be transparent */
background-color: rgba(0, 0, 0, .5);
}
.frame::-webkit-scrollbar-track {
background-color: #fff;
border-radius: 8px;
}
WebKit (Chrome) Screenshot
Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.
This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html
(It also includes the drag/drop interface but that's easily ignored.)
Basically what it comes down to is this:
<input id="files" type="file" />
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
(xhr.upload || xhr).addEventListener('progress', function(e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
console.log('xhr progress: ' + Math.round(done/total*100) + '%');
});
xhr.addEventListener('load', function(e) {
console.log('xhr upload complete', e, this.responseText);
});
xhr.open('post', '/URL-HERE', true);
xhr.send(file);
});
</script>
(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)
So basically what it comes down to is this =)
xhr.send(file);
Where file
is typeof Blob
: http://www.w3.org/TR/FileAPI/
Another (better IMO) way is to use FormData
. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.
var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);
FormData
makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).
All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.
This is how I handled the request (1 image per request) in PHP:
if ( isset($_FILES['file']) ) {
$filename = basename($_FILES['file']['name']);
$error = true;
// Only upload if on my home win dev machine
if ( isset($_SERVER['WINDIR']) ) {
$path = 'uploads/'.$filename;
$error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
}
$rsp = array(
'error' => $error, // Used in JS
'filename' => $filename,
'filepath' => '/tests/uploads/' . $filename, // Web accessible
);
echo json_encode($rsp);
exit;
}
An other approach is to use splice.
The
splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
N.B : In case you're working with reactive frameworks, it will update the "view", your array "knowing" you've updated it.
Answer :
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
let foundIndex = items.findIndex(element => element.id === item.id)
items.splice(foundIndex, 1, item)
And in case you want to only change a value of an item, you can use find function :
// Retrieve item and assign ref to updatedItem
let updatedItem = items.find((element) => { return element.id === item.id })
// Modify object property
updatedItem.aProp = ds.aProp
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.
Add new column to DataTable
and use column Expression
property to set your Status expression.
Here you can find good example: DataColumn.Expression
Property
DataTable and DataColumn Expressions in ADO.NET - Calculated Columns
UPDATE
Code sample:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
UPDATE #2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Try this:
grep -i -A 10 "my_regex"
-A 10 means, print ten lines after match to "my_regex"
Add ?var1=data1&var2=data2
to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
If your program is "publicly available non-commercial in nature" and has "a publicly available Web site that meets the basic quality standards", then you can try and get a free license of Excelsior. If its not then it's expensive, but still a viable option.
Program: https://www.excelsiorjet.com
As a side note: Here's a study of all existing Jar to EXE programs, which is a bit depressing - https://www.excelsior-usa.com/articles/java-to-exe.html
In my case, it was the problem when I setup my time manually two month earlier on my iPhone. But when I changed to set time automatically, it worked fine.
Setting
-> General
-> Date & Time
-> set time automatically
If it does not work then set time automatically of both mac & iPhone, it may work fine.
I did it this way. it's easy :)
Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();
Calendar day1 = Calendar.getInstance();
day1.setTime(d1);
Calendar day2 = Calendar.getInstance();
day2.setTime(d2);
int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);
int difference = to-from;
I don't know if this is the best way, but it has worked for me.
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");
I was just going through this myself. I had ensured that my MSSQLSERVER login user had full access
but it was still causing issues. It only worked once I moved the destination to the root of C. More importantly out of a user folder (even though I had a share with full permissions - even tried "Everyone" as a test).
I don't know if i consider my issue "fixed", however it is "working".
Just a FYI for any other users that come across this thread.
It's possible but not all that easy, to create a hybrid native/managed assembly in C#. Were you using C++ instead it'd be a lot easier, as the Visual C++ compiler can create hybrid assemblies as easily as anything else.
Unless you have a strict requirement to produce a hybrid assembly, I'd agree with MusiGenesis that this isn't really worth the trouble to do with C#. If you need to do it, perhaps look at moving to C++/CLI instead.
Just for future reference, here's a solution that worked for me (thanks to a comment that @George Hawkins posted in one of the answers):
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream out = new ByteArrayOutputStream();
output.setByteStream(out);
writer.write(document, output);
String xmlStr = new String(out.toByteArray());
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
You can make this happen with less typing. First, change the way your push works:
git config --global push.default current
This will infer the origin my_branch
part, thus you can do:
git push -u
Which will both create the remote branch with the same name and track it.
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
Heres my solution that I wrote for a project I'm working on in javascript. If you don't mind the memory cost of a few arrays it's probably the fastest and simplest solution you'll find. It assumes you know the position of the last move.
/*
* Determines if the last move resulted in a win for either player
* board: is an array representing the board
* lastMove: is the boardIndex of the last (most recent) move
* these are the boardIndexes:
*
* 0 | 1 | 2
* ---+---+---
* 3 | 4 | 5
* ---+---+---
* 6 | 7 | 8
*
* returns true if there was a win
*/
var winLines = [
[[1, 2], [4, 8], [3, 6]],
[[0, 2], [4, 7]],
[[0, 1], [4, 6], [5, 8]],
[[4, 5], [0, 6]],
[[3, 5], [0, 8], [2, 6], [1, 7]],
[[3, 4], [2, 8]],
[[7, 8], [2, 4], [0, 3]],
[[6, 8], [1, 4]],
[[6, 7], [0, 4], [2, 5]]
];
function isWinningMove(board, lastMove) {
var player = board[lastMove];
for (var i = 0; i < winLines[lastMove].length; i++) {
var line = winLines[lastMove][i];
if(player === board[line[0]] && player === board[line[1]]) {
return true;
}
}
return false;
}
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
Think this is, what you are searching for: Allow access to specific projects for Users
Short description without screenshots:
Use Jenkins "Project-based Matrix Authorization Strategy" under "Manage Jenkins" => "Configure System". On the configuration page of each project, you now have "Enable project-based security". Now add each user you want to authorize.
You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
I came across this question looking for a way to open an Explorer window from PowerShell and also select a file. I'm adding this answer in case others come across it for the same reason.
To launch Explorer and select a file, use Invoke-Expression
:
Invoke-Expression "explorer '/select,$filePath'"
There are probably other ways to do this, but this worked for me.
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
Expanding upon the above code from @dreamlax
char *readFile(char *fileName) {
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL) return NULL; //could not open file
fseek(file, 0, SEEK_END);
long f_size = ftell(file);
fseek(file, 0, SEEK_SET);
code = malloc(f_size);
while ((c = fgetc(file)) != EOF) {
code[n++] = (char)c;
}
code[n] = '\0';
return code;
}
This gives you the length of the file, then proceeds to read it character by character.
On Mac OS press: CMD
+OPTION
+J
for console
The following generic fix would for any module. For example with request-promise
.
Replace
npm install request-promise --global
With
npm install request-promise --cli
worked (source) and also for globals
and inherits
Also, try setting the environment variable
NODE_PATH=%AppData%\npm\node_modules
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
"all" and "any" are nice for the many conditions of same type case. BUT they always evaluates all conditions. As shown in this example:
def c1():
print " Executed c1"
return False
def c2():
print " Executed c2"
return False
print "simple and (aborts early!)"
if c1() and c2():
pass
print
print "all (executes all :( )"
if all((c1(),c2())):
pass
print
In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:
<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>
Where MyActivity
is the one you want to stay in landscape.
The android:configChanges=...
line prevents onResume()
, onPause()
from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.
Note: keyboardHidden
and orientation
are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation
.
Here is a simple solution in C. Assume interrupts are turned off for each function. No polymorphism & stuff, just common sense.
#define BUFSIZE 128
char buf[BUFSIZE];
char *pIn, *pOut, *pEnd;
char full;
// init
void buf_init()
{
pIn = pOut = buf; // init to any slot in buffer
pEnd = &buf[BUFSIZE]; // past last valid slot in buffer
full = 0; // buffer is empty
}
// add char 'c' to buffer
int buf_put(char c)
{
if (pIn == pOut && full)
return 0; // buffer overrun
*pIn++ = c; // insert c into buffer
if (pIn >= pEnd) // end of circular buffer?
pIn = buf; // wrap around
if (pIn == pOut) // did we run into the output ptr?
full = 1; // can't add any more data into buffer
return 1; // all OK
}
// get a char from circular buffer
int buf_get(char *pc)
{
if (pIn == pOut && !full)
return 0; // buffer empty FAIL
*pc = *pOut++; // pick up next char to be returned
if (pOut >= pEnd) // end of circular buffer?
pOut = buf; // wrap around
full = 0; // there is at least 1 slot
return 1; // *pc has the data to be returned
}
$ee = array('a' => 50, 'b' => 25, 'c' => 5, 'd' => 80, 'e' => 40, 'f' => 152, 'g' => 45, 'h' => 28);
$Acurr = '';
$Amax = 0;
foreach($ee as $key => $value) {
$Acurr = $value;
if($Acurr >= $Amax) {
$Amax = $Acurr;
}
}
echo "greatest number is $Amax";
First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
Your Event.hbm.xml says:
<set name="attendees" cascade="all">
<key column="attendeeId" />
<one-to-many class="Attendee" />
</set>
In plain english, this means that the column Attendee.attendeeId
is the foreign key for the association attendees
and points to the primary key of Event
.
When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.
Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.
Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event
-end as inverse
.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
BEWARE : Order of update columns is critical
GOOD: What I want saves existing Value of Status to PrevStatus
UPDATE Collections SET PrevStatus=Status, Status=44 WHERE ID=1487496;
BAD: Status & PrevStatus both end up as 44
UPDATE Collections SET Status=44, PrevStatus=Status WHERE ID=1487496;
No, there's no legal and reliable way to do this.
If you find a way, it will be disabled in the future, as it has happened with every method before.
I've gotten this error because the user trying to login was lacking permissions.
I don't recommend doing this, but I fixed it by granting the user db_owner
globally. It was a local instance, so not a huge security concern.
As Richard Corden pointed, use C++ functions min and max defined in std namespace. They provide type safety, and help to avoid comparing mixed types (i.e. float point vs integer) what sometimes may be undesirable.
If you find that C++ library you use defines min/max as macros as well, it may cause conflicts, then you can prevent unwanted macro substitution calling the min/max functions this way (notice extra brackets):
(std::min)(x, y)
(std::max)(x, y)
Remember, this will effectively disable Argument Dependant Lookup (ADL, also called Koenig lookup), in case you want to rely on ADL.
I have found the simplest (cheap and cheerful) solution is simply add an empty span with ng-show = "someFunctionThatAlwaysReturnsZeroOrNothing()" to the end of the last element rendered. This function will be run when to check if the span element should be displayed. Execute any other code in this function.
I realize this is not the most elegant way to do things, however, it works for me...
I had a similar situation, though slightly reversed where I needed to remove a loading indicator when an animation began, on mobile devices angular was initializing much faster than the animation to be displayed, and using an ng-cloak was insufficient as the loading indicator was removed well before any real data was displayed. In this case I just added the my return 0 function to the first rendered element, and in that function flipped the var that hides the loading indicator. (of course I added an ng-hide to the loading indicator triggered by this function.
You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.
If p is the object retrieved:
existing = p['d']['a']
For pymongo versions < 3.0
db.ProductData.update({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0
db.ProductData.update_one({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False)
However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:
For pymongo versions < 3.0:
db.ProductData.update({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0:
db.ProductData.update_one({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False)
This ensures your increments will always happen.
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE
would ever confuse anyone who knew what they were doing.
Explanation of Serialize and Deserialize using Python
In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.
Serialization using pickle
import pickle
#the object to serialize
example_dic={1:"6",2:"2",3:"f"}
#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()
The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):
€}q (KX 6qKX 2qKX fqu.
Deserialization using pickle
import pickle
pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)
print(get_deserialized_data_back)
Output:
{1: '6', 2: '2', 3: 'f'}
You manage the list of available compilers in the Window -> Preferences -> Java -> Installed JRE's tab
.
In the project build path configuration dialog, under the libraries tab, you can delete the entry for JRE System Library
, click on Add Library
and choose the installed JRE to compile with. Some compilers can be configured to compile at a back-level compiler version. I think that's why you're seeing the addition version options.
You can use the sorted method with a key.
sorted(a, key=lambda x : x[1])
Here is all the information you need in order to format clickable hyperlinks in LaTeX:
http://en.wikibooks.org/wiki/LaTeX/Hyperlinks
Essentially, you use the hyperref
package and use the \url
or \href
tag depending on what you're trying to achieve.
Use this method and pass your array in parameter
Collections.shuffle(arrayList);
This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.
You can now use arraylist which is shuffled.
Please use datatable if you want to get result from json object. Datatable also works in the same manner of converting the json result into table format with the facility of searchable and sortable columns automatically.
It is totally possible, i did something similar based on the example of Mike Sav. That's the html page and ther shoul be an external test.js file in the same folder
example.html:
<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./test.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
document.getElementById('mylink').click();
}
</script>
</html>
test.js:
alert('hello world')
Two things I noticed (they may be mistakes from when you wrote it down though).
$('.navlink').click
)return $(this).data("selected")==true
)Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
I had the same problem with Versions displaying the same message. I simply right clicked the offending files and selected 'Revert...' from the right-click menu and all was good.
Basically Versions (actually Subversion) thinks you still want to add the file, but it cannot find it because you deleted it in the file system. The Revert option tells Subversion to forget about adding it.
assign
copy:
retain:
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
Solution 1:
Go to your android folder > Gradle.properties > add your jdk path.
Clean and rebuild then it is done. // For Example Purpose Only
org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home
Solution 2 At last, here I found the solution.
Add jdk path
to gradle.properties file and did a rebuild.
This will also solve your error.
Here is all Solution could not find tools.jar
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
If you care less about performance, I'm a big fan of Apache Digester, since it essentially lets you map directly from XML to Java Beans.
Otherwise, you have to first parse, and then construct your objects.
In the function context "this" its not referring to the select element, but to the page itself
var ID = $(this).attr("id");
to var ID = $(obj).attr("id");
If obj is already a jQuery Object, just remove the $() around it.
This is not a shorthand for $(document).ready()
.
The code you posted boxes the inside code and makes jQuery available as $
without polluting the global namespace. This can be used when you want to use both prototype and jQuery on one page.
Documented here: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/#use-an-immediately-invoked-function-expression
This works:
<script src="/clock.js" type="text/javascript"></script>
The leading slash means the root directory of your site. Strictly speaking, language="Javascript"
has been deprecated by type="text/javascript"
.
Capitalization of tags and attributes is also widely discouraged.
The difference between (R,)
and (1,R)
is literally the number of indices that you need to use. ones((1,R))
is a 2-D array that happens to have only one row. ones(R)
is a vector. Generally if it doesn't make sense for the variable to have more than one row/column, you should be using a vector, not a matrix with a singleton dimension.
For your specific case, there are a couple of options:
1) Just make the second argument a vector. The following works fine:
np.dot(M[:,0], np.ones(R))
2) If you want matlab like matrix operations, use the class matrix
instead of ndarray
. All matricies are forced into being 2-D arrays, and operator *
does matrix multiplication instead of element-wise (so you don't need dot). In my experience, this is more trouble that it is worth, but it may be nice if you are used to matlab.
I just want to put my view
So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.
public interface GenericReturnType{
public static RETURN_TYPE enum{
MACHINE, PERSON;
}
public RETURN_TYPE getReturnType();
}
public class PersonReturnType implements GenericReturnType{
// CONSTRUCTORS //
// GETTRE AND SETTER //
public RETURN_TYPE getReturnType(){
return PERSON;
}
public String getAddress(){
return something;
}
}
public class MachineReturnType implements GenericReturnType{
// CONSTRUCTORS //
// GETTRE AND SETTER //
public RETURN_TYPE getReturnType(){
return MACHINE;
}
public String getManufatureName(){
return something;
}
}
public class TestService{
public GenericReturnType getObject(// some input //){
GenericReturnType obj ;
if(// some code //){
obj = new PersonReturnType();
// some code //
}
if(// some code //){
obj = new MachineReturnType();
// some code //
}
return obj;
}
}
public class TestDriver{
TestService service = new TestService();
GenericReturnType genObj = TestService.getObject(// some input //);
if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
// SOME CODE //
}
if(genObj.getReturnType() == RETURN_TYPE.PERSON){
// SOME CODE //
}
}