you need to use add class open
in <div class="btn-group open">
and in li
add class="active"
Updated
For MS SQL Server 2012 and above
USE [master];
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'
FROM sys.dm_exec_sessions
WHERE database_id = db_id('MyDB')
EXEC(@kill);
For MS SQL Server 2000, 2005, 2008
USE master;
DECLARE @kill varchar(8000); SET @kill = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('MyDB')
EXEC(@kill);
Something like
script > /dev/null 2>&1
This will prevent standard output and error output, redirecting them both to /dev/null
.
As the documentation clearly states, Character.getNumericValue()
returns the character's value as a digit.
It returns -1
if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character
object, you'll need to unbox it first:
int value = (int)c.charValue();
This is meant half as a joke, since the question is kinda silly.
public static bool IsNull (this System.Object o)
{
return (o == null);
}
This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.
Then you can save tons of code by doing:
if (foo.IsNull())
instead of the super lame:
if (foo == null)
@Column(columnDefinition="tinyint(1) default 1")
I just tested the issue. It works just fine. Thanks for the hint.
About the comments:
@Column(name="price")
private double price = 0.0;
This one doesn't set the default column value in the database (of course).
if(!rsData.IsDBNull(rsData.GetOrdinal("usr.ursrdaystime")))
{
strLevel = rsData.GetString("usr.ursrdaystime");
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx
2 more helpful methods: System.Environment.GetEnvironmentVariable("ComputerName" )
System.Environment.GetEnvironmentVariable("ClientName" ) to get the name of the user's PC if they're connected via Citrix XenApp or Terminal Services (aka RDS, RDP, Remote Desktop)
F9 executes only one statement. By default Toad will try to execute the statement wherever your cursor is or treat all the highlighted text as a statement and try to execute that. A ;
is not necessary in this case.
F5 is "Execute as Script" which means that Toad will take either the complete highlighted text (or everything in your editor if nothing is highlighted) containing more than one statement and execute it like it was a script in SQL*Plus. So, in this case every statement must be followed by a ;
and sometimes (in PL/SQL cases) ended with a /
.
Can try like this:
ContentValues values=new ContentValues();
values.put("name","aaa");
values.put("publisher","ppp");
values.put("price","111");
int id=sqdb.update("table_name",values,"bookid='5' and booktype='comic'",null);
Not sure why @user3133050 is voted down, that's all you need to do...
Here's the structure you need, based on your script tag's src, assuming you are trying to load moment.js
into index.html
:
/js/moment.js
/some-other-directory/index.html
The ../
looks "up" at the "some-other-directory" folder level, finds the js
folder next to it, and loads the moment.js
inside.
It sounds like your index.html
is at root level, or nested even deeper.
If you're still struggling, create a test.js
file in the same location as index.html
, and add a <script src="test.js"></script>
and see if that loads. If that fails, check your syntax. Tested in Chrome 46.
Get all querystring parameters including checkbox values (arrays).
Considering the correct & normal use of GET parameters, the things I see it's missing, on most functions, is the support for arrays and removing the hash data.
So I wrote this function:
function qs(a){
if(!a)return {};
a=a.split('#')[0].split('&');
var b=a.length,c={},d,k,v;
while(b--){
d=a[b].split('=');
k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
}
return c
}
Using shorthand operators & while-- loop, the performance should be very good to.
Support:
Notes:
It does not support object arrays (key[key]=value)
If the space is + it remains a +.
Add .replace(/\+/g, " ")
if you need.
Usage:
qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')
Return:
{
"empty": "",
"key": "value",
"array": [
"1",
"2"
]
}
Demo:
Info
If you don't understand something or you can't read the function just ask. I'm happy to explain what I did here.
If you think the function is unreadable and unmaintainable I'm happy to rewrite the function for you, but consider that shorthand & bitwise operators are always faster than a standard syntax (maybe read about shorthands and bitwise operators in the ECMA-262 book or use your favorite search engine). Rewriting the code in a standard readable syntax means performance loss.
I've found this to work:
var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
It is surprising the question of validating an email address continually comes up on SO!
You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.
Excerpt:
The virtue of my regular expression above is that it matches 99% of the email addresses in use today. All the email address it matches can be handled by 99% of all email software out there. If you're looking for a quick solution, you only need to read the next paragraph. If you want to know all the trade-offs and get plenty of alternatives to choose from, read on.
See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:
To all the complainers: after 3 hours experimenting all the solutions offered in this gigantic discussion, this is THE ONLY good java regex solution I can find. None of the rfc5322 stuff works on java regex.
Application.Exit() does the trick too: any forms you have can still cancel this for instance if you want to present a save changes dialog.
Here's a couple ways to do this using the Joda-Time 2.3 library.
One way is to use the simple isBefore
and isAfter
methods on DateTime instances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.
Another way is to build an Interval in Joda-Time. The contains
method tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically [)
.
See both ways in the following code example.
Convert the java.util.Date instances to Joda-Time DateTime
instances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specific DateTimeZone
object rather than rely on JVM’s default time zone.
DateTime dateTime1 = new DateTime( new java.util.Date() ).minusWeeks( 1 );
DateTime dateTime2 = new DateTime( new java.util.Date() );
DateTime dateTime3 = new DateTime( new java.util.Date() ).plusWeeks( 1 );
Compare by testing for before/after…
boolean is1After2 = dateTime1.isAfter( dateTime2 );
boolean is2Before3 = dateTime2.isBefore( dateTime3 );
boolean is2Between1And3 = ( ( dateTime2.isAfter( dateTime1 ) ) && ( dateTime2.isBefore( dateTime3 ) ) );
Using the Interval approach instead of isAfter/isBefore…
Interval interval = new Interval( dateTime1, dateTime3 );
boolean intervalContainsDateTime2 = interval.contains( dateTime2 );
Dump to console…
System.out.println( "DateTimes: " + dateTime1 + " " + dateTime1 + " " + dateTime1 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
System.out.println( "is2Between1And3 " + is2Between1And3 );
System.out.println( "intervalContainsDateTime2 " + intervalContainsDateTime2 );
When run…
DateTimes: 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00
is1After2 false
is2Before3 true
is2Between1And3 true
intervalContainsDateTime2 true
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
ok,most of them have shown you something good. Let'me give you this:
// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
if len(timeFormat) > 1 {
log.SetFlags(log.Llongfile | log.LstdFlags)
log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
}
var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
switch v := tmp.(type) {
case int:
return strconv.Itoa(v)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case string:
return v
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case time.Time:
if len(timeFormat) == 1 {
return v.Format(timeFormat[0])
}
return v.Format("2006-01-02 15:04:05")
case jsoncrack.Time:
if len(timeFormat) == 1 {
return v.Time().Format(timeFormat[0])
}
return v.Time().Format("2006-01-02 15:04:05")
case fmt.Stringer:
return v.String()
case reflect.Value:
return ToString(v.Interface(), timeFormat...)
default:
return ""
}
}
Try Like this :
TextView text=(TextView)findViewById(R.id.textviewID);
text.setText("Text");
Instead of this:
text = (EditText) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");
The maximal length of the target column is shorter than the value you try to insert.
Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.
Edit:
Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.
This way I implement upload file to web API in project.
I share for whom concern.
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
Step by step
ASP.NET Web API
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML form
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
class="material-icons">save</i></button>
</div>
</form>
TS file to use API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
Service TS
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
You may try to use node attributes
property to keep compatibility with old browsers even IE6:
function getClassNode(element) {_x000D_
for (var i = element.attributes.length; i--;)_x000D_
if (element.attributes[i].nodeName === 'class')_x000D_
return element.attributes[i];_x000D_
}_x000D_
_x000D_
function removeClass(classNode, className) {_x000D_
var index, classList = classNode.value.split(' ');_x000D_
if ((index = classList.indexOf(className)) > -1) {_x000D_
classList.splice(index, 1);_x000D_
classNode.value = classList.join(' ');_x000D_
}_x000D_
}_x000D_
_x000D_
function hasClass(classNode, className) {_x000D_
return classNode.value.indexOf(className) > -1;_x000D_
}_x000D_
_x000D_
function addClass(classNode, className) {_x000D_
if (!hasClass(classNode, className))_x000D_
classNode.value += ' ' + className;_x000D_
}_x000D_
_x000D_
document.getElementById('message').addEventListener('click', function() {_x000D_
var classNode = getClassNode(this);_x000D_
var className = hasClass(classNode, 'red') && 'blue' || 'red';_x000D_
_x000D_
removeClass(classNode, 'red');_x000D_
removeClass(classNode, 'blue');_x000D_
_x000D_
addClass(classNode, className);_x000D_
})
_x000D_
.red {_x000D_
color: red;_x000D_
}_x000D_
.red:before {_x000D_
content: 'I am red! ';_x000D_
}_x000D_
.red:after {_x000D_
content: ' again';_x000D_
}_x000D_
.blue {_x000D_
color: blue;_x000D_
}_x000D_
.blue:before {_x000D_
content: 'I am blue! '_x000D_
}
_x000D_
<span id="message" class="">Click me</span>
_x000D_
You may be looking for auto-fill
:
grid-template-columns: repeat(auto-fill, 186px);
Demo: http://codepen.io/alanbuchanan/pen/wJRMox
To use up the available space more efficiently, you could use minmax
, and pass in auto
as the second argument:
grid-template-columns: repeat(auto-fill, minmax(186px, auto));
Demo: http://codepen.io/alanbuchanan/pen/jBXWLR
If you don't want the empty columns, you could use auto-fit
instead of auto-fill
.
When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.
R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.
If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.
But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.
Explore yourself with the following code:
> x <- 1:3
> y <- c(1,2,4)
> x == y
[1] TRUE TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1] TRUE TRUE FALSE TRUE TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1] TRUE TRUE FALSE FALSE
Warning message:
In x == y2 :
longer object length is not a multiple of shorter object length
Never call
setState
insiderender
method
You should never ever call setState
inside the render
method. Why? calling setState
eventually fires the render
method again. That means you are calling setState (mentioned in your render
block) in a loop that would never end. The correct way to do that is by using componentDidMount
hook in React, like so:
class CowtanApp extends Component {
state = {
timePassed: false
}
componentDidMount () {
setTimeout(() => this.setState({timePassed: true}), 1000)
}
render () {
return this.state.timePassed ? (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
) : <LoadingPage/>
}
}
PS Use ternary operators for cleaner, shorter and readable code.
"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding
For a regular dict, you can use:
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new
was already existing in which case it will overwrite the value in-place.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2
to 'two'
:
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}
The same is true for an OrderedDict
, where you can't use dict comprehension syntax, but you can use a generator expression:
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.
Actually this is very straightforward with CSS3 flex boxes.
.flex-container{
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex; /* NEW, Spec - Firefox, Chrome, Opera */
justify-content: center;
align-items: center;
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
width: 100px;
height: 100px;
background-color: #f1c40f;
}
_x000D_
<div class="flex-container">
<div class="inner-element"></div>
</div>
_x000D_
It seems that I didn't read the OP edit at the time I wrote this answer. The above code will center all inner elements (without overlapping between them), but the OP wants just an specific element to be centered, not the other inner elements. So @Warface answer second method is more appropiate, but it still requires vertical centering:
.flex-container{
position: relative;
/* Other styling stuff */
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* or 3d alternative if you will add animations (smoother transitions) */
transform: translate3d(-50%,-50%,0);
/* Other styling stuff */
width: 100px;
height: 100px;
background-color: #f1c40f;
}
_x000D_
<div class="flex-container">
<p>Other inner elements like this follows the normal flow.</p>
<div class="inner-element"></div>
</div>
_x000D_
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
With mailx you can do:
mailx -s "My Subject" -a ./mail_att.csv -S [email protected] [email protected] < ./mail_body.txt
This worked great on our GNU Linux servers, but unfortunately my dev environment is Mac OsX which only has a crummy old BSD version of mailx. Normally I use Coreutils to get better versions of unix commands than the Mac BSD ones, but mailx is not in Coreutils.
I found a solution from notpeter in an unrelated thread (https://serverfault.com/questions/196001/using-unix-mail-mailx-with-a-modern-mail-server-imap-instead-of-mbox-files) which was to download the Heirloom mailx OSX binary package from http://www.tramm.li/iWiki/HeirloomNotes.html. It has a more featured mailx which can handle the above command syntax.
(Apologies for poor cross linking linking or attribution, I'm new to the site.)
You can also use my implementations on google.colab and PyDrive at https://github.com/ruelj2/Google_drive which makes it a lot easier.
!pip install - U - q PyDrive
import os
os.chdir('/content/')
!git clone https://github.com/ruelj2/Google_drive.git
from Google_drive.handle import Google_drive
Gd = Google_drive()
Then, if you want to load all files in a Google Drive directory, just
Gd.load_all(local_dir, drive_dir_ID, force=False)
Or just a specific file with
Gd.load_file(local_dir, file_ID)
You have to give width:100%
to parent to center
the text.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
If you also need to centre align vertically, give height:100%
and align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .
I have also provided the source please check it.
public void setBounds(int x,
int y,
int width,
int height)
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.
Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component
source:- setBounds
function getPercentUsed() {
$sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
return $val[0];
}
For intellij users: If you want to make changes in interactive way for past commits, which are not pushed follow below steps in Intellij:
Hope it helps
To easily debug Ruby shell script, just change its first line from:
#!/usr/bin/env ruby
to:
#!/usr/bin/env ruby -rdebug
Then every time when debugger console is shown, you can choose:
c
for Continue (to the next Exception, breakpoint or line with: debugger
),n
for Next line,w
/where
to Display frame/call stack,l
to Show the current code,cat
to show catchpoints.h
for more Help.See also: Debugging with ruby-debug, Key shortcuts for ruby-debug gem.
In case the script just hangs and you need a backtrace, try using lldb
/gdb
like:
echo 'call (void)rb_backtrace()' | lldb -p $(pgrep -nf ruby)
and then check your process foreground.
Replace lldb
with gdb
if works better. Prefix with sudo
to debug non-owned process.
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
The best way I think is to just declare the desired enum values. That way accessing them is clean and pretty (every time).
enum myEnum { entry1 = 'VALUE1', entry2 = 'VALUE2' }
for (var entry in myEnum) {
console.log(entry);
}
will produce:
VALUE1
VALUE2
The way I fixed similar issue was by adding Month to my SELECT portion
Month DATEADD(day,Created_Date,'1971/12/31') As Month
and than I added WHERE statement
Month DATEADD(day,Created_Date,'1971/12/31') = month(getdate())-1
Running the command prompt or Powershell ISE as an administrator fixed this for me.
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
I am not 100% sure what the conditions are for this, but for me the above didn't work directly, thought it got close. I think it was because I needed "id" for my view by in the model it was called "ObjectID".
I had a model with a variety of pieces of information. I just needed the id.
Before the above I created a new System.Web.Routing.RouteValueDictionary object and added the needed id.
(System.Web.Routing.)RouteValueDictionary RouteInfo = new RouteValueDictionary();
RouteInfo.Add("id", ObjectID);
return RedirectToAction("details", RouteInfo);
(Note: the MVC project in question I didn't create, so I don't know where all the right "fiddly" bits are.)
No, but it's been requested many times.
I wrote a similar solution some time ago.
Of course it's just a PoC and can be improved further.
This solution covers the following features:
const pattern = "__/__/____";_x000D_
const patternFreeChar = "_";_x000D_
const validDate = [_x000D_
/^[0-3]$/,_x000D_
/^(0[1-9]|[12]\d|3[01])$/,_x000D_
/^(0[1-9]|[12]\d|3[01])[01]$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)[12]$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)(19|20)/_x000D_
]_x000D_
_x000D_
/**_x000D_
* Validate a date as your type._x000D_
* @param {string} date The date in format DDMMYYYY as a string representation._x000D_
* @throws {Error} When the date is invalid._x000D_
*/_x000D_
function validateStartTypingDate(date) {_x000D_
if ( !date ) return "";_x000D_
_x000D_
date = date.substr(0, 8);_x000D_
_x000D_
if ( !/^\d+$/.test(date) )_x000D_
throw new Error("Please type numbers only");_x000D_
_x000D_
if ( !validDate[Math.min(date.length-1,validDate.length-1)].test(date) ) {_x000D_
let errMsg = "";_x000D_
switch ( date.length ) {_x000D_
case 1:_x000D_
throw new Error("Day in month can start only with 0, 1, 2 or 3");_x000D_
_x000D_
case 2:_x000D_
throw new Error("Day in month must be in a range between 01 and 31");_x000D_
_x000D_
case 3:_x000D_
throw new Error("Month can start only with 0 or 1");_x000D_
_x000D_
case 4: {_x000D_
const day = parseInt(date.substr(0,2));_x000D_
const month = parseInt(date.substr(2,2));_x000D_
const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
_x000D_
if ( month < 1 || month > 12 )_x000D_
throw new Error("Month number must be in a range between 01 and 12");_x000D_
_x000D_
if ( day > 30 && [4,6,9,11].includes(month) )_x000D_
throw new Error(`${monthName} have maximum 30 days`);_x000D_
_x000D_
if ( day > 29 && month === 2 )_x000D_
throw new Error(`${monthName} have maximum 29 days`);_x000D_
break; _x000D_
}_x000D_
_x000D_
case 5:_x000D_
case 6:_x000D_
throw new Error("We support only years between 1900 and 2099, so the full year can start only with 19 or 20");_x000D_
}_x000D_
}_x000D_
_x000D_
if ( date.length === 8 ) {_x000D_
const day = parseInt(date.substr(0,2));_x000D_
const month = parseInt(date.substr(2,2));_x000D_
const year = parseInt(date.substr(4,4));_x000D_
const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
if ( !isLeap(year) && month === 2 && day === 29 )_x000D_
throw new Error(`The year you are trying to enter (${year}) is not a leap year. Thus, in this year, ${monthName} can have maximum 28 days`);_x000D_
}_x000D_
_x000D_
return date;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Check whether the given year is a leap year._x000D_
*/_x000D_
function isLeap(year) {_x000D_
return new Date(year, 1, 29).getDate() === 29;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Move cursor to the end of the provided input element._x000D_
*/_x000D_
function moveCursorToEnd(el) {_x000D_
if (typeof el.selectionStart == "number") {_x000D_
el.selectionStart = el.selectionEnd = el.value.length;_x000D_
} else if (typeof el.createTextRange != "undefined") {_x000D_
el.focus();_x000D_
var range = el.createTextRange();_x000D_
range.collapse(false);_x000D_
range.select();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Move cursor to the end of the self input element._x000D_
*/_x000D_
function selfMoveCursorToEnd() {_x000D_
return moveCursorToEnd(this);_x000D_
}_x000D_
_x000D_
const input = document.querySelector("input")_x000D_
_x000D_
input.addEventListener("keydown", function(event){_x000D_
event.preventDefault();_x000D_
document.getElementById("date-error-msg").innerText = "";_x000D_
_x000D_
// On digit pressed_x000D_
let inputMemory = this.dataset.inputMemory || "";_x000D_
_x000D_
if ( event.key.length === 1 ) {_x000D_
try {_x000D_
inputMemory = validateStartTypingDate(inputMemory + event.key);_x000D_
} catch (err) {_x000D_
document.getElementById("date-error-msg").innerText = err.message;_x000D_
}_x000D_
}_x000D_
_x000D_
// On backspace pressed_x000D_
if ( event.code === "Backspace" ) {_x000D_
inputMemory = inputMemory.slice(0, -1);_x000D_
}_x000D_
_x000D_
// Build an output using a pattern_x000D_
if ( this.dataset.inputMemory !== inputMemory ) {_x000D_
let output = pattern;_x000D_
for ( let i=0, digit; i<inputMemory.length, digit=inputMemory[i]; i++ ) {_x000D_
output = output.replace(patternFreeChar, digit);_x000D_
}_x000D_
this.dataset.inputMemory = inputMemory;_x000D_
this.value = output;_x000D_
}_x000D_
_x000D_
// Clean the value if the memory is empty_x000D_
if ( inputMemory === "" ) {_x000D_
this.value = "";_x000D_
}_x000D_
}, false);_x000D_
_x000D_
input.addEventListener('select', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mousedown', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mouseup', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('click', selfMoveCursorToEnd, false);
_x000D_
<input type="text" placeholder="DD/MM/YYYY" />_x000D_
<div id="date-error-msg"></div>
_x000D_
A link to jsfiddle: https://jsfiddle.net/d1xbpw8f/56/
Good luck!
Just for fun, consider the different question one would get with a very literal interpretation of the OP's description: "Write a query to print the list of names of students who have scored the maximum mark in each subject."
Those who've answered here have written queries to list a student if he or she scored the maximum mark in any one subject, but not necessarily in all subjects. Since the question posed by the OP does not ask for subject names in the output, this is a plausible interpretation.
To list the names of students (if any) who have scored the maximum mark in all subjects (excluding subjects with no marks, since arguably there is then no maximum mark then), I think this works, using column names from Michael's SQL Fiddle, which I've adapted here.
select StudentName
from Student
where not exists (
select * from Subject
where exists (
select * from Mark as M1
where M1.SubjectID = Subject.SubjectID
and M1.StudentID <> Student.StudentID
and not exists (
select * from Mark as M2
where M2.StudentID = Student.StudentID
and M2.SubjectID = M1.SubjectID
and M2.MarkRate >= M1.MarkRate
)
)
)
In other words, select a student X's name if there is no subject in which someone's mark for that subject is not matched or exceeded by some mark belonging to X for the same subject. (This query returns a student's name if the student has received more than one mark in a subject, so long as one of those marks is the highest for the subject.)
A very easy way to understand typedef of function pointer:
int add(int a, int b)
{
return (a+b);
}
typedef int (*add_integer)(int, int); //declaration of function pointer
int main()
{
add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
int c = addition(11, 11); //calling function via new variable
printf("%d",c);
return 0;
}
You can use jQuery plugin with the inview
event like this :
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
I have faced this issue, but found an answer before finding this post :
Based on unutbu's answer, load your data...
import pandas as pd
import io
texts = ['''\
id Name score isEnrolled Date
111 Jack True 2013-05-01 12:00:00
112 Nick 1.11 False 2013-05-12 15:05:23
Zoe 4.12 True ''',
'''\
id Name score isEnrolled Date
111 Jack 2.17 True 2013-05-01 12:00:00
112 Nick 1.21 False
Zoe 4.12 False 2013-05-01 12:00:00''']
df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,17,20], parse_dates=[4])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,17,20], parse_dates=[4])
...define your diff function...
def report_diff(x):
return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
Then you can simply use a Panel to conclude :
my_panel = pd.Panel(dict(df1=df1,df2=df2))
print my_panel.apply(report_diff, axis=0)
# id Name score isEnrolled Date
#0 111 Jack nan | 2.17 True 2013-05-01 12:00:00
#1 112 Nick 1.11 | 1.21 False 2013-05-12 15:05:23 | NaT
#2 nan | nan Zoe 4.12 True | False NaT | 2013-05-01 12:00:00
By the way, if you're in IPython Notebook, you may like to use a colored diff function to give colors depending whether cells are different, equal or left/right null :
from IPython.display import HTML
pd.options.display.max_colwidth = 500 # You need this, otherwise pandas
# will limit your HTML strings to 50 characters
def report_diff(x):
if x[0]==x[1]:
return unicode(x[0].__str__())
elif pd.isnull(x[0]) and pd.isnull(x[1]):
return u'<table style="background-color:#00ff00;font-weight:bold;">'+\
'<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % ('nan', 'nan')
elif pd.isnull(x[0]) and ~pd.isnull(x[1]):
return u'<table style="background-color:#ffff00;font-weight:bold;">'+\
'<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % ('nan', x[1])
elif ~pd.isnull(x[0]) and pd.isnull(x[1]):
return u'<table style="background-color:#0000ff;font-weight:bold;">'+\
'<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % (x[0],'nan')
else:
return u'<table style="background-color:#ff0000;font-weight:bold;">'+\
'<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % (x[0], x[1])
HTML(my_panel.apply(report_diff, axis=0).to_html(escape=False))
If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:
INSERT INTO tbl_member
(Field1,Field2,Field3,...)
SELECT a.Field1,a.Field2,a.Field3,...
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a
LEFT JOIN tbl_member AS b
ON a.Field1 = b.Field1
WHERE b.Field1 IS NULL
The record to be inserted is in the new value fields.
Similar to getting the length of a dataframe, len(df)
, the following worked for pandas and blaze:
Total = sum(df['MyColumn'])
or alternatively
Total = sum(df.MyColumn)
print Total
Try to use ;
instead of GO
. It worked for me for 2008 R2 version
DECLARE @GLOBAL_VAR_1 INT = Value_1;
DECLARE @GLOBAL_VAR_2 INT = Value_2;
USE "DB_1";
SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_1
AND "COL_2" = @GLOBAL_VAR_2;
USE "DB_2";
SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_2;
you can use the simpleDateFormat to parse the string date.
Here is the simple version
#one
a = [[0]*10]*10
#two
row, col = 10, 10
a = [[0]*row]*col
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods.
While you can call these methods directly ([10, 20].__len__()
for example), the presence of the underscores is a hint that these methods are intended to be invoked indirectly (len([10, 20])
for example). Most python operators have an associated "magic" method (for example, a[x]
is the usual way of invoking a.__getitem__(x)
).
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)
<input @change="foo" v-model... >
If you wanna detect single character changes (during user typing) use
<input @keydown="foo" v-model... >
You can also use @keyup
and @input
events. If you wanna to pass additional parameters use in template e.g. @keyDown="foo($event, param1, param2)"
. Comparision below (editable version here)
new Vue({_x000D_
el: "#app",_x000D_
data: { _x000D_
keyDown: { key:null, val: null, model: null, modelCopy: null },_x000D_
keyUp: { key:null, val: null, model: null, modelCopy: null },_x000D_
change: { val: null, model: null, modelCopy: null },_x000D_
input: { val: null, model: null, modelCopy: null },_x000D_
_x000D_
_x000D_
},_x000D_
methods: {_x000D_
_x000D_
keyDownFun: function(event){ // type of event: KeyboardEvent _x000D_
console.log(event); _x000D_
this.keyDown.key = event.key; // or event.keyCode_x000D_
this.keyDown.val = event.target.value; // html current input value_x000D_
this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
keyUpFun: function(event){ // type of event: KeyboardEvent_x000D_
console.log(event); _x000D_
this.keyUp.key = event.key; // or event.keyCode_x000D_
this.keyUp.val = event.target.value; // html current input value_x000D_
this.keyUp.modelCopy = this.keyUp.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
changeFun: function(event) { // type of event: Event_x000D_
console.log(event);_x000D_
this.change.val = event.target.value; // html current input value_x000D_
this.change.modelCopy = this.change.model; // copy of model value at the moment on event handling_x000D_
},_x000D_
_x000D_
inputFun: function(event) { // type of event: Event_x000D_
console.log(event);_x000D_
this.input.val = event.target.value; // html current input value_x000D_
this.input.modelCopy = this.input.model; // copy of model value at the moment on event handling_x000D_
}_x000D_
}_x000D_
})
_x000D_
div {_x000D_
margin-top: 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
Type in fields below (to see events details open browser console)_x000D_
_x000D_
<div id="app">_x000D_
<div><input type="text" @keyDown="keyDownFun" v-model="keyDown.model"><br> @keyDown (note: model is different than value and modelCopy)<br> key:{{keyDown.key}}<br> value: {{ keyDown.val }}<br> modelCopy: {{keyDown.modelCopy}}<br> model: {{keyDown.model}}</div>_x000D_
_x000D_
<div><input type="text" @keyUp="keyUpFun" v-model="keyUp.model"><br> @keyUp (note: model change value before event occure) <br> key:{{keyUp.key}}<br> value: {{ keyUp.val }}<br> modelCopy: {{keyUp.modelCopy}}<br> model: {{keyUp.model}}</div>_x000D_
_x000D_
<div><input type="text" @change="changeFun" v-model="change.model"><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: {{ change.val }}<br> modelCopy: {{change.modelCopy}}<br> model: {{change.model}}</div>_x000D_
_x000D_
<div><input type="text" @input="inputFun" v-model="input.model"><br> @input<br> value: {{ input.val }}<br> modelCopy: {{input.modelCopy}}<br> model: {{input.model}}</div>_x000D_
_x000D_
</div>
_x000D_
Building on @sreedeep-kesav's answer (not enough rep to comment), Privacy - Camera Usage Description
and Privacy - Photo Library Usage Description
can be set by opening your Info.plist
file in Xcode and selecting the plus button next to Information Property List
:
df --output=avail -B 1 "$PWD" |tail -n 1
you get size in bytes this way.
I've found this to work for my code,, however my code is getting the class out of an array within a for loop.
String className="";
className = list[i].getClass().getCanonicalName();
System.out.print(className); //Use this to test it works
I had the same issue as @Gravity Grave whereby scrolling doesn't work if you use
data-toggle="modal" data-target="TARGET-2"
in conjunction with
data-dismiss="modal"
The scroll doesn't work correctly and reverts to scrolling the page rather than the modal. This is due to data-dismiss removing the modal-open class from the tag.
My solution in the end was to set the html of the inner component on the modal and use css to fade the text in/out.
In Windows 10 I had to run the batch file as an administrator.
I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
Bash can get the last part of a path without having to call the external basename
:
subdir="/path/to/whatever/${1##*/}"
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
And, of course, the CORS spec:
~Cheers
Here's the list of logger categories:
Category Function
org.hibernate.SQL Log all SQL DML statements as they are executed
org.hibernate.type Log all JDBC parameters
org.hibernate.tool.hbm2ddl Log all SQL DDL statements as they are executed
org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache Log all second-level cache activity
org.hibernate.transaction Log transaction related activity
org.hibernate.jdbc Log all JDBC resource acquisition
org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing
org.hibernate.secure Log all JAAS authorization requests
org.hibernate Log everything (a lot of information, but very useful for troubleshooting)
Formatted for pasting into a log4j XML configuration file:
<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />
NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.
And a category is specified as such:
<logger name="org.hibernate">
<level value="ALL" />
<appender-ref ref="FILE"/>
</logger>
It must be placed before the root element.
Instead of using URLConnection use HttpURLConnection by calling openConnection() on your URL object.
Then use getResponseCode() will give you the HTTP response once you've read from the connection.
here is code:
HttpURLConnection connection = null;
try {
URL u = new URL("http://www.google.com/");
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
Also check similar question How to check if a URL exists or returns 404 with Java?
Hope this helps.
I use SLF4J + Logback classic and apply it like this:
trait Logging {
lazy val logger = LoggerFactory.getLogger(getClass)
implicit def logging2Logger(anything: Logging): Logger = anything.logger
}
Then you can use it whichever fits your style better:
class X with Logging {
logger.debug("foo")
debug("bar")
}
but this approach of course uses a logger instance per class instance.
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.
export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT
sudo apt-get install openjdk-8-jdk
Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address
cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip
Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.
PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin
This had no effect for me, hence the next step
cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin
yes | sudo sdkmanager --licenses
Finally, run this inside your project
sudo ./gradlew assembleDebug
This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.
https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40
Android Command line tools sdkmanager always shows: Warning: Could not create settings
"Failed to install the following Android SDK packages as some licences have not been accepted" error
https://developer.android.com/studio/build/building-cmdline#sign_cmdline
use App\Http\Controllers\InvoiceController; // InvoiceController is controller name Route::get('invoice',[InvoiceController::class, 'index']);
protected $namespace = 'App\\Http\\Controllers';
If you need a custom string sort, you can create a function that returns a number based on the order you specify.
For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:
Private Function sortpictures(s As String) As Integer
If Regex.IsMatch(s, "FRONT") Then
Return 0
ElseIf Regex.IsMatch(s, "SIDE") Then
Return 1
ElseIf Regex.IsMatch(s, "CLASP") Then
Return 2
Else
Return 3
End If
End Function
Then I call the sort function like this:
list.Sort(Function(elA As String, elB As String)
Return sortpictures(elA).CompareTo(sortpictures(elB))
End Function)
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Try below Alphanumeric regex
"^[a-zA-Z0-9]*$"
^ - Start of string
[a-zA-Z0-9]* - multiple characters to include
$ - End of string
See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
I found this very useful. It is a very simple approach where you create patches that are applied to the new repo. See the linked page for more details.
It only contains three steps (copied from the blog):
# Setup a directory to hold the patches
mkdir <patch-directory>
# Create the patches
git format-patch -o <patch-directory> --root /path/to/copy
# Apply the patches in the new repo using a 3 way merge in case of conflicts
# (merges from the other repo are not turned into patches).
# The 3way can be omitted.
git am --3way <patch-directory>/*.patch
The only issue I had was that I could not apply all patches at once using
git am --3way <patch-directory>/*.patch
Under Windows I got an InvalidArgument error. So I had to apply all patches one after another.
You can use this;
Form1 button1 click
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
this.Hide();
frm2.Show();
}
And add this to Form2
public string info = "";
Form2 button1 click
private void button1_Click(object sender, EventArgs e)
{
info = textBox1.Text;
this.Hide();
BeginInvoke(new MethodInvoker(() =>
{
Gogo();
}));
}
public void Gogo()
{
Form1 frm = new Form1();
frm.Show();
frm.Text = info;
}
Since you can't rollback you should merge that commit into the new head you got when you pulled. If you don't want any of the work you did in it you can easily do that using this tip.
So if you've pulled and updated to their head you can do this:
hg --config ui.merge=internal:local merge
keeps all the changes in the currently checked out revision, and none of the changes in the not-checked-out revision (the one you wrote that you no longer want).
This is a great way to do it because it keeps your history accurate and complete. If 2 years from now someone finds a bug in what you pulled down you can look in your (unused but saved) implementation of the same thing and go, "oh, I did it right". :)
What is this for and why would I use @":\" instead of ":\"?
Because when you have a long string with many \
you don't need to escape them all and the \n
, \r
and \f
won't work too.
Each record from the left table will be returned as many times as there are matching records on the right table -- at least 1, but could easily be more than 1.
You can even pass parameters to the sed command:
test.sh
#!/bin/bash
echo "-> start"
for i in $(seq 5); do
# passing parameters to sed
j=$(($i+3))
sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit
orignial output.dat:
a
b
c
d
e
f
g
h
i
j
Executing ./test.sh gives the new output.dat
a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j
The example in Javascript: The Good Parts can be adapted to do this:
var doubled_words = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1(?:\s|$)/gi;
\b uses \w for word boundaries, where \w is equivalent to [0-9A-Z_a-z]. If you don't mind that limitation, the accepted answer is fine.
I needed this for javascript for use in an html5 canvas for detecting if the users cursor was over or near a certain line. So I modified the answer given by Darius Bacon into coffeescript:
is_on = (a,b,c) ->
# "Return true if point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
return (collinear(a,b,c) and withincheck(a,b,c))
withincheck = (a,b,c) ->
if a[0] != b[0]
within(a[0],c[0],b[0])
else
within(a[1],c[1],b[1])
collinear = (a,b,c) ->
# "Return true if a, b, and c all lie on the same line."
((b[0]-a[0])*(c[1]-a[1]) < (c[0]-a[0])*(b[1]-a[1]) + 1000) and ((b[0]-a[0])*(c[1]-a[1]) > (c[0]-a[0])*(b[1]-a[1]) - 1000)
within = (p,q,r) ->
# "Return true if q is between p and r (inclusive)."
p <= q <= r or r <= q <= p
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.
I finally ended with:
EXIT_ON_CLOSE
as this can leave resources behind;Do use something like the following in the JFrame initialization:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame()
returns a reference to the JFrame:
public class AppMenuFileExit extends JMenuItem implements ActionListener
{
// do your normal menu item code here
@Override
public void actionPerformed(ActionEvent e)
{
WindowEvent we;
we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
App.getFrame().dispatchEvent(we);
}
}
JFrame is a subclass of Window so may be cast to Window for this purpose.
And, have the following in your JFrame class to handle Window messages:
public class AppFrame extends JFrame implements WindowListener
{
// Do all the things you need to for the class
@Override
public void windowOpened(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{/* can do cleanup here if necessary */}
@Override
public void windowClosed(WindowEvent e)
{
dispose();
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowDeactivated(WindowEvent e)
{}
@Override
public void windowDeiconified(WindowEvent e)
{}
@Override
public void windowIconified(WindowEvent e)
{}
}
It is there to specify another column as the default id column of the other table, e.g. consider the following
TableA
id int identity
tableb_key varchar
TableB
id int identity
key varchar unique
// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")
Try this, it worked for me!
If you happen to have Eclipse not responding anymore sometimes, the reason could be that you sit on a 64bit machine where eclipse needs more memory. Be sure to have (at least) the following configurations in your eclipse.ini (I even use bigger values for the PermSizes):
-Xms512m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m
.p12
and .pfx
are both PKCS #12 files. Am I missing something?
Have you tried renaming the exported .pfx
file to have a .p12
extension?
Found another interesting solution
SELECT salary
FROM emp
WHERE salary = (SELECT DISTINCT(salary)
FROM emp as e1
WHERE (n) = (SELECT COUNT(DISTINCT(salary))
FROM emp as e2
WHERE e1.salary <= e2.salary))
Sorry. Forgot to write. n is the nth number of salary which you want.
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
I'm afraid that the first of those command lines unconditionally deleted from the working copy all the files that are in git's staging area. The second one unstaged all the files that were tracked but have now been deleted. Unfortunately this means that you will have lost any uncommitted modifications to those files.
If you want to get your working copy and index back to how they were at the last commit, you can (carefully) use the following command:
git reset --hard
I say "carefully" since git reset --hard
will obliterate uncommitted changes in your working copy and index. However, in this situation it sounds as if you just want to go back to the state at your last commit, and the uncommitted changes have been lost anyway.
Update: it sounds from your comments on Amber's answer that you haven't yet created any commits (since HEAD cannot be resolved), so this won't help, I'm afraid.
As for how those pipes work: git ls-files -z
and git diff --name-only --diff-filter=D -z
both output a list of file names separated with the byte 0
. (This is useful, since, unlike newlines, 0
bytes are guaranteed not to occur in filenames on Unix-like systems.) The program xargs
essentially builds command lines from its standard input, by default by taking lines from standard input and adding them to the end of the command line. The -0
option says to expect standard input to by separated by 0
bytes. xargs
may invoke the command several times to use up all the parameters from standard input, making sure that the command line never becomes too long.
As a simple example, if you have a file called test.txt
, with the following contents:
hello
goodbye
hello again
... then the command xargs echo whatever < test.txt
will invoke the command:
echo whatever hello goodbye hello again
There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:
Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:
JImageComponent ic = new JImageComponent(myImageGoesHere);
imagePanel.add(ic);
where JImageComponent is a self created class that extends JComponent
that overrides the paintComponent()
method to draw the image.
From the Intel's manual - Instruction Set Reference, the JE
and JZ
have the same opcode (74
for rel8 / 0F 84
for rel 16/32) also JNE
and JNZ
(75
for rel8 / 0F 85
for rel 16/32) share opcodes.
JE
and JZ
they both check for the ZF
(or zero flag), although the manual differs slightly in the descriptions of the first JE
rel8 and JZ
rel8 ZF
usage, but basically they are the same.
Here is an extract from the manual's pages 464, 465 and 467.
Op Code | mnemonic | Description
-----------|-----------|-----------------------------------------------
74 cb | JE rel8 | Jump short if equal (ZF=1).
74 cb | JZ rel8 | Jump short if zero (ZF ? 1).
0F 84 cw | JE rel16 | Jump near if equal (ZF=1). Not supported in 64-bit mode.
0F 84 cw | JZ rel16 | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
0F 84 cd | JE rel32 | Jump near if equal (ZF=1).
0F 84 cd | JZ rel32 | Jump near if 0 (ZF=1).
75 cb | JNE rel8 | Jump short if not equal (ZF=0).
75 cb | JNZ rel8 | Jump short if not zero (ZF=0).
0F 85 cd | JNE rel32 | Jump near if not equal (ZF=0).
0F 85 cd | JNZ rel32 | Jump near if not zero (ZF=0).
For multiple classes
in the same js
file, extending Component
from @wordpress/element
, you can do that :
// classes.js
import { Component } from '@wordpress/element';
const Class1 = class extends Component {
}
const Class2 = class extends Component {
}
export { Class1, Class2 }
And import them in another js
file :
import { Class1, Class2 } from './classes';
Probably shortest (based on OR operator and its precedence)
x-2||dosomething()
let x=1, y=2;_x000D_
let dosomething = s=>console.log(s); _x000D_
_x000D_
x-2||dosomething('x do something');_x000D_
y-2||dosomething('y do something');
_x000D_
foreach($array as $item=>$values){
echo $values->filepath;
}
if ($("#Password").val() != $("#ConfirmPassword").val()) {
alert("Passwords do not match.");
}
A JQuery approach that will eliminate needless code.
Android provides a couple of different library sets. One is called the Android support Library, and the other is called AndroidX. Selecting "Use android.* artifacts" indicates that we want to use AndroidX.
This may be useful for who want to use dateformater.dateformat
;
if you want 12.09.18
you use dateformater.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
You can pass values from one page to another by followings..
Response.Redirect
Cookies
Application Variables
HttpContext
Response.Redirect
SET :
Response.Redirect("Defaultaspx?Name=Pandian");
GET :
string Name = Request.QueryString["Name"];
Cookies
SET :
HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian";
GET :
string name = Request.Cookies["Name"].Value;
Application Variables
SET :
Application["Name"] = "pandian";
GET :
string Name = Application["Name"].ToString();
Refer the full content here : Pass values from one to another
datetime2 wins in most aspects except (old apps Compatibility)
please note the following points
image source : MCTS Self-Paced Training Kit (Exam 70-432): Microsoft® SQL Server® 2008 - Implementation and Maintenance Chapter 3:Tables -> Lesson 1: Creating Tables -> page 66
I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.
I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.
EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager
for it. Here's some sample code that works with your sample document:
using System;
using System.Xml;
public class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
namespaces.AddNamespace("ns", "urn:hl7-org:v3");
doc.Load("test.xml");
XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
string msgID = idNode.Attributes["extension"].Value;
Console.WriteLine(msgID);
}
}
A formal analysis has been done by Phil Rogaway in 2011, here. Section 1.6 gives a summary that I transcribe here, adding my own emphasis in bold (if you are impatient, then his recommendation is use CTR mode, but I suggest that you read my paragraphs about message integrity versus encryption below).
Note that most of these require the IV to be random, which means non-predictable and therefore should be generated with cryptographic security. However, some require only a "nonce", which does not demand that property but instead only requires that it is not re-used. Therefore designs that rely on a nonce are less error prone than designs that do not (and believe me, I have seen many cases where CBC is not implemented with proper IV selection). So you will see that I have added bold when Rogaway says something like "confidentiality is not achieved when the IV is a nonce", it means that if you choose your IV cryptographically secure (unpredictable), then no problem. But if you do not, then you are losing the good security properties. Never re-use an IV for any of these modes.
Also, it is important to understand the difference between message integrity and encryption. Encryption hides data, but an attacker might be able to modify the encrypted data, and the results can potentially be accepted by your software if you do not check message integrity. While the developer will say "but the modified data will come back as garbage after decryption", a good security engineer will find the probability that the garbage causes adverse behaviour in the software, and then he will turn that analysis into a real attack. I have seen many cases where encryption was used but message integrity was really needed more than the encryption. Understand what you need.
I should say that although GCM has both encryption and message integrity, it is a very fragile design: if you re-use an IV, you are screwed -- the attacker can recover your key. Other designs are less fragile, so I personally am afraid to recommend GCM based upon the amount of poor encryption code that I have seen in practice.
If you need both, message integrity and encryption, you can combine two algorithms: usually we see CBC with HMAC, but no reason to tie yourself to CBC. The important thing to know is encrypt first, then MAC the encrypted content, not the other way around. Also, the IV needs to be part of the MAC calculation.
I am not aware of IP issues.
Now to the good stuff from Professor Rogaway:
ECB: A blockcipher, the mode enciphers messages that are a multiple of n bits by separately enciphering each n-bit piece. The security properties are weak, the method leaking equality of blocks across both block positions and time. Of considerable legacy value, and of value as a building block for other schemes, but the mode does not achieve any generally desirable security goal in its own right and must be used with considerable caution; ECB should not be regarded as a “general-purpose” confidentiality mode.
CBC: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is merely a nonce, nor if it is a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are highly malleable. No chosen ciphertext attack (CCA) security. Confidentiality is forfeit in the presence of a correct-padding oracle for many padding methods. Encryption inefficient from being inherently serial. Widely used, the mode’s privacy-only security properties result in frequent misuse. Can be used as a building block for CBC-MAC algorithms. I can identify no important advantages over CTR mode.
CFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is predictable, nor if it is made by a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are malleable. No CCA-security. Encryption inefficient from being inherently serial. Scheme depends on a parameter s, 1 = s = n, typically s = 1 or s = 8. Inefficient for needing one blockcipher call to process only s bits . The mode achieves an interesting “self-synchronization” property; insertion or deletion of any number of s-bit characters into the ciphertext only temporarily disrupts correct decryption.
OFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is a nonce, although a fixed sequence of IVs (eg, a counter) does work fine. Ciphertexts are highly malleable. No CCA security. Encryption and decryption inefficient from being inherently serial. Natively encrypts strings of any bit length (no padding needed). I can identify no important advantages over CTR mode.
CTR: An IV-based encryption scheme, the mode achieves indistinguishability from random bits assuming a nonce IV. As a secure nonce-based scheme, the mode can also be used as a probabilistic encryption scheme, with a random IV. Complete failure of privacy if a nonce gets reused on encryption or decryption. The parallelizability of the mode often makes it faster, in some settings much faster, than other confidentiality modes. An important building block for authenticated-encryption schemes. Overall, usually the best and most modern way to achieve privacy-only encryption.
XTS: An IV-based encryption scheme, the mode works by applying a tweakable blockcipher (secure as a strong-PRP) to each n-bit chunk. For messages with lengths not divisible by n, the last two blocks are treated specially. The only allowed use of the mode is for encrypting data on a block-structured storage device. The narrow width of the underlying PRP and the poor treatment of fractional final blocks are problems. More efficient but less desirable than a (wide-block) PRP-secure blockcipher would be.
ALG1–6: A collection of MACs, all of them based on the CBC-MAC. Too many schemes. Some are provably secure as VIL PRFs, some as FIL PRFs, and some have no provable security. Some of the schemes admit damaging attacks. Some of the modes are dated. Key-separation is inadequately attended to for the modes that have it. Should not be adopted en masse, but selectively choosing the “best” schemes is possible. It would also be fine to adopt none of these modes, in favor of CMAC. Some of the ISO 9797-1 MACs are widely standardized and used, especially in banking. A revised version of the standard (ISO/IEC FDIS 9797-1:2010) will soon be released [93].
CMAC: A MAC based on the CBC-MAC, the mode is provably secure (up to the birthday bound) as a (VIL) PRF (assuming the underlying blockcipher is a good PRP). Essentially minimal overhead for a CBCMAC-based scheme. Inherently serial nature a problem in some application domains, and use with a 64-bit blockcipher would necessitate occasional re-keying. Cleaner than the ISO 9797-1 collection of MACs.
HMAC: A MAC based on a cryptographic hash function rather than a blockcipher (although most cryptographic hash functions are themselves based on blockciphers). Mechanism enjoys strong provable-security bounds, albeit not from preferred assumptions. Multiple closely-related variants in the literature complicate gaining an understanding of what is known. No damaging attacks have ever been suggested. Widely standardized and used.
GMAC: A nonce-based MAC that is a special case of GCM. Inherits many of the good and bad characteristics of GCM. But nonce-requirement is unnecessary for a MAC, and here it buys little benefit. Practical attacks if tags are truncated to = 64 bits and extent of decryption is not monitored and curtailed. Complete failure on nonce-reuse. Use is implicit anyway if GCM is adopted. Not recommended for separate standardization.
CCM: A nonce-based AEAD scheme that combines CTR mode encryption and the raw CBC-MAC. Inherently serial, limiting speed in some contexts. Provably secure, with good bounds, assuming the underlying blockcipher is a good PRP. Ungainly construction that demonstrably does the job. Simpler to implement than GCM. Can be used as a nonce-based MAC. Widely standardized and used.
GCM: A nonce-based AEAD scheme that combines CTR mode encryption and a GF(2128)-based universal hash function. Good efficiency characteristics for some implementation environments. Good provably-secure results assuming minimal tag truncation. Attacks and poor provable-security bounds in the presence of substantial tag truncation. Can be used as a nonce-based MAC, which is then called GMAC. Questionable choice to allow nonces other than 96-bits. Recommend restricting nonces to 96-bits and tags to at least 96 bits. Widely standardized and used.
If there is space between the letters of the font, you need to use quote.
font-family:"Calibri (Body)";
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
With Angular 1.3+ you can no longer use global controller declaration on the global scope (Without explicit registration). You would need to register the controller using module.controller
syntax.
Example:-
angular.module('app', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
or
function ContactController($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);
It is a breaking change but it can be turned off to use globals by using allowGlobals
.
Example:-
angular.module('app')
.config(['$controllerProvider', function($controllerProvider) {
$controllerProvider.allowGlobals();
}]);
Here is the comment from Angular source:-
- check if a controller with given name is registered via
$controllerProvider
- check if evaluating the string on the current scope returns a constructor
- if $controllerProvider#allowGlobals, check
window[constructor]
on the globalwindow
object (not recommended)
.....
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
Some additional checks:-
Do Make sure to put the appname in ng-app
directive on your angular root element (eg:- html
) as well. Example:- ng-app="myApp"
If everything is fine and you are still getting the issue do remember to make sure you have the right file included in the scripts.
You have not defined the same module twice in different places which results in any entities defined previously on the same module to be cleared out, Example angular.module('app',[]).controller(..
and again in another place angular.module('app',[]).service(..
(with both the scripts included of course) can cause the previously registered controller on the module app
to be cleared out with the second recreation of module.
For en-US ( American English ) strings this should suffice:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )
Be aware that if you support UTF-8 and characters like chinese/russian and all, this will replace them as well, so you really have to specify what you want.
I took the Ned Rockson's version and adjusted it to allow upwards scrolls as well.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop === 0);
var targetY = 0;
do {
if (target === scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
Math.abs(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var isUp = targetY < scrollContainer.scrollTop;
var stepFunc = function() {
if (isUp) {
scrollContainer.scrollTop = Math.max(targetY, scrollContainer.scrollTop - pixelsPerStep);
if (scrollContainer.scrollTop <= targetY) {
return;
}
} else {
scrollContainer.scrollTop = Math.min(targetY, scrollContainer.scrollTop + pixelsPerStep);
if (scrollContainer.scrollTop >= targetY) {
return;
}
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
};
I had this exact same problem. I fixed it by adding the following line to my FindOpenCV.cmake
file. Put it anywhere at the top before the rest of the code.
set (OpenCV_DIR /home/cmake/opencv/compiled) #change the path to match your complied directory of opencv
Basically you are telling FindOpenCV.cmake
where to find opencv files assuming the other compilation can find the FindOpenCV.cmake
You could also:
handlers = app.logger.handlers
# detach console handler
app.logger.handlers = []
# attach
app.logger.handlers = handlers
You can use NSpredicate to remove items from your mutable array. This requires no for loops.
For example if you have an NSMutableArray of names, you can create a predicate like this one:
NSPredicate *caseInsensitiveBNames =
[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
The following line will leave you with an array that contains only names starting with b.
[namesArray filterUsingPredicate:caseInsensitiveBNames];
If you have trouble creating the predicates you need, use this apple developer link.
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
This function is using yield:
function a($items) {
foreach ($items as $item) {
yield $item + 1;
}
}
It is almost the same as this one without:
function b($items) {
$result = [];
foreach ($items as $item) {
$result[] = $item + 1;
}
return $result;
}
The only one difference is that a()
returns a generator and b()
just a simple array. You can iterate on both.
Also, the first one does not allocate a full array and is therefore less memory-demanding.
Just drop them:
nms.dropna(thresh=2)
this will drop all rows where there are at least two non-NaN
.
Then you could then drop where name is NaN
:
In [87]:
nms
Out[87]:
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN NaN
[5 rows x 3 columns]
In [89]:
nms = nms.dropna(thresh=2)
In [90]:
nms[nms.name.notnull()]
Out[90]:
movie name rating
0 thg John 3
3 mol Graham NaN
[2 rows x 3 columns]
EDIT
Actually looking at what you originally want you can do just this without the dropna
call:
nms[nms.name.notnull()]
UPDATE
Looking at this question 3 years later, there is a mistake, firstly thresh
arg looks for at least n
non-NaN
values so in fact the output should be:
In [4]:
nms.dropna(thresh=2)
Out[4]:
movie name rating
0 thg John 3.0
1 thg NaN 4.0
3 mol Graham NaN
It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.
You could try something like this:
#!/bin/bash
all_but()
{
target="$(git rev-parse $1)"
echo "$target --not"
git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
while read entry
do
eval "$entry"
test "$ref" != "$target" && echo "$ref"
done
}
git log $(all_but $1)
Or, borrowing from the recipe in the Git User's Manual:
#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
You can use : org.springframework.util.StringUtils
;
String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);
In addition to what people wrote years ago:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
Then your version of mingw does not default to c99. Add this compiler flag: -std=c99
.
ctrl + F12 (cmd + F12 on macOS) will show all members of the current class in a popup window and let you pick up one. It works exactly like the ctrl + o shortcut in eclipse, much faster than ctrl + alt + shift + n
$('elements-to-match').click(function(){
alert("The id is "+ this.id );
});
no need to wrap it in a jquery object
You can assign an id to the specific link and add CSS. See the steps below:
1.Add an id of your choice (must be a unique name; can only start with text, not a number):
<a href="/abc/xyz" id="smallLinkButton">def</a>
Then add the necessary CSS as follows:
#smallLinkButton:hover,active,visited{
text-decoration: none;
}
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
If you can find the DB files... "cp DBFiles backup/"
Almost for sure not advisable in most cases, but it's simple as all getup.
this can be done by extending org.springframework.cache.interceptor.CacheInterceptor , and override "doPut" method - org.springframework.cache.interceptor.AbstractCacheInvoker your override logic should use the cache provider put method that knows to set TTL for cache entry (in my case I use HazelcastCacheManager)
@Autowired
@Qualifier(value = "cacheManager")
private CacheManager hazelcastCacheManager;
@Override
protected void doPut(Cache cache, Object key, Object result) {
//super.doPut(cache, key, result);
HazelcastCacheManager hazelcastCacheManager = (HazelcastCacheManager) this.hazelcastCacheManager;
HazelcastInstance hazelcastInstance = hazelcastCacheManager.getHazelcastInstance();
IMap<Object, Object> map = hazelcastInstance.getMap("CacheName");
//set time to leave 18000 secondes
map.put(key, result, 18000, TimeUnit.SECONDS);
}
on your cache configuration you need to add those 2 bean methods , creating your custom interceptor instance .
@Bean
public CacheOperationSource cacheOperationSource() {
return new AnnotationCacheOperationSource();
}
@Primary
@Bean
public CacheInterceptor cacheInterceptor() {
CacheInterceptor interceptor = new MyCustomCacheInterceptor();
interceptor.setCacheOperationSources(cacheOperationSource());
return interceptor;
}
This solution is good when you want to set the TTL on the entry level , and not globally on cache level
Use usort:
usort($array, function($a1, $a2) {
$v1 = strtotime($a1['date']);
$v2 = strtotime($a2['date']);
return $v1 - $v2; // $v2 - $v1 to reverse direction
});
Using System.Web.HttpContext.Current.User.Identity.Name
should work.
Please check the IIS Site settings on the server that is hosting your site by doing the following:
Go to IIS ? Sites ? Your Site ? Authentication
Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.
Now System.Web.HttpContext.Current.User.Identity.Name
should return something like this:
domain\username
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
PHP/AJAX/MySQL will not be enough for creating the live video streaming application There is a similar thread here. It primarily suggests using Flex or Silverlight.
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
Ran into a similar issue the solution for me was to run fuser -k 'filename.db'
on the file that had a lock associated with it.
Hope this helps!
Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName
Will result in
System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Can you not use AcceptButton
in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.
Try adding the property line-height: 22px;
to the code.
Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR
)?
Update: from MSDN:
The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.
def count_letter(word, char):
count = 0
for char in word:
if char == word:
count += 1
return count #Your return is inside your for loop
r = count_word("banana", "a")
print r
3
Use stored procedures.
And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".
jQuery('#masterdiv div').html('');
use ntpath.split()
I've updated the Microsoft.Net.Compilers to version 2.0 or higher
Use position:fixed
on the video, set it to 100% width/height, and put a negative z-index
on it so it appears behind everything.
If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.
HTML
<video id="video_background" src="video.mp4" autoplay>
(Add webm and ogg sources to support more browsers)
CSS
#video_background {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1000;
}
It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.
Use Pythons library Clipboard
Its simply used like this:
import clipboard
clipboard.copy("this text is now in the clipboard")
print clipboard.paste()
You can use this code:
android:textSize="32dp"
it solves your problem but you must know that you should respect user decisions. by this, changing text size from device settings will not change this value. so that's why you need to use sp instead of dp. So my suggestion is to review your app with different system font sizes(small,normal,big,...)
To set value
$('#searchField').val('your_value');
to retrieve value
$('#searchField').val();
Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.
forward the request to another server
server{
server_name mydomain.com sub.mydomain.com;
location /{
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_pass_request_headers on;
}
location /static/{
alias /my/static/files/path;
}
}
Server the request
With this configuration, when the request url is
mydomain.com/static/myjs.js
it returns themyjs.js
file in/my/static/files/path
folder. When you configure nginx to serve static files, it handles the request itself.
forward the request to another server
When the request url is
mydomain.com/dothis
nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.
When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.
If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
Another way is to select a column with the columns
array:
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
Comparing an object with a class using instanceOf
or ... is already answered.
If you have two objects and you want to compare their types with each other, you can use:
if (obj1.getClass() == obj2.getClass()) {
// Both have the same type
}
Probably this kind of situations should only happen at development time, so this might work:
- (id)myMethodWithVar:(id)var {
NSAssert(NO, @"You most override myMethodWithVar:");
return nil;
}
With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter
to java.io.FileFilter
in one line.
javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);
I suspect you've got the same problem at least twice.
Here:
namespace TimeTest
{
class TimeTest
{
}
... you're declaring a type with the same name as the namespace it's in. Don't do that.
Now you apparently have the same problem with Time2
. I suspect if you add:
using Time2;
to your list of using
directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)
(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)
Use ViewCompat.setBackground(view, background);
The JRE/JDK/Java 8 jurisdiction files can be found here:
Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8 Download
Like James said above:
Install the files in ${java.home}/jre/lib/security/
.
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
import re
if re.search('(?i)Mandy Pande:', line):
...
You might be able to use IN, if you don't actually need wildcards.
SELECT * from table WHERE column IN ('AAA', 'BBB', 'CCC')
Suppose I have this line of scripts in my "package.json"
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"export_advertisements": "node export.js advertisements",
"export_homedata": "node export.js homedata",
"export_customdata": "node export.js customdata",
"export_rooms": "node export.js rooms"
},
Now to run the script "export_advertisements", I will simply go to the terminal and type
npm run export_advertisements
You are most welcome
After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.
We can control it with network.http.response.timeout
parameter.
network.http.response.timeout
parameter will be displayed.network.http.response.timeout
parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.Say you have a table and need to rename "colb" to "col_b":
First you rename the old table:
ALTER TABLE orig_table_name RENAME TO tmp_table_name;
Then create the new table, based on the old table but with the updated column name:
CREATE TABLE orig_table_name (
col_a INT
, col_b INT
);
Then copy the contents across from the original table.
INSERT INTO orig_table_name(col_a, col_b)
SELECT col_a, colb
FROM tmp_table_name;
Lastly, drop the old table.
DROP TABLE tmp_table_name;
Wrapping all this in a BEGIN TRANSACTION;
and COMMIT;
is also probably a good idea.
you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6
sub Macro1
' now you call the function this way
dim o1 as integer, o2 as integer
AddSubtract 5, 6, o1, o2
msgbox o2
msgbox o1
end sub
function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
sum = a + b
dif = b - 1
end function
If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):
shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.
While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.
The findDuplicates
function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.
let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
_x000D_
Another reason of this problem may be a missing library.
Go to Properties -> Android and check that you add the libraries correctly
angular.module('testApp',[]).controller('testCTRL',function($scope)_x000D_
_x000D_
{_x000D_
_x000D_
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";_x000D_
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding."; _x000D_
});
_x000D_
div input{_x000D_
width:600px; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<head>Diff b/w model and bind</head>_x000D_
<body data-ng-app="testApp">_x000D_
<div data-ng-controller="testCTRL">_x000D_
Model-Data : <input type="text" data-ng-model="testingModel">_x000D_
<p>{{testingModel}}</p>_x000D_
<input type="text" data-ng-bind="testingBind">_x000D_
<p ng-bind="testingBind"></p>_x000D_
</div>_x000D_
</body>
_x000D_
For SQLLite you will need to concat the strings
select * from list1 l, list2 ll
WHERE l.name like "%"||ll.alias||"%";
Remove nodemon because it's a dev dependency and use node instead of it.
"scripts": {
"start": "node server.js"
},
This worked for me.
pip install -U websocket
I just use this to fix my problem
Ignore is exactly what the name implies.
It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.
It works with both input and output buffers.
Essentially, for std::cin
statements you use ignore before you do a getline
call, because when a user inputs something with std::cin
, they hit enter and a '\n'
char gets into the cin
buffer. Then if you use getline
, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n')
and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)
Sometimes you need to get HTTP headers but at the same time you don't want return those headers.**
This skeleton takes care of cookies and HTTP redirects using recursion. The main idea here is to avoid return HTTP headers to the client code.
You can build a very strong curl class over it. Add POST functionality, etc.
<?php
class curl {
static private $cookie_file = '';
static private $user_agent = '';
static private $max_redirects = 10;
static private $followlocation_allowed = true;
function __construct()
{
// set a file to store cookies
self::$cookie_file = 'cookies.txt';
// set some general User Agent
self::$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
if ( ! file_exists(self::$cookie_file) || ! is_writable(self::$cookie_file))
{
throw new Exception('Cookie file missing or not writable.');
}
// check for PHP settings that unfits
// correct functioning of CURLOPT_FOLLOWLOCATION
if (ini_get('open_basedir') != '' || ini_get('safe_mode') == 'On')
{
self::$followlocation_allowed = false;
}
}
/**
* Main method for GET requests
* @param string $url URI to get
* @return string request's body
*/
static public function get($url)
{
$process = curl_init($url);
self::_set_basic_options($process);
// this function is in charge of output request's body
// so DO NOT include HTTP headers
curl_setopt($process, CURLOPT_HEADER, 0);
if (self::$followlocation_allowed)
{
// if PHP settings allow it use AUTOMATIC REDIRECTION
curl_setopt($process, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($process, CURLOPT_MAXREDIRS, self::$max_redirects);
}
else
{
curl_setopt($process, CURLOPT_FOLLOWLOCATION, false);
}
$return = curl_exec($process);
if ($return === false)
{
throw new Exception('Curl error: ' . curl_error($process));
}
// test for redirection HTTP codes
$code = curl_getinfo($process, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302)
{
curl_close($process);
try
{
// go to extract new Location URI
$location = self::_parse_redirection_header($url);
}
catch (Exception $e)
{
throw $e;
}
// IMPORTANT return
return self::get($location);
}
curl_close($process);
return $return;
}
static function _set_basic_options($process)
{
curl_setopt($process, CURLOPT_USERAGENT, self::$user_agent);
curl_setopt($process, CURLOPT_COOKIEFILE, self::$cookie_file);
curl_setopt($process, CURLOPT_COOKIEJAR, self::$cookie_file);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($process, CURLOPT_VERBOSE, 1);
// curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
}
static function _parse_redirection_header($url)
{
$process = curl_init($url);
self::_set_basic_options($process);
// NOW we need to parse HTTP headers
curl_setopt($process, CURLOPT_HEADER, 1);
$return = curl_exec($process);
if ($return === false)
{
throw new Exception('Curl error: ' . curl_error($process));
}
curl_close($process);
if ( ! preg_match('#Location: (.*)#', $return, $location))
{
throw new Exception('No Location found');
}
if (self::$max_redirects-- <= 0)
{
throw new Exception('Max redirections reached trying to get: ' . $url);
}
return trim($location[1]);
}
}
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
Supposing data is a char*. Working example using std::hex:
for(int i=0; i<data_length; ++i)
std::cout << std::hex << (int)data[i];
Or if you want to keep it all in a string:
std::stringstream ss;
for(int i=0; i<data_length; ++i)
ss << std::hex << (int)data[i];
std::string mystr = ss.str();
If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.
In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.
Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'")
the way you wanted.
There are jQuery plugins to that effect, like json2xml.
Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
I can see the following approaches:
a) Use 2 different maps. You can wrap them in a class as you suggest, but even that might be an overkill. Just use the maps directly: key1Map.getValue(k1), key2Map.getValue(k2)
b) You can create a type-aware key class, and use that (untested).
public class Key {
public static enum KeyType { KEY_1, KEY_2 }
public final Object k;
public final KeyType t;
public Key(Object k, KeyType t) {
this.k = k;
this.t= t;
}
public boolean equals(Object obj) {
KeyType kt = (KeyType)obj;
return k.equals(kt.k) && t == kt.t;
}
public int hashCode() {
return k.hashCode() ^ t.hashCode();
}
}
By the way, in a lot of common cases the space of key1
and the space of key2
do not intersect. In that case, you don't actually need to do anything special. Just define a map that has entries key1=>v
as well as key2=>v
please use this
var uri = "ws://localhost:5000/ws";
var socket = new WebSocket(uri);
socket.onclose = function (e){
console.log(connection closed);
};
window.addEventListener("unload", function () {
if(socket.readyState == WebSocket.OPEN)
socket.close();
});
Close browser doesn't trigger websocket close event. You must call socket.close() manually.
In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.
Also read Protect from sql injection it will guide how you can protect your database.
Hope it help you to understand also any question comment me.
If you declare it like
int x;
in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).
The correct way to approach this is to have the header file say
extern int x; /* declared in foo.c */
and then in foo.c you can say
int x; /* exported in foo.h */
THen you can include your header file in as many places as you like.
.section {
display: flex;
}
.element-left {
width: 94%;
}
.element-right {
flex-grow: 1;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
or
.section {
display: flex;
flex-wrap: wrap;
}
.element-left {
flex: 2;
}
.element-right {
width: 100px;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
Try granting permission to the NETWORK SERVICE user.
The data in COL1 is in dd-mon-yy
No it's not. A DATE
column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.
If COL1 is really a DATE
column using to_date()
on it is useless because to_date()
converts a string to a DATE.
You only need to_char(), nothing else:
SELECT TO_CHAR(col1, 'mm/dd/yyyy')
FROM TABLE1
What happens in your case is that calling to_date()
converts the DATE
into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.
Edit
So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.
The best (and to be honest: only sensible) solution is to convert that column to a DATE
. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.
But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR
instead of YY
:
SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1
should do the trick. Note that I also changed mon
to mm
as your example is 27-11-89
which has a number for the month, not an "word" (like NOV)
For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215
(Header CSS:)
<style>
a {
color: #ccc; /* original colour state*/
}
a:active {
color: #F66;
}
a[tabindex]:focus {
color: #F66;
outline: none;
}
</style>
(Body HTML:)
<a href="javascript:;" style="font-size:36px; text-decoration:none;" tabindex="1">click me ♥</a>
There are two ways to group multiple SVG shapes and position the group:
The first to use <g>
with transform
attribute as Aaron wrote. But you can't just use a x
attribute on the <g>
element.
The other way is to use nested <svg>
element.
<svg id="parent">
<svg id="group1" x="10">
<!-- some shapes -->
</svg>
</svg>
In this way, the #group1 svg is nested in #parent, and the x=10
is relative to the parent svg. However, you can't use transform
attribute on <svg>
element, which is quite the contrary of <g>
element.
As a workaround, you could use the timestamp (old and new) for checking though, that one is not updated when there are no changes to the row. (Possibly that is the source for confusion? Because that one is also called 'on update' but is not executed when no change occurs) Changes within one second will then not execute that part of the trigger, but in some cases that could be fine (like when you have an application that rejects fast changes anyway.)
For example, rather than
IF NEW.a <> OLD.a or NEW.b <> OLD.b /* etc, all the way to NEW.z <> OLD.z */
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
you could use
IF NEW.ts <> OLD.ts
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
Then you don't have to change your trigger every time you update the scheme (the issue you mentioned in the question.)
EDIT: Added full example
create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);
INSERT INTO foo (a,b) VALUES(1,1);
INSERT INTO foo (a,b) VALUES(2,2);
INSERT INTO foo (a,b) VALUES(3,3);
DELIMITER ///
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
BEGIN
IF NEW.ts <> OLD.ts THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b);
END IF;
END;
///
DELIMITER ;
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- UPDATE without change
UPDATE foo SET b = 3 WHERE a = 3;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
-- the timestamo didnt change
select * from foo WHERE a = 3;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
1 rows in set (0.00 sec)
-- the trigger didn't run
select * from bar;
Empty set (0.00 sec)
-- UPDATE with change
UPDATE foo SET b = 4 WHERE a=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
-- the timestamp changed
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- and the trigger ran
select * from bar;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
1 row in set (0.00 sec)
It is working because of mysql's behavior on handling timestamps. The time stamp is only updated if a change occured in the updates.
Documentation is here:
https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
desc foo;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+-------------------+-----------------------------+
| a | int(11) | YES | | NULL | |
| b | int(11) | YES | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
Initializations with (...)
in the class body is not allowed. Use {..}
or = ...
. Unfortunately since the respective constructor is explicit
and vector
has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
Implements is used for Interfaces and extends is used to extend a class.
To make it more clearer in easier terms,an interface is like it sound - an interface - a model, that you need to apply,follow, along with your ideas to it.
Extend is used for classes,here,you are extending something that already exists by adding more functionality to it.
A few more notes:
an interface can extend another interface.
And when you need to choose between implementing an interface or extending a class for a particular scenario, go for implementing an interface. Because a class can implement multiple interfaces but extend only one class.
.Net4.5 does not have a 2GB limitation for objects any more. Add this lines to App.config
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>
and it will be possible to create very large objects without getting OutOfMemoryException
Please note it will work only on x64 OS's!
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself).
For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow:
In the last two I talk about a few things you can try:
You can get a commercial renderer (PDFViewForNet, PDFRasterizer.NET, ABCPDF, ActivePDF, XpdfRasterizer and others in the other answers...).
Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails.
In addition to Omar Shahine's code snippet, there is a CodeProject article that shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF).
You could have a look at the source code for SumatraPDF, an OpenSource PDF viewer for windows.
There is also Poppler, a rendering engine that uses Xpdf as a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL.
You may want to consider using GhostScript as an interpreter because rendering pages is a fairly simple process.
The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process).
It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net.
I did a small project that you will find on the Developer Express forums as an attachment.
Be careful of the license requirements for GhostScript through.
If you can't leave with that then commercial software is probably your only choice.
You can simply use
int numberOfLetters = yourWord.Length;
or to be cool and trendy, use LINQ like this :
int numberOfLetters = yourWord.ToCharArray().Count();
and if you hate both Properties and LINQ, you can go old school with a loop :
int numberOfLetters = 0;
foreach (char letter in yourWord)
{
numberOfLetters++;
}
try:
doSomething()
except:
pass
or
try:
doSomething()
except Exception:
pass
The difference is that the first one will also catch KeyboardInterrupt
, SystemExit
and stuff like that, which are derived directly from exceptions.BaseException
, not exceptions.Exception
.
See documentation for details:
The Location
property has type Point
which is a struct.
Instead of trying to modify the existing Point
, try assigning a new Point
object:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y
);
The Chrome setting you refer to is to disable the same origin policy.
This was covered in this thread also: Disable firefox same origin policy
about:config -> security.fileuri.strict_origin_policy -> false