async Task<int> LongTask1() {
...
return 0;
}
async Task<int> LongTask2() {
...
return 1;
}
...
{
Task<int> t1 = LongTask1();
Task<int> t2 = LongTask2();
await Task.WhenAll(t1,t2);
//now we have t1.Result and t2.Result
}
try this solution and it is working fine for me
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js
</IfModule>
## EXPIRES CACHING ##
When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.
You can use following:
$ java -d64 -Xms512m -Xmx4g HelloWorld
where,
You can tune in -Xms and -Xmx as per you requirements (YMMV)
A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html
If you don't have MySQL installed on your host, you have to execute it in the container (https://docs.docker.com/engine/reference/commandline/exec/#/examples gives explanation about docker run vs docker exec).
Considering your container is running, you might use
docker exec yourcontainername mysql -u root -p
to access to the client.
Also, if you are using Docker Compose, and you've declared a mysql db service named database, you can use :
docker-compose exec database mysql -u root -p
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):
@echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html
REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set ss=%%o
)
)
REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss%
I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:
setlocal
@echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err
:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : Start === >> %ERRLOG%
:: Perform some long running action and log errors to ERRLOG.
:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : End === >> %ERRLOG%
As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.
Just to suggest another way without using if statements, you can use the get()
method for DataFrame
s. For performing the sum based on the question:
df['sum'] = df.get('A', df['B']) + df['C']
The DataFrame
get method has similar behavior as python dictionaries.
I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:
npm install @angular/fire firebase --save
In my app/app.module.ts:
...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule
],
providers: [
{ provide: SETTINGS, useValue: {} }
],
bootstrap: [AppComponent]
})
Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)
In my app/services/myService.ts I imported as:
import { AngularFirestore } from "@angular/fire/firestore";
For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!
I find that I run into Net::HTTP and Net::FTP problems like this periodically, and when I do, surrounding the call with a timeout() makes all of those issues vanish. So where this will occasionally hang for 3 minutes or so and then raise an EOFError:
res = Net::HTTP.post_form(uri, args)
This always fixes it for me:
res = timeout(120) { Net::HTTP.post_form(uri, args) }
Just going to add a simple example to what everyone has explained,
json.load()
json.load
can deserialize a file itself i.e. it accepts a file
object, for example,
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
will output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I use json.loads
to open a file instead,
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
I would get this error:
TypeError: expected string or buffer
json.loads()
json.loads()
deserialize string.
So in order to use json.loads
I will have to pass the content of the file using read()
function, for example,
using content.read()
with json.loads()
return content of the file,
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
Output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
That's because type of content.read()
is string, i.e. <type 'str'>
If I use json.load()
with content.read()
, I will get error,
with open("json_data.json", "r") as content:
print(json.load(content.read()))
Gives,
AttributeError: 'str' object has no attribute 'read'
So, now you know json.load
deserialze file and json.loads
deserialize a string.
Another example,
sys.stdin
return file
object, so if i do print(json.load(sys.stdin))
, I will get actual json data,
cat json_data.json | ./test.py
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I want to use json.loads()
, I would do print(json.loads(sys.stdin.read()))
instead.
I was testing a function that had multiple UPDATE
statements within IF-ELSE
blocks.
I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE
statements each time before running the function again.
I noticed that the issue would happen just after those UPDATE
statements;
I added a COMMIT;
after the UPDATE
statement I used to reset the tables and that solved the problem.
So, caution, the problem was not the function itself...
It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.
And if I miss-read the question then I humbly accept the votes down. (Still good to know though)
Please consider the following code:
#some_div_or_body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
There are some alternatives that can be used with a little bit peace of mind by using jQuery:
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
I hope this helps!
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
while not condition1 or not condition2 or val == -1:
But there was nothing wrong with your original of using an if inside of a while True.
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.
You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n
indicating one line.
So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n
, perform your operation on the line and proceed to read the next line into the buffer.
Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...
EDIT
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
line = []
while True:
for c in ser.read():
line.append(c)
if c == '\n':
print("Line: " + ''.join(line))
line = []
break
ser.close()
The following eight pseudo-elements are made available by WebKit for customizing a date input’s textbox:
::-webkit-datetime-edit
::-webkit-datetime-edit-fields-wrapper
::-webkit-datetime-edit-text
::-webkit-datetime-edit-month-field
::-webkit-datetime-edit-day-field
::-webkit-datetime-edit-year-field
::-webkit-inner-spin-button
::-webkit-calendar-picker-indicator
So if you thought the date input could use more spacing and a ridiculous color scheme you could add the following:
::-webkit-datetime-edit { padding: 1em; }_x000D_
::-webkit-datetime-edit-fields-wrapper { background: silver; }_x000D_
::-webkit-datetime-edit-text { color: red; padding: 0 0.3em; }_x000D_
::-webkit-datetime-edit-month-field { color: blue; }_x000D_
::-webkit-datetime-edit-day-field { color: green; }_x000D_
::-webkit-datetime-edit-year-field { color: purple; }_x000D_
::-webkit-inner-spin-button { display: none; }_x000D_
::-webkit-calendar-picker-indicator { background: orange; }
_x000D_
<input type="date">
_x000D_
Like Snukker said, clients1.google.com is where the search suggestions come from. My guess is that they make a request to force clients1.google.com into your DNS cache before you need it, so you will have less latency on the first "real" request.
Google Chrome already does that for any links on a page, and (I think) when you type an address in the location bar. This seems like a way to get all browsers to do the same thing.
Try using private browsing in Safari or deleting your entire cache/cookies.
I've had some similar issues using chrome when the browser thought it had the website in its cache but actually had not.
The part of the http request that makes the server respond a 304 is the etag. Seems like Safari is sending the right etag without having the corresponding cache.
plt.cla() means clear current axis
plt.clf() means clear current figure
also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)
Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?
To clarify an already posted solution due to questions in the comments
import numpy
array = numpy.array([49, 51, 53, 56])
array = array - 13
will output:
array([36, 38, 40, 43])
You have to switch it!
switch (true) {
case ( (pageid === "listing-page") || (pageid === ("home-page") ):
alert("hello");
break;
case (pageid === "details-page"):
alert("goodbye");
break;
}
To further simplify B T's answer: Use refresh tokens when you don't typically want the user to have to type in credentials again, but still want the power to be able to revoke the permissions (by revoking the refresh token)
You cannot revoke an access token, only a refresh token.
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.
Hai sridhar, I found an answer for your prob
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);
change false to true
or try this
ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);
Updated Solution - using the schema solution that we were debating. This gets you to your answer:
Sample Schema:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code Generated
SportType:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
Sports:
package org.example.sport;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"sport"
})
@XmlRootElement(name = "sports")
public class Sports {
protected List<SportType> sport;
public List<SportType> getSport() {
if (sport == null) {
sport = new ArrayList<SportType>();
}
return this.sport;
}
}
Output class files are produced by running xjc against the schema on the command line
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");
Solution
Angular2 developed on the ground of modern technologies like TypeScript and ES6.
So you can just do let copy = Object.assign({}, myObject)
.
Object assign - nice examples.
For nested objects :
let copy = JSON.parse(JSON.stringify(myObject))
I know this is old but since it's now 2018, I thought I would reply making it better by simplifying the code and enhancing the user experience by making the chevron rotate based on collapsed or not. I'm using FontAwesome however. Here's the CSS:
a[data-toggle="collapse"] .rotate {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
-ms-transition: all 0.2s ease-out;
-o-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}
a[data-toggle="collapse"].collapsed .rotate {
-moz-transform: rotate(0deg);
-ms-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
Here's the HTML for the panel section:
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
Collapsible Group Item #1
<i class="fa fa-chevron-right pull-right rotate"></i>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
I use bootstraps pull-right to pull the chevron all the way to the right of the panel heading which should be full width and responsive. The CSS does all of the animation work and rotates the chevron based on if the panel is collapsed or not. Simple.
Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.
Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.
For one time action, you can use .dump and .read.
Dump the table my_table from old_db.sqlite
c:\sqlite>sqlite3.exe old_db.sqlite
sqlite> .output mytable_dump.sql
sqlite> .dump my_table
sqlite> .quit
Read the dump into the new_db.sqlite assuming the table there does not exist
c:\sqlite>sqlite3.exe new_db.sqlite
sqlite> .read mytable_dump.sql
Now you have cloned your table. To do this for whole database, simply leave out the table name in the .dump command.
Bonus: The databases can have different encodings.
I know this question is already answered but I still don't like any solution on this page. For the people who use JQuery I made a final solution which enables you to give the table row almost the same behaviour as the <a>
tag.
This is my solution:
jQuery You can add this for example to a standard included javascript file
$('body').on('mousedown', 'tr[url]', function(e){
var click = e.which;
var url = $(this).attr('url');
if(url){
if(click == 1){
window.location.href = url;
}
else if(click == 2){
window.open(url, '_blank');
window.focus();
}
return true;
}
});
HTML Now you can use this on any <tr>
element inside your HTML
<tr url="example.com">
<td>value</td>
<td>value</td>
<td>value</td>
<tr>
One of the most straightforward ways of gettings rid of ^Ms with just an emacs command one-liner:
C-x h C-u M-| dos2unix
Analysis:
C-x h: select current buffer
C-u: apply following command as a filter, redirecting its output to replace current buffer
M-| dos2unix: performs `dos2unix` [current buffer]
*nix platforms have the dos2unix
utility out-of-the-box, including Mac (with brew
). Under Windows, it is widely available too (MSYS2, Cygwin, user-contributed, among others).
My 2 cents:
If you are concatenating a significant amount of strings, you should be using the StringBuilder instead. IMO it's cleaner, and significantly faster.
Just want to add a demonstration using loc
to filter not only by rows but also by columns and some merits to the chained operation.
The code below can filter the rows by value.
df_filtered = df.loc[df['column'] == value]
By modifying it a bit you can filter the columns as well.
df_filtered = df.loc[df['column'] == value, ['year', 'column']]
So why do we want a chained method? The answer is that it is simple to read if you have many operations. For example,
res = df\
.loc[df['station']=='USA', ['TEMP', 'RF']]\
.groupby('year')\
.agg(np.nanmean)
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
I got a script which extracts id3 tags encodes the songs newly in a certain format, and then adds them according to the tags to my music library.
300 lines of python. Mostly because lame isn't able to deal with tags in a nice fashion.
Deleting .gradle
as suggested by Suragch wasn't enough for me. Additionally, I had to perform a Build > Clean Project
.
Note that, in order to see .gradle
, you need to switch to the "Project" view in the navigator on the top left:
It seems that your project is written in Python < 3. This is because the file()
builtin function is removed in Python 3. Try using Python 2to3 tool or edit the erroneous file yourself.
EDIT: BTW, the project page clearly mentions that
Gunicorn requires Python 2.x >= 2.5. Python 3.x support is planned.
This also works like a charm
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
Can you try the following?
psexec \\server cmd /c "echo . | powershell script.ps1"
I try all the above, if you did all steps in the above answers, and you not solve the problem, then:
I thing that because of, when I create the "METHOD REQUEST" (see step 2 how to go to this menu) , in "Authorization" I select "AWS_IAM" after testing api, in aws test option, I try it in "postman" then I understand the in "METHOD REQUEST" , in "Authorization", I should select "none"
I change it to none, but I thing the AWS, need to deploy it again, as I explain
<select name="gender" class="form-control" id="gender">
<option value="">Select Gender</option>
<option value="M" @if (old('gender') == "M") {{ 'selected' }} @endif>Male</option>
<option value="F" @if (old('gender') == "F") {{ 'selected' }} @endif>Female</option>
</select>
Here you go this should give you the correct answers every time!
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print ("This equation has one solutions: "), x
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Java references always point to an object. The object has a header that amongst other things identifies the concrete type (so casts can fail with ClassCastException
). For arrays, the start of the object also includes the length, the data then follows immediately after in memory (technically an implementation is free to do what it pleases, but it would be daft to do anything else). So, you can;t have a reference that points somewhere into an array.
In C pointers point anywhere and to anything, and you can point to the middle of an array. But you can't safely cast or find out how long the array is. In D the pointer contains an offset into the memory block and length (or equivalently a pointer to the end, I can't remember what the implementation actually does). This allows D to slice arrays. In C++ you would have two iterators pointing to the start and end, but C++ is a bit odd like that.
So getting back to Java, no you can't. As mentioned, NIO ByteBuffer
allows you to wrap an array and then slice it, but gives an awkward interface. You can of course copy, which is probably very much faster than you would think. You could introduce your own String
-like abstraction that allows you to slice an array (the current Sun implementation of String
has a char[]
reference plus a start offset and length, higher performance implementation just have the char[]
). byte[]
is low level, but any class-based abstraction you put on that is going to make an awful mess of the syntax, until JDK7 (perhaps).
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
JTable source = (JTable)evt.getSource();
int row = source.rowAtPoint( evt.getPoint() );
int column = source.columnAtPoint( evt.getPoint() );
String s=source.getModel().getValueAt(row, column)+"";
JOptionPane.showMessageDialog(null, s);
}
if you want click cell or row in jtable use this way
add this code to your menufests.xml .
this is your activity.
<activity
....
..
android:configChanges="orientation|screenSize"/>
You can do it using clone()
function of jQuery, Accepted answer is ok but i am providing alternative to it, you can use append()
, but it works only if you can change html slightly as below:
$(document).ready(function(){_x000D_
$('#clone_btn').click(function(){_x000D_
$("#car_parent").append($("#car2").clone());_x000D_
});_x000D_
});
_x000D_
.car-well{_x000D_
border:1px solid #ccc;_x000D_
text-align: center;_x000D_
margin: 5px;_x000D_
padding:3px;_x000D_
font-weight:bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="car_parent">_x000D_
<div id="car1" class="car-well">Normal div</div>_x000D_
<div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>_x000D_
<div id="car3" class="car-well">Normal div</div>_x000D_
<div id="car4" class="car-well">Normal div</div>_x000D_
<div id="car5" class="car-well">Normal div</div>_x000D_
</div>_x000D_
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");
Sybase IQ:
describe table_name;
Don't delete it: for just one commit git cherry-pick
is enough.
But if you had several commits on the wrong branch, that is where git rebase --onto
shines:
Suppose you have this:
x--x--x--x <-- master
\
-y--y--m--m <- y branch, with commits which should have been on master
, then you can mark master
and move it where you would want to be:
git checkout master
git branch tmp
git checkout y
git branch -f master
x--x--x--x <-- tmp
\
-y--y--m--m <- y branch, master branch
, reset y branch where it should have been:
git checkout y
git reset --hard HEAD~2 # ~1 in your case,
# or ~n, n = number of commits to cancel
x--x--x--x <-- tmp
\
-y--y--m--m <- master branch
^
|
-- y branch
, and finally move your commits (reapply them, making actually new commits)
git rebase --onto tmp y master
git branch -D tmp
x--x--x--x--m'--m' <-- master
\
-y--y <- y branch
With Vim on Windows, use Ctrl + Q in place of Ctrl + V.
To see a frequency count for column two (for example):
awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr
fileA.txt
z z a
a b c
w d e
fileB.txt
t r e
z d a
a g c
fileC.txt
z r a
v d c
a m c
Result:
3 d
2 r
1 z
1 m
1 g
1 b
If someone is using bootstrap sass note the code is on the _reboot.scss file like this:
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
So if you want to keep the _reboot file I guess feel free to override with plain css instead of trying to look for a variable to change.
Use this commad when first connect to psql
=# psql <databaseName> <usernamePostgresql>
Not sure why this works but dynamic (or wildcard if you prefer) routes are possible in angular 1.2.0-rc.2...
http://code.angularjs.org/1.2.0-rc.2/angular.min.js
http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js
angular.module('yadda', [
'ngRoute'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/:a', {
template: '<div ng-include="templateUrl">Loading...</div>',
controller: 'DynamicController'
}).
controller('DynamicController', function ($scope, $routeParams) {
console.log($routeParams);
$scope.templateUrl = 'partials/' + $routeParams.a;
}).
example.com/foo -> loads "foo" partial
example.com/bar-> loads "bar" partial
No need for any adjustments in the ng-view. The '/:a' case is the only variable I have found that will acheive this.. '/:foo' does not work unless your partials are all foo1, foo2, etc... '/:a' works with any partial name.
All values fire the dynamic controller - so there is no "otherwise" but, I think it is what you're looking for in a dynamic or wildcard routing scenario..
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!
I hope you are using Linux;
pdftotext -layout NAME_OF_PDF.pdf
AMAZING!!
Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..
It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!
Javascript arrays have a length property. Use it like this:
st.itemb.length
add CSS or class to the input element which works in select and text tags like
style="pointer-events: none;background-color:#E9ECEF"
My solution was to insert <packaging>pom</packaging>
between artifactId
and version
<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>server</module>
<module>client</module>
<module>network</module>
</modules>
Here is how I do this: http://jsfiddle.net/Zz7Wq/2/
I use a background instead of after and use my H1 or H2 to cover the background. Not quite your method above but does work well for me.
CSS
.title-box { background: #fff url('images/bar-orange.jpg') repeat-x left; text-align: left; margin-bottom: 20px;} .title-box h1 { color: #000; background-color: #fff; display: inline; padding: 0 50px 0 50px; }
HTML
<div class="title-box"><h1>Title can go here</h1></div>
<div class="title-box"><h1>Title can go here this one is really really long</h1></div>
UPDATE cities c,
city_langs cl
SET c.fakename = cl.name
WHERE c.id = cl.city_id
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
You would need a JavaScript engine (such as Mozilla's Rhino) in order to evaluate the script - exactly as you do for Python, though the latter ships with the standard distribution.
If you have Rhino (or alternative) installed and on your path, then running JS can indeed be as simple as
> rhino filename.js
It's worth noting though that while JavaScript is simply a language in its own right, a lot of particular scripts assume that they'll be executing in a browser-like environment - and so try to access global variables such as location.href
, and create output by appending DOM objects rather than calling print
.
If you've got hold of a script which was written for a web page, you may need to wrap or modify it somewhat to allow it to accept arguments from stdin and write to stdout. (I believe Rhino has a mode to emulate standard browser global vars which helps a lot, though I can't find the docs for this now.)
If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions
.
Or, if you want to do it for every Java application, but only when your Mac OS X account runs them, then use ~/Library/Java/Extensions
instead.
EDIT: If you want to do this only for a particular application, as Thorbjørn asked, then you will need to tell us more about how the application is packaged.
Try to do...
DELIMITER $$
CREATE TRIGGER aumentarsalario
BEFORE INSERT
ON empregados
FOR EACH ROW
BEGIN
if (NEW.SALARIO < 900) THEN
set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
END IF;
END $$
DELIMITER ;
The most important thing to realize is that, using Linq, the query does not get evaluated immediately. It is only run as part of iterating through the resulting IEnumerable<T>
in a foreach
- that's what all the weird delegates are doing.
So, the first example evaluates the query immediately by calling ToList
and putting the query results in a list.
The second example returns an IEnumerable<T>
that contains all the information needed to run the query later on.
In terms of performance, the answer is it depends. If you need the results to be evaluated at once (say, you're mutating the structures you're querying later on, or if you don't want the iteration over the IEnumerable<T>
to take a long time) use a list. Else use an IEnumerable<T>
. The default should be to use the on-demand evaluation in the second example, as that generally uses less memory, unless there is a specific reason to store the results in a list.
If you wish to use canvas only, the best result will be with multiple downsteps. But that's not good enougth yet. For better quality you need pure js implementation. We just released pica - high speed downscaler with variable quality/speed. In short, it resizes 1280*1024px in ~0.1s, and 5000*3000px image in 1s, with highest quality (lanczos filter with 3 lobes). Pica has demo, where you can play with your images, quality levels, and even try it on mobile devices.
Pica does not have unsharp mask yet, but that will be added very soon. That's much more easy than implement high speed convolution filter for resize.
I like Get-Command | Format-List
, or shorter, using aliases for the two and only for powershell.exe
:
gcm powershell | fl
You can find aliases like this:
alias -definition Format-List
Tab completion works with gcm
.
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
You have to define both the schema and the table in two different places.
the context defines the schema
public class BContext : DbContext
{
public BContext(DbContextOptions<BContext> options) : base(options)
{
}
public DbSet<PriorityOverride> PriorityOverrides { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("My.Schema");
builder.ApplyConfiguration(new OverrideConfiguration());
}
}
and for each table
class PriorityOverrideConfiguration : IEntityTypeConfiguration<PriorityOverride>
{
public void Configure(EntityTypeBuilder<PriorityOverride> builder)
{
builder.ToTable("PriorityOverrides");
...
}
}
I had this same problem.
Did:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
Write 'plt.show()' only once, after the last figure.
Worked for me.
It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:
public isEmpty(myVar): boolean {
return (myVar && (Object.keys(myVar).length === 0));
}
Otherwise: if (!myVar) {}, should do the job
Still looking for a solution? I got mine from this link .
All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".
var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));
Yes, you have to add:
You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.
There are at least 6 (!) ways to clone an array:
A.map(function(e){return e;});
There has been a huuuge BENCHMARKS thread, providing following information:
for blink browsers slice()
is the fastest method, concat()
is a bit slower, and while loop
is 2.4x slower.
for other browsers while loop
is the fastest method, since those browsers don't have internal optimizations for slice
and concat
.
This remains true in Jul 2016.
Below are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. They output milliseconds, lower is better.
while loop
n = 1000*1000;
start = + new Date();
a = Array(n);
b = Array(n);
i = a.length;
while(i--) b[i] = a[i];
console.log(new Date() - start);
slice
n = 1000*1000;
start = + new Date();
a = Array(n);
b = a.slice();
console.log(new Date() - start);
Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned.
origAr == clonedArr //returns false
origAr[0] == clonedArr[0] //returns true
Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture
TryParse does not allway work as we would expect There are change request in .net in this area:
Try grepl
on the names of your data.frame
. grepl
matches a regular expression to a target and returns TRUE
if a match is found and FALSE
otherwise. The function is vectorised so you can pass a vector of strings to match and you will get a vector of boolean values returned.
# Data
df <- data.frame( ABC_1 = runif(3),
ABC_2 = runif(3),
XYZ_1 = runif(3),
XYZ_2 = runif(3) )
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0.3792645 0.3614199 0.9793573 0.7139381
#2 0.1313246 0.9746691 0.7276705 0.0126057
#3 0.7282680 0.6518444 0.9531389 0.9673290
# Use grepl
df[ , grepl( "ABC" , names( df ) ) ]
# ABC_1 ABC_2
#1 0.3792645 0.3614199
#2 0.1313246 0.9746691
#3 0.7282680 0.6518444
# grepl returns logical vector like this which is what we use to subset columns
grepl( "ABC" , names( df ) )
#[1] TRUE TRUE FALSE FALSE
To answer the second part, I'd make the subset data.frame and then make a vector that indexes the rows to keep (a logical vector) like this...
set.seed(1)
df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
ABC_2 = sample(0:1,3,repl = TRUE),
XYZ_1 = sample(0:1,3,repl = TRUE),
XYZ_2 = sample(0:1,3,repl = TRUE) )
# We will want to discard the second row because 'all' ABC values are 0:
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0 1 1 0
#2 0 0 1 0
#3 1 1 1 0
df1 <- df[ , grepl( "ABC" , names( df ) ) ]
ind <- apply( df1 , 1 , function(x) any( x > 0 ) )
df1[ ind , ]
# ABC_1 ABC_2
#1 0 1
#3 1 1
public boolean hasLoop(Node start){
TreeSet<Node> set = new TreeSet<Node>();
Node lookingAt = start;
while (lookingAt.peek() != null){
lookingAt = lookingAt.next;
if (set.contains(lookingAt){
return false;
} else {
set.put(lookingAt);
}
return true;
}
// Inside our Node class:
public Node peek(){
return this.next;
}
Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?
I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.
Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be
df <- iris %>%
mutate(Species = recode(Species,
setosa = "SETOSA",
versicolor = "VERSICOLOR",
virginica = "VIRGINICA")
)
The file path "c:\Test\blah"
will have a tab character for the `\T'. You need to use either:
"C:\\Test"
or
r"C:\Test"
here is a demo
first you need to correct your syntax error its
display: table-cell;
not diaplay: table-cell;
.container {
display: table;
border-collapse:collapse
}
.column {
display:table-row;
}
.cell {
display: table-cell;
border: 1px solid red;
width: 120px;
height: 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
There are many approaches and i will suggest to go with ref attachment to input.
<input
id="image"
type="file"
required
ref={ref => this.fileInput = ref}
multiple
onChange={this.onFileChangeHandler}
/>
to clear value after submit.
this.fileInput.value = "";
Note that in Entity Framework 6.1 (currently in beta) will support the IndexAttribute to annotate the index properties which will automatically result in a (unique) index in your Code First Migrations.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting
X-XSS-Protection: 0
The default constructor has no arguments. You need to specify a constructor:
public Friends( String firstName, String age) { ... }
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
import java.util.*;
class Maxmin
{
public static void main(String args[])
{
int[] arr = new int[10];
Scanner in = new Scanner(System.in);
int i, min=0, max=0;
for(i=0; i<=arr.length; i++)
{
System.out.print("Enter any number: ");
arr[i] = in.nextInt();
}
min = arr[0];
for(i=0; i<=9; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
On your device (iPhone/iPad) goto: Settings -> Developer -> Clear Trusted Computers worked for me.
If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.
Change IIS7 Inetpub path
- Open %windir%\system32\inetsrv\config\applicationhost.config and search for
%SystemDrive%\inetpub\wwwroot
- Change the path.
A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
Not sure it will help people but this one worked for me :
So the issue I had was that I was getting the following message:
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "My.Resources.Resources.resources" was correctly embedded or linked into assembly "X" at compile time, or that all the satellite assemblies required are loadable and fully signed"
I was trying to get the resources that were embedded in my project from another class library.
What I did to fix the problem was to set the Access Modifier in the tab Project->Properties->Resources from "Internal" (accessible only within the same class library) to "Public" (accessible from another class library)
Then run and voilà, no more error for me...
The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string:
var folderKey = folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);
Then refresh your AWS console, and you will see the folder
I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.
Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
There's an O(N) solution for very specific cases where:
The following code assumes that both sets are based on the records comparable. A similar method could be based on on a Comparator.
public class SortedSetComparitor <Foo extends Comparable<Foo>>
implements Comparator<SortedSet<Foo>> {
@Override
public int compare( SortedSet<Foo> arg0, SortedSet<Foo> arg1 ) {
Iterator<Foo> otherRecords = arg1.iterator();
for (Foo thisRecord : arg0) {
// Shorter sets sort first.
if (!otherRecords.hasNext()) return 1;
int comparison = thisRecord.compareTo(otherRecords.next());
if (comparison != 0) return comparison;
}
// Shorter sets sort first
if (otherRecords.hasNext()) return -1;
else return 0;
}
}
The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass
and give its value as the class which contains your main method. For me it was DriverClass
in mainpkg
. Change it as per your project.
Having done this navigate to the folder that contains your project's pom.xml
and run this on the command prompt mvn exec:java
. This should call the main method.
you can use pathlib
from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]
The output of the above was this:
'folder2'
If you look deeper into the other uses of size
you can see that you can actually get a vector of the size of each dimension. This link shows you the documentation:
www.mathworks.com/access/helpdesk/help/techdoc/ref/size.html
After getting the size vector, iterate over that vector. Something like this (pardon my syntax since I have not used Matlab since college):
d = size(m);
dims = ndims(m);
for dimNumber = 1:dims
for i = 1:d[dimNumber]
...
Make this into actual Matlab-legal syntax, and I think it would do what you want.
Also, you should be able to do Linear Indexing as described here.
In these two lines:
mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
try instead:
cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
I had the same problem and the variables were being returned empty
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
SQL is not faithful to the relational model in many ways. The result of a SQL query is not a relation because it may have columns with duplicate names, 'anonymous' (unnamed) columns, duplicate rows, nulls, etc. SQL doesn't treat tables as relations because it relies on column ordering etc.
The idea behind NATURAL JOIN
in SQL is to make it easier to be more faithful to the relational model. The result of the NATURAL JOIN
of two tables will have columns de-duplicated by name, hence no anonymous columns. Similarly, UNION CORRESPONDING
and EXCEPT CORRESPONDING
are provided to address SQL's dependence on column ordering in the legacy UNION
syntax.
However, as with all programming techniques it requires discipline to be useful. One requirement for a successful NATURAL JOIN
is consistently named columns, because joins are implied on columns with the same names (it is a shame that the syntax for renaming columns in SQL is verbose but the side effect is to encourage discipline when naming columns in base tables and VIEW
s :)
Note a SQL NATURAL JOIN
is an equi-join**, however this is no bar to usefulness. Consider that if NATURAL JOIN
was the only join type supported in SQL it would still be relationally complete.
While it is indeed true that any NATURAL JOIN
may be written using INNER JOIN
and projection (SELECT
), it is also true that any INNER JOIN
may be written using product (CROSS JOIN
) and restriction (WHERE
); further note that a NATURAL JOIN
between tables with no column names in common will give the same result as CROSS JOIN
. So if you are only interested in results that are relations (and why ever not?!) then NATURAL JOIN
is the only join type you need. Sure, it is true that from a language design perspective shorthands such as INNER JOIN
and CROSS JOIN
have their value, but also consider that almost any SQL query can be written in 10 syntactically different, but semantically equivalent, ways and this is what makes SQL optimizers so very hard to develop.
Here are some example queries (using the usual parts and suppliers database) that are semantically equivalent:
SELECT *
FROM S NATURAL JOIN SP;
-- Must disambiguate and 'project away' duplicate SNO attribute
SELECT S.SNO, SNAME, STATUS, CITY, PNO, QTY
FROM S INNER JOIN SP
USING (SNO);
-- Alternative projection
SELECT S.*, PNO, QTY
FROM S INNER JOIN SP
ON S.SNO = SP.SNO;
-- Same columns, different order == equivalent?!
SELECT SP.*, S.SNAME, S.STATUS, S.CITY
FROM S INNER JOIN SP
ON S.SNO = SP.SNO;
-- 'Old school'
SELECT S.*, PNO, QTY
FROM S, SP
WHERE S.SNO = SP.SNO;
** Relational natural join is not an equijoin, it is a projection of one. – philipxy
See lodash flatten, underscore flatten (shallow true
)
function flatten(arr) {
return arr.reduce((acc, e) => acc.concat(e), []);
}
function flatten(arr) {
return [].concat.apply([], arr);
}
Tested with
test('already flatted', () => {
expect(flatten([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]);
});
test('flats first level', () => {
expect(flatten([1, [2, [3, [4]], 5]])).toEqual([1, 2, [3, [4]], 5]);
});
See lodash flattenDeep, underscore flatten
function flattenDeep(arr) {
return arr.reduce((acc, e) => Array.isArray(e) ? acc.concat(flattenDeep(e)) : acc.concat(e), []);
}
Tested with
test('already flatted', () => {
expect(flattenDeep([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]);
});
test('flats', () => {
expect(flattenDeep([1, [2, [3, [4]], 5]])).toEqual([1, 2, 3, 4, 5]);
});
First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.
Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:
Consider following query.
Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A
You can use lateral in this condition.
Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
Select B.Column1,B.Column2,B.Fk1 from B Limit 1
) x ON X.Fk1 = A.PK
In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.
There are more usages for lateral or cross apply but this is most common one I found.
The problem with most of these solutions is that they do not work correctly when changing the cursor position within the input field.
The onmouseup
event changes the cursor position within the field, which is fired after onfocus
(at least within Chrome and FF). If you unconditionally discard the mouseup
then the user cannot change the cursor position with the mouse.
function selectOnFocus(input) {
input.each(function (index, elem) {
var jelem = $(elem);
var ignoreNextMouseUp = false;
jelem.mousedown(function () {
if (document.activeElement !== elem) {
ignoreNextMouseUp = true;
}
});
jelem.mouseup(function (ev) {
if (ignoreNextMouseUp) {
ev.preventDefault();
ignoreNextMouseUp = false;
}
});
jelem.focus(function () {
jelem.select();
});
});
}
selectOnFocus($("#myInputElement"));
The code will conditionally prevent the mouseup
default behaviour if the field does not currently have focus. It works for these cases:
I have tested this within Chrome 31, FF 26 and IE 11.
var offset = new Date().getTimezoneOffset();
offset
will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files
However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security
That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206
A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
public class UrlPrettyfierFilter implements Filter {
private static final String JSF_VIEW_ROOT_PATH = "/ui";
private static final String JSF_VIEW_SUFFIX = ".xhtml";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
//Only process the paths starting with /ui, so as other requests get unprocessed.
//You can register the filter itself for /ui/* only, too
if (requestURI.startsWith(JSF_VIEW_ROOT_PATH)
&& !requestURI.contains(JSF_VIEW_SUFFIX)) {
request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>
Update :
Audio/Video Updates in Chrome 73
Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
The right approach is
<template>
<div> <!-- The root -->
<p></p>
<p></p>
</div>
</template>
The wrong approach
<template> <!-- No root Element -->
<p></p>
<p></p>
</template>
Multi Root Components
The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.
As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this
anymore and everything is passed with context.
Here is how you can create a simple functional component.
Vue.component('my-component', {
// you must set functional as true
functional: true,
// Props are optional
props: {
// ...
},
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
render: function (createElement, context) {
// ...
}
})
Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.
<template>
<ul>
<NavBarRoutes :routes="persistentNavRoutes"/>
<NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
<NavBarRoutes v-else :routes="loggedOutNavRoutes" />
</ul>
</template>
Now if we take a look at NavBarRoutes template
<template>
<li
v-for="route in routes"
:key="route.name"
>
<router-link :to="route">
{{ route.title }}
</router-link>
</li>
</template>
We cant do some thing like this we will be violating single root component restriction
Solution Make this component functional and use render
{
functional: true,
render(h, { props }) {
return props.routes.map(route =>
<li key={route.name}>
<router-link to={route}>
{route.title}
</router-link>
</li>
)
}
Here you have it you have created a multi root component, Happy coding
Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/
The REST doesn't prevent body inclusion with DELETE request but it is better to use query string as it is most standarized (unless you need the data to be encrypted)
I got it to work with angular 2 by doing following:
let options:any = {}
option.header = new Headers({
'header_name':'value'
});
options.search = new URLSearchParams();
options.search.set("query_string_key", "query_string_value");
this.http.delete("/your/url", options).subscribe(...)
The default value for bool is false
. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.
<?php
header('Content-Type: text/css');
?>
some selector {
background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}
You have to install it explixitly using the python package manager as
Angular.io have quick start tutorial. I copied this tutorial and extended with some simple gulp tasks for bundling everything to dist folder which can be copied to server and work just like that. I tried to optimize everything to work well on Jenkis CI, so node_modules can be cached and don't need to be copied.
Source code with sample app on Github: https://github.com/Anjmao/angular2-production-workflow
Steps to productionNode: While you always can create your own build process, but I highly recommend to use angular-cli, because it have all needed workflows and it works perfectly now. We are already using it in production and don't have any issues with angular-cli at all.
I remote into the computer using Enter-PSsession pcName then I type Get-PSDrive
That will list all drives and space used and remaining. If you need to see all the info formated, pipe it to FL like this: Get-PSdrive | FL *
The reason is that php cannot find the correct path of mysql.sock
.
Please make sure that your mysql is running first.
Then, please confirm that which path is the mysql.sock
located, for example /tmp/mysql.sock
then add this path string to php.ini:
Finally, restart Apache.
Here is how you can handle this:
var scrollStop = function (callback) {_x000D_
if (!callback || typeof callback !== 'function') return;_x000D_
var isScrolling;_x000D_
window.addEventListener('scroll', function (event) {_x000D_
window.clearTimeout(isScrolling);_x000D_
isScrolling = setTimeout(function() {_x000D_
callback();_x000D_
}, 66);_x000D_
}, false);_x000D_
};_x000D_
scrollStop(function () {_x000D_
console.log('Scrolling has stopped.');_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Title</title>_x000D_
</head>_x000D_
<body>_x000D_
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>_x000D_
</body>_x000D_
</html>
_x000D_
Add a new pandas.Series using pandas.DataFrame.append().
If you wish to specify the name (AKA the "index") of the new row, use:
df.append(pandas.Series(name='NameOfNewRow'))
If you don't wish to name the new row, use:
df.append(pandas.Series(), ignore_index=True)
where df
is your pandas.DataFrame.
To avoid this problem you can use native method Bitmap.recycle()
before null
-ing Bitmap
object (or setting another value). Example:
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
}
And next you can change myBitmap
w/o calling System.gc()
like:
setMyBitmap(null);
setMyBitmap(anotherBitmap);
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency. Security is another, a process can't change your string and inject code into the string
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):
ILIKE, which is a case insensitive LIKE match:
select * from people where name ilike 'JOHN'
Matches:
And if you want to get really mad you can use regular expressions:
select * from people where name ~ 'John.*'
Matches:
I real all the solution but there is not a standard solution...
JUST REMOVE NODEJS AND INSTALL THE LATEST VERSION OF NODEJS
instead of many bad shortcut solutions.
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
And you can use %stylesheets% (assetic feature) tag:
{% stylesheets
"@MainBundle/Resources/public/colorbox/colorbox.css"
"%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}
You can write path to css as parameter (%parameter_name%).
More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html
I find this easier.
sort -u input_filename > output_filename
-u
stands for unique.
It was very useful for me i have used in the following way to add user in active directory:
:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "
cls
:while1
if %x% leq %lent% (
dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
echo User %Uname%%x% with DC %DcName% is created
set /a "x = x + 1"
goto :while1
)
endlocal
No need to do this:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
You can directly do this:
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['value'] . "'>" . $row['value'] . "</option>";
}
If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.
If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.
If you a running Jupyter/Ipython notebook and having problems using;
ax = df1.plot()
df2.plot(ax=ax)
Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.
ListView has the Item click listener callback. You should set the onItemClickListener
in the ListView
. Callback contains AdapterView
and position
as parameter. Which can give you the ListEntry
.
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = entry.getMessage();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
You can try this code :
int columnIndex = dataGridView.CurrentCell.ColumnIndex;
int rowIndex = dataGridView.CurrentCell.RowIndex;
You could use custom css classes (className) instead of the css tag too. No need for an external package.
import React, { useState, useEffect } from 'react';
import { css } from '@emotion/css'
const Hello = (props) => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
// For load
setTimeout(function () {
setLoaded(true);
}, 50); // Browser needs some time to change to unload state/style
// For unload
return () => {
setLoaded(false);
};
}, [props.someTrigger]); // Set your trigger
return (
<div
css={[
css`
opacity: 0;
transition: opacity 0s;
`,
loaded &&
css`
transition: opacity 2s;
opacity: 1;
`,
]}
>
hello
</div>
);
};
If you're working in a large multi-module project, with several different application.properties
files, then try adding your value to the parent project's property file.
If you are unsure which is your parent project, check your project's pom.xml
file, for a <parent>
tag.
This solved the issue for me.
You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.
There is an example function that do it:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.
"filename=[name of file]" specifies name of file which will be downloaded.
For more information please see this stackoverflow topic.
I had this problem when trying to change directory, using the character _
. The solution was to use a string to change directories.
C:\> cd "my_new_dir"
If you get this error in PowerShell, it's most likely because you're using Resolve-Path
to resolve a remote path, e.g.
Resolve-Path \\server\share\path
In this case, Resolve-Path
returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:
> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path
The solution is to use the ProviderPath
property on the object returned by Resolve-Path
:
> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
We can't reference the result of an aggregate function (for example MAX()
) in a WHERE
clause of the same SELECT
.
The normative pattern for solving this type of problem is to use an inline view, something like this:
SELECT t.firstName
, t.Lastname
, t.id
FROM mytable t
JOIN ( SELECT MAX(mx.id) AS max_id
FROM mytable mx
) m
ON m.max_id = t.id
This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:
WHERE t.id = (SELECT MAX(id) FROM ... )
Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)
SELECT t.firstName
, t.Lastname
, t.id
FROM mytable t
ORDER BY t.id DESC
LIMIT 1
Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)
This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5
.
Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id
as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.
Using anchor tag and PHP it can be done, Check this answer
JQuery Ajax call for PDF file download
HTML
<a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>
PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
readfile($fullPath);
exit;
}
?>
I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
As said before, @Column(unique = true)
is a shortcut to UniqueConstraint
when it is only a single field.
From the example you gave, there is a huge difference between both.
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;
This code implies that both mask
and group
have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.
On the other hand,
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)
Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.
If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(columnNames = "mask"),
@UniqueConstraint(columnNames = "group")
}
)
This has the same effect as the first code block.
You should create separate component, which will be listening to state changes and updating on every state change:
import store from '../reducers/store';
class Items extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
store.subscribe(() => {
// When state will be updated(in our case, when items will be fetched),
// we will update local component state and force component to rerender
// with new data.
this.setState({
items: store.getState().items;
});
});
}
render() {
return (
<div>
{this.state.items.map((item) => <p> {item.title} </p> )}
</div>
);
}
};
render(<Items />, document.getElementById('app'));
I just found this solution below on the W3 CSS page and it answered my problem.
img {
display: block;
margin-left: auto;
margin-right: auto;
}
sometime you missed some file like I missed my one file rt.java
so better to check yours .........
C:\Program Files\Java\jdk1.8.0_112\jre\lib
I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.
I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with pip install --egg --upgrade scons
)
Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.
Update with Spring Boot 2.2.2.Release.
Full example here, https://www.surasint.com/spring-boot-override-property-example/
Assume that, in your jar file, you have the application.properties which have these two line:
server.servlet.context-path=/test
server.port=8081
Then, in production, you want to override the server.port=8888 but you don't want to override the other properties.
First you create another file, ex override.properties and have online this line:
server.port=8888
Then you can start the jar like this
java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties
Try disclose
: https://github.com/pmq20/disclose
disclose
essentially makes a self-extracting exe out of your Node.js project and Node.js interpreter with the following characteristics,
Try node-compiler
: https://github.com/pmq20/node-compiler
I have made a new project called node-compiler
to compile your Node.js project into one single executable.
It is better than disclose
in that it never runs slowly for the first time, since your source code is compiled together with Node.js interpreter, just like the standard Node.js libraries.
Additionally, it redirect file and directory requests transparently to the memory instead of to the file system at runtime. So that no source code is required to run the compiled product.
How it works: https://speakerdeck.com/pmq20/node-dot-js-compiler-compiling-your-node-dot-js-application-into-a-single-executable
Comparing with Similar Projects,
pkg(https://github.com/zeit/pkg): Pkg hacked fs.* API's dynamically in order to access in-package files, whereas Node.js Compiler leaves them alone and instead works on a deeper level via libsquash. Pkg uses JSON to store in-package files while Node.js Compiler uses the more sophisticated and widely used SquashFS as its data structure.
EncloseJS(http://enclosejs.com/): EncloseJS restricts access to in-package files to only five fs.* API's, whereas Node.js Compiler supports all fs.* API's. EncloseJS is proprietary licensed and charges money when used while Node.js Compiler is MIT-licensed and users are both free to use it and free to modify it.
Nexe(https://github.com/nexe/nexe): Nexe does not support dynamic require because of its use of browserify, whereas Node.js Compiler supports all kinds of require including require.resolve.
asar(https://github.com/electron/asar): Asar uses JSON to store files' information while Node.js Compiler uses SquashFS. Asar keeps the code archive and the executable separate while Node.js Compiler links all JavaScript source code together with the Node.js virtual machine and generates a single executable as the final product.
AppImage(http://appimage.org/): AppImage supports only Linux with a kernel that supports SquashFS, while Node.js Compiler supports all three platforms of Linux, macOS and Windows, meanwhile without any special feature requirements from the kernel.
Suppose you have a Customer Entity mapped to CUSTOMER_INFORMATION table and you want to get list of distinct firstName of customer. You can use below snippet to get the same.
Query distinctFirstName = session.createQuery("select ci.firstName from Customer ci group by ci.firstName");
Object [] firstNamesRows = distinctFirstName.list();
I hope it helps. So here we are using group by instead of using distinct keyword.
Also previously I found it difficult to use distinct keyword when I want to apply it to multiple columns. For example I want of get list of distinct firstName, lastName then group by would simply work. I had difficulty in using distinct in this case.
I`m very happy my problem is solved.
and do this : Look below that line and find the tag. It will have a big ol' select statement in it. Remove the tag and it's contents..
now without changing DB T I can insert to a table which has not PK
thanks all and thank Pharylon
Another approach is to use a Ruby class with a hash containing names and values as described in the following RubyFleebie blog post. This allows you to convert easily between values and constants (especially if you add a class method to lookup the name for a given value).
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
generate sql:
docker exec -t your-db-container pg_dumpall -c -U your-db-user > dump_$(date +%Y-%m-%d_%H_%M_%S).sql
to reduce the size of the sql you can generate a compress:
docker exec -t your-db-container pg_dumpall -c -U your-db-user | gzip > ./dump_$(date +"%Y-%m-%d_%H_%M_%S").gz
cat your_dump.sql | docker exec -i your-db-container psql -U your-db-user -d your-db-name
to restore a compressed sql:
gunzip < your_dump.sql.gz | docker exec -i your-db-container psql -U your-db-user -d your-db-name
PD: this is a compilation of what worked for me, and what I got from here and elsewhere. I am beginning to make contributions, any feedback will be appreciated.
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
A couple other examples of declarative programming:
Declarative programming is nice because it can help simplify your mental model* of code, and because it might eventually be more scalable.
For example, let's say you have a function that does something to each element in an array or list. Traditional code would look like this:
foreach (object item in MyList)
{
DoSomething(item);
}
No big deal there. But what if you use the more-declarative syntax and instead define DoSomething() as an Action? Then you can say it this way:
MyList.ForEach(DoSometing);
This is, of course, more concise. But I'm sure you have more concerns than just saving two lines of code here and there. Performance, for example. The old way, processing had to be done in sequence. What if the .ForEach() method had a way for you to signal that it could handle the processing in parallel, automatically? Now all of a sudden you've made your code multi-threaded in a very safe way and only changed one line of code. And, in fact, there's a an extension for .Net that lets you do just that.
mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks
table.
Documentation here
In the upper right corner of the dialog, mouse over where the button should be, and see rather or not you get some effect (the button hover). Try clicking it and seeing if it closes. If it does close, then you're just missing your image sprites that came with your package download.
# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1
#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763
#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237
#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)
#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)
#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
ALTER FUNCTION [dbo].[StringListTo] (@StringList Nvarchar(max),@Separators char(1),@start int, @index int )
RETURNS nvarchar(max)
AS
BEGIN
declare @out Nvarchar(max)
declare @i int
declare @start_old int
set @start=@start+1
set @i=1
while(@i<=@index)
begin
set @start_old=@start
set @start=CHARINDEX('.',@StringList,@start+1)
if (@start>0)
begin
set @out=Substring(@StringList,@start_old+1,@start-@start_old-1)
end
else
begin
set @out=Substring(@StringList,@start_old+1,len(@StringList)-1)
end
set @i=@i+1
end
RETURN @out
END;
Just adding to all the fine answers, my version with decoration:
from __future__ import print_function
import six
def classrep(rep):
def decorate(cls):
class RepMetaclass(type):
def __repr__(self):
return rep
class Decorated(six.with_metaclass(RepMetaclass, cls)):
pass
return Decorated
return decorate
@classrep("Wahaha!")
class C(object):
pass
print(C)
stdout:
Wahaha!
The down sides:
C
without a super class (no class C:
)C
instances will be instances of some strange derivation, so it's probably a good idea to add a __repr__
for the instances as well.The encryption methods described are symmetric key block ciphers.
Data Encryption Standard (DES) is the predecessor, encrypting data in 64-bit blocks using a 56 bit key. Each block is encrypted in isolation, which is a security vulnerability.
Triple DES extends the key length of DES by applying three DES operations on each block: an encryption with key 0, a decryption with key 1 and an encryption with key 2. These keys may be related.
DES and 3DES are usually encountered when interfacing with legacy commercial products and services.
AES is considered the successor and modern standard. http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
I believe the use of Blowfish is discouraged.
It is highly recommended that you do not attempt to implement your own cryptography and instead use a high-level implementation such as GPG for data at rest or SSL/TLS for data in transit. Here is an excellent and sobering video on encryption vulnerabilities http://rdist.root.org/2009/08/06/google-tech-talk-on-common-crypto-flaws/
I assume you are talking about getElementById()
returning a reference to an element whilst the others return a node list. Just subscript the nodelist for the others, e.g. document.getElementBytag('table')[4]
.
Also, elements
is only a property of a form (HTMLFormElement
), not a table
such as in your example.
Its usually better to whitelist characters you allow, rather than to blacklist characters you don't allow. both from a security standpoint, and from an ease of implementation standpoint.
If you do go down the blacklist route, here is an example, but be warned, the syntax is not simple.
http://groups.google.com/group/regex/browse_thread/thread/0795c1b958561a07
If you want to whitelist all the accent characters, perhaps using unicode ranges would help? Check out this link.
Very easy if you fgrep to do a case-insensitive line compare:
str1="MATCH"
str2="match"
if [[ $(fgrep -ix $str1 <<< $str2) ]]; then
echo "case-insensitive match";
fi
In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:
extension Dictionary {
subscript(i:Int) -> (key:Key,value:Value) {
get {
return self[index(startIndex, offsetBy: i)];
}
}
}
You can select a child like
TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);
bootstrap 3 + jquery 2.0.3:
$('#myModal').on('hide.bs.modal', function () {
$('#myModal').removeData();
})
You can accept the license agreements of the stated SDKs by going to the SDK Manager (Settings > [Search for Android SDK]) then find the packages noted in the error message and find them there. Chances are, you'll find SDKs that are not fully installed and installing them will ask you to accept the license agreement.
Another possible solution:
public String DecToHex(int dec){
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
String hex = "";
while (dec != 0) {
int rem = dec % 16;
hex = hexDigits[rem] + hex;
dec = dec / 16;
}
return hex;
}
Look for "Windows x86", it's the 32 bit version.
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require c++11 or a third party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg
in the future intead.
// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
public:
typedef mkvec<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
my_type& operator<< (const std::vector<T>& inVector) {
this->data_.reserve(this->data_.size() + inVector.size());
this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
std::vector<int32_t> vec1;
std::vector<int32_t> vec2;
vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5,8,19,79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1,2,3,5,8,19,79,10,11,12)
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
This could happen due to the change in java version of the project.Say for example if the project is build in java 8 and if we change the java version to 11 then there can be such issue. In intellij idea go to the File->Project Structure then change the Project SDK Version.
Here is an alternate approach using pure CSS. The idea is to include both the images in the HTML markup and have these displayed or hidden accordingly on :hover
HTML
<a>
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_15-128.png" />
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_12-128.png" />
</a>
CSS
a img:last-child {
display: none;
}
a:hover img:last-child {
display: block;
}
a:hover img:first-child {
display: none;
}
jsfiddle: https://jsfiddle.net/m4v1onyL/
Note that the images used are of the same dimensions for proper display. Also, these images file sizes are quite small so loading multiple is not an issue in this case but may be if you are looking to toggle display of large sized images.
You could do the following
declare @role varchar(100) = 'Alpha'
select * from xmltable where convert(varchar(max),xmlfield) like '%<role>'+@role+'</role>%'
Obviously this is a bit of a hack and I wouldn't recommend it for any formal solutions. However I find this technique very useful when doing adhoc queries on XML columns in SQL Server Management Studio for SQL Server 2012.
Lookup pom.xml > project tag > build tag.
I would like solution below.
<artifactId>bird</artifactId>
<name>bird</name>
<build>
...
<finalName>${project.artifactId}</finalName>
OR
<finalName>${project.name}</finalName>
...
</build>
Worked for me. ^^
how to club the 4 query's as a single query
show below query
nsc = nature of case
report is taken on 06th of every month
( monthly report will be counted from 05th previous month to 05th present of present month)
If you need to update user information for a specific user ID "x",
The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:
@Entity
class User{
@PrimaryKey
String userId;
String username;
}
Interface UserDao{
//forUpdate
@Update
void updateUser(User user)
}
Class DbManager{
//AppDatabase gets the static object o roomDatabase.
AppDatabase appDatabase;
UserDao userDao;
public DbManager(Application application ){
appDatabase = AppDatabase.getInstance(application);
//getUserDao is and abstract method of type UserDao declared in AppDatabase //class
userDao = appDatabase.getUserDao();
}
public void updateUser(User user, boolean isUpdate){
new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
}
public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDAO;
private boolean isInsert;
public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
this. userDAO = userDAO;
this.isInsert = isInsert;
}
@Override
protected Void doInBackground(User... users) {
if (isInsert)
userDAO.insertBrand(brandEntities[0]);
else
//for update
userDAO.updateBrand(users[0]);
//try {
// Thread.sleep(1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
return null;
}
}
}
Class UserViewModel{
DbManager dbManager;
public UserViewModel(Application application){
dbmanager = new DbMnager(application);
}
public void updateUser(User user, boolean isUpdate){
dbmanager.updateUser(user,isUpdate);
}
}
Now in your activity or fragment initialise your UserViewModel like this:
UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".
Get an userItem of id 1122 User object
User user = new user(); if(user.getUserId() == 1122){ user.setuserName("zyx"); userViewModel.updateUser(user); }
This is a raw code, hope it helps you.
Happy coding
Taking help from above answer link mentioned in the above answer sets the max value with option
yAxis: { max: 100 },
On similar line min value can be set.So if you want to set min-max value then
yAxis: {
min: 0,
max: 100
},
If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option
$series->yAxis->min=0;
$series->yAxis->max=100;
This is a good tutorial on how to get easy_install
on windows. The short answer: add C:\Python26\Scripts
(or whatever python you have installed) to your PATH.
I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.
You'll want to listen for escape's keyCode
(27) from the React SyntheticKeyBoardEvent
onKeyDown
:
const EscapeListen = React.createClass({
handleKeyDown: function(e) {
if (e.keyCode === 27) {
console.log('You pressed the escape key!')
}
},
render: function() {
return (
<input type='text'
onKeyDown={this.handleKeyDown} />
)
}
})
Brad Colthurst's CodePen posted in the question's comments is helpful for finding key codes for other keys.
PHP has no explicit byte
type, but its string
is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …")
. The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.
From PythonTR - Python Programcilari Dernegi, e-kitap, örnek:
Process p = new Process(); // Create new object
p.StartInfo.UseShellExecute = false; // Do not use shell
p.StartInfo.RedirectStandardOutput = true; // Redirect output
p.StartInfo.FileName = "c:\\python26\\python.exe"; // Path of our Python compiler
p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py"; // Path of the .py to be executed