since your ant file's name is build.xml, you should just type ant without ant build.xml.
that is: > ant
[enter]
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'your-icon.png'
});
You need to specify the executable path of Git in the Git Settings, as mentionned in the per-requesites:
The Git integration plugin is enabled and the location of the Git executable file is correctly specified on the Git page of the Settings dialog box.
As long as you see "a message indicating that the Git execution path is not correct", the rest of the instructions won't work.
Path to Git executable
In this text box, specify the path to the Git executable file.
Type the path manually or click the Browse button to open theSelect Path - Git Configuration
dialog box and select the location of the Git executable file in the directories tree.
See "Where is git.exe located?" for the path of Git on Windows.
with Git for Windows:
C:\Program Files\Git\mingw64\bin
OR
c:\path\to\PortableGit-2.6.2-64-bit\usr\bin
OR
c:\path\to\PortableGit-2.x.\mingw64\bin
With GitHub Desktop:
%USERPROFILE%\AppData\Local\GitHub\PORTAB~1\bin\git.exe
Update 2020, three years later:
As noted by Daniel Connelly in the comments
IntelliJ now lets people install it through the path specified in the help above (just look for the "
Download Now
" button on the Git menu).
If you download Git from the website, a version that IntelliJ does not support will be installed.
If you just want to get the file names and not directory names then use :
dir /b /a-d > file.txt
Besides the 'console
' usage issue mentioned in accepted answer and others,there is at least another reason why sometimes pages in Internet Explorer work only with the developer tools activated.
When Developer Tools is enabled, IE doesn't really uses its HTTP cache (at least by default in IE 11) like it does in normal mode.
It means if your site or page has a caching problem (if it caches more than it should for example - that was my case), you will not see that problem in F12 mode. So if the javascript does some cached AJAX requests, they may not work as expected in normal mode, and work fine in F12 mode.
Actually, the simplest way to do it could be to:
MERGE_BASE=$(git merge-base branch-a branch-b)
rebase the resulting branch onto itself, starting at the merge base from step 1, and manually remove commits that are not desired:
git rebase ${SAVED_MERGE_BASE} -i
Alternatively, if there are only a few new commits, skip step 1, and simply use
git rebase HEAD^^^^^^^ -i
in the first step, using enough ^
to move past the merge-base.
You will see something like this in the interactive rebase:
pick 3139276 commit a
pick c1b421d commit b
pick 7204ee5 commit c
pick 6ae9419 commit d
pick 0152077 commit e
pick 2656623 commit f
Then remove lines b (and any others you want)
If you want to get the contents of selected cell; you need the index of row and cell.
int rowindex = dataGridView1.CurrentCell.RowIndex;
int columnindex = dataGridView1.CurrentCell.ColumnIndex;
dataGridView1.Rows[rowindex].Cells[columnindex].Value.ToString();
just make a function :
public Spanned fromHtml(String str){
return Build.VERSION.SDK_INT >= 24 ? Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY) : Html.fromHtml(str);
}
date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801
I encountered this error with the Eclipse 4.10 installer. We had failed to complete the install correctly due to platform security settings and attempted to uninstall but had to do it by hand since no uninstaller was introduced during the failed install. We suspected this corrupted the end result - even after re-installing.
The solution was to use the JVM to launch Eclipse and bypass the launcher executable entirely. The following command successfully launches Eclipse 4.10 (some parameters will change based on the version of Eclipse):
%JDK190%\bin\javaw.exe -jar C:\<fully_qualified_path_to_eclipse>\Eclipse410\plugins\org.eclipse.equinox.launcher_1.5.200.v20180922-1751.jar -clean -showsplash
After using this command/shortcut to launch Eclipse we had no further errors with Eclipse itself but we weren't able to use the EXE launcher in the future. Even after a year of using this version, the launcher continues to display this same error.
To be clear, you'll have to modify your javaw.exe
command to match your system specifications on MS Windows.
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
Because $
does not work on atomic vectors. Use [
or [[
instead. From the help file for $
:
The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
x[["ed"]]
will work.
From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.
That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.
You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.
Using docker compose you can mount a volume with postgresql.auto.conf
.
Example:
version: '2'
services:
db:
image: postgres:10.9-alpine
volumes:
- postgres:/var/lib/postgresql/data:z
- ./docker/postgres/postgresql.auto.conf:/var/lib/postgresql/data/postgresql.auto.conf
ports:
- 5432:5432
The git will ignore the files matched .gitignore pattern after you add it to .gitignore.
But the files already existed in repository will be still in.
use git rm files_ignored; git commit -m 'rm no use files'
to delete ignored files.
Try this SQL statement:
update Table set Column =( Column - your val )
Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:
string s = //{ "user" : { "id" : 12345, "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);
You'll get back something, where you can do:
var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.
Look at result
in the debugger to see, what's in there.
To add a use case to this that is often not discussed, I will pose a solution when submitting a Spark
application via spark-submit
in local mode.
According to the gitbook Mastering Apache Spark by Jacek Laskowski:
You can run Spark in local mode. In this non-distributed single-JVM deployment mode, Spark spawns all the execution components - driver, executor, backend, and master - in the same JVM. This is the only mode where a driver is used for execution.
Thus, if you are experiencing OOM
errors with the heap
, it suffices to adjust the driver-memory
rather than the executor-memory
.
Here is an example:
spark-1.6.1/bin/spark-submit
--class "MyClass"
--driver-memory 12g
--master local[*]
target/scala-2.10/simple-project_2.10-1.0.jar
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
server: "localhost\\SQL2K14",_x000D_
database: "SampleDb",_x000D_
user: "sa",_x000D_
password: "sql2014",_x000D_
port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
var conn = new sql.Connection(dbConfig);_x000D_
_x000D_
conn.connect().then(function () {_x000D_
var req = new sql.Request(conn);_x000D_
req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
console.log(recordset);_x000D_
conn.close();_x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
conn.close();_x000D_
}); _x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
});_x000D_
_x000D_
//--> another way_x000D_
//var req = new sql.Request(conn);_x000D_
//conn.connect(function (err) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// return;_x000D_
// }_x000D_
// req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// }_x000D_
// else { _x000D_
// console.log(recordset);_x000D_
// }_x000D_
// conn.close();_x000D_
// });_x000D_
//});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:
FOR /F "tokens=*" %G IN ('dir /b') DO robocopy "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0
As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.
It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.
I've solved this as is shown below:
long year = calendar.get(Calendar.YEAR);
long month = calendar.get(Calendar.MONTH) + 1;
long day = calendar.get(Calendar.DAY_OF_MONTH);
long calcDate = year * 100 + month;
calcDate = calcDate * 100 + day;
System.out.println("int: " + calcDate);
Because the vertical-align
is set at baseline as default.
Use vertical-align:top
instead:
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align:top;
}
http://jsfiddle.net/Lighty_46/RHM5L/9/
Or as @f00644 said you could apply float
to the child elements as well.
I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:
subinacl.exe /service w3svc /grant=VMX001\job=PTO
The permissions you can grant are defined as follows (list taken from here):
F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service
U : Service User-Defined Control Commands
So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.
You need to specify data
, index
and columns
to DataFrame
constructor, as in:
>>> pd.DataFrame(data=data[1:,1:], # values
... index=data[1:,0], # 1st column as index
... columns=data[0,1:]) # 1st row as the column names
edit: as in the @joris comment, you may need to change above to np.int_(data[1:,1:])
to have correct data type.
Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0
Follow the official instruction doesn't work
Finally use the old way to figure it out.
ADD:
# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
#proj/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'proj.middlewares.CsrfExemptSessionAuthentication',
),
}
You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.
Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
server.on('listening', function() {
console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});
This works just fine in nodejs v0.6+ and Express v3.0+.
make input to block and float, Adjust margin top value.
HTML:
<div class="label">
<input type="checkbox" name="test" /> luke..
</div>
CSS:
/*
change margin-top, if your line-height is different.
*/
input[type=checkbox]{
height:18px;
width:18px;
padding:0;
margin-top:5px;
display:block;
float:left;
}
.label{
border:1px solid red;
}
Quote, which summarizes from this article:
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
Try
html
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
js
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
The real easy way to do that it is
word = str(raw_input(""))
is_palindrome = word.find(word[::-1])
if is_palindrome == 0:
print True
else:
print False
And if/else here just for fancy looks. The question about palindrome was on Amazon's interview for QA
If all that's needed is to send html code inline in the code, we can use below
var app = express();
app.get('/test.html', function (req, res) {
res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});
1, 2, 3 ,... are invalid identifiers in python because first of all they are integer objects and secondly in python a variable name can't start with a number.
>>> 1 = 12 #you can't assign to an integer
File "<ipython-input-177-30a62b7248f1>", line 1
SyntaxError: can't assign to literal
>>> 1a = 12 #1a is an invalid variable name
File "<ipython-input-176-f818ca46b7dc>", line 1
1a = 12
^
SyntaxError: invalid syntax
Valid identifier definition:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
Example:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
As you can see, the script "build_c" is building the angular application, then deletes all old files from a directory, then finally copies the result build files.
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
Here is one-liner to get absolute path to your Makefile
file using shell syntax:
SHELL := /bin/bash
CWD := $(shell cd -P -- '$(shell dirname -- "$0")' && pwd -P)
And here is version without shell based on @0xff answer:
CWD := $(abspath $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))))
Test it by printing it, like:
cwd:
@echo $(CWD)
Try to avoid complete path references in the #include directive, whether they are absolute or relative. Instead, add the location of the other project's include folder in your project settings. Use only subfolders in path references when necessary. That way, it is easier to move things around without having to update your code.
Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan
Here is an extract from it:
openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>
Even if you don't have GNU date, you'll probably have Perl installed:
use Time::Local;
sub to_epoch {
my ($t) = @_;
my ($y, $d, $m) = ($t =~ /(\d{4})-(\d{2})-(\d{2})/);
return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
}
sub diff_days {
my ($t1, $t2) = @_;
return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
}
print diff_days("2002-20-10", "2003-22-11"), "\n";
This returns 398.041666666667
-- 398 days and one hour due to daylight savings.
The question came back up on my feed. Here's a more concise method using a Perl bundled module
days=$(perl -MDateTime -le '
sub parse_date {
@f = split /-/, shift;
return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
}
print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
' $A $B)
echo $days # => 398
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
Here is the solution :
This is kind of hack , but it will work
<input type="number"
placeholder="Charge"
[(ngModel)]="rateInput"
name="rateInput"
pattern="^$|^([0-9]|[1-9][0-9]|[1][0][0])?"
required
#rateInput2 = "ngModel">
<div *ngIf="rateInput2.errors && (rateInput2.dirty || rateInput2.touched)"
<div [hidden]="!rateInput2.errors.pattern">
Number should be between 0 and 100
</div>
</div>
Here is the link to the plunker , please have a look.
Also The function can help in sorting. To be more clear about sorting. strcmp() returns less than 0 if string1 sorts before string2, greater than 0 if string2 sorts before string1 or 0 if they are the same. For example
$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string,$second_string);
The function will return greater than zero, as aaao is sorting before aabo.
let parameters = ["foo": "bar"]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
Is's better because getOne(ID id)
gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save()
it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find()
like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.
That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require
(which is always needed) with a matching version constraint.
In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.
For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:
require
for the package in questionrequire
matches the versions provided by the VCS repo. You can use composer show <packagename>
to find the available versions. In this case ~2.3
would be a good option.require
matches the name in the remote composer.json
. In this case, it is gedmo/doctrine-extensions
.Here is a sample composer.json
that installs the same package via a VCS repo:
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
The VCS repo docs explain all of this quite well.
If there is a git (or other VCS) repository with a composer.json
available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json
present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.
Avoid package repos (see also the docs).
I had a similar problem, I had created a DLL, i.e., A.dll, which referenced other DLL, i.e., B.dll.
I created an application C.exe and referenced DLLs A.dll and B.dll.
Solution - On removing the reference of B.dll from c.exe I was able to fix the issue.
Hope this helps.
Using moment.js
, you can use keepOffset
parameter of toISOString
:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Environment:Linux Error: "jenkins Failed to connect to repository : Error performing command: git ls-remote -h"
Solution : if repository URL and credential configured correctly ,problem on git installion and config a) make sure git installed on your linux machine. if git not installed , install it ("sudo yum install git") b) Goto to -> Manage Jenkins -> Global Tool Configuration ->Git->Path to Git executable make sure "git" command present.
Or, you may exclude the options in quotes:
FOR /F %%i IN (myfile.txt) DO ECHO %%i
In my case, I had not given my <input>
elements any ID, and was using a class to apply the datepicker as in SeanJA's answer, but the datepicker was only being applied to the first one. I discovered that JQuery was automatically adding an ID and it was the same one in all of the elements, which explained why only the first was getting datepickered.
A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.
Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.
In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.
Below a useless code is given, but it will suffice to do away with your some confusions about Runnable
. It will print "Hello World".
class NamedRunnable implements Runnable {
public void run() { // The run method prints a message to standard output.
System.out.println("Hello World");
}
public static void main(String[]arg){
NamedRunnable namedRunnable = new NamedRunnable( );
namedRunnable.run();
}
}
A singleton service
is a service for which only one instance exists in an app.
There are (2) ways to provide a singleton service for your application.
use the providedIn
property, or
provide the module directly in the AppModule
of the application
Using providedIn
Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn
to root on the service's @Injectable()
decorator. This tells Angular to provide the service in the application root.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
NgModule providers array
In apps built with Angular versions prior to 6.0, services are registered NgModule providers arrays as follows:
@NgModule({
...
providers: [UserService],
...
})
If this NgModule
were the root AppModule
, the UserService would be a singleton and available throughout the app. Though you may see it coded this way, using the providedIn
property of the @Injectable()
decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable.
By using
$_SERVER['REQUEST_METHOD']
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
For more details please see the documentation for the $_SERVER variable.
With O(1)
dequeue()
, which is same as pythonquick's answer:
// time: O(n), space: O(n)
enqueue(x):
if stack.isEmpty():
stack.push(x)
return
temp = stack.pop()
enqueue(x)
stack.push(temp)
// time: O(1)
x dequeue():
return stack.pop()
With O(1)
enqueue()
(this is not mentioned in this post so this answer), which also uses backtracking to bubble up and return the bottommost item.
// O(1)
enqueue(x):
stack.push(x)
// time: O(n), space: O(n)
x dequeue():
temp = stack.pop()
if stack.isEmpty():
x = temp
else:
x = dequeue()
stack.push(temp)
return x
Obviously, it's a good coding exercise as it inefficient but elegant nevertheless.
It depends on how you declare your table. NULL would not be allowed in:
create table MyTable (col1 datetime NOT NULL);
But it would be allowed in:
create table MyTable (col1 datetime NULL);
The second is the default, so someone must've actively decided that the column should not be nullable.
It's available many, many places, depending upon what is installed: On my box, every one except the v6.0A SDK version supports the /fd option.
Since fields
or fns
are cell arrays, you have to index with curly brackets {}
in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields
directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end
For Laravel 5.5 and probably 5.4
In App\Http\Middleware\RedirectIfAuthenticated change redirect('/home')
to redirect()->intended('/home')
in the handle function:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/home');
}
return $next($request);
}
in App\Http\Controllers\Auth\LoginController create the showLoginForm()
function as follows:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
This way if there was an intent for another page it will redirect there otherwise it will redirect home.
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
The same approach should work for other attribute types.
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
for uploading a new project into GIT (first you need to have local code base of project and the GIT repo where you will be uploading project ,in GIT you need to have your credentials)
List item
1.open Git Bash
2 . go to the directory where you have the code base (project location ) cd to project location cd /*/***/*****/***** Then here you need to execute git commands
git add . press enter the above command will add all the directory,sub directory , files etc you will see something like this warning: LF will be replaced by CRLF in ****. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ********. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *******. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ********. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *******. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in **************. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ************. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *************** The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in j*******. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ***********. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in **************. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ***********. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *********. The file will have its original line endings in your working directory.
git commit -m "first commit" press enter -m provided option for adding comment it will commit the code to stage env you will see some thing like this
[master (root-commit) 34a28f6] adding ******** warning: LF will be replaced by CRLF in c*******. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *******. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in ********. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in *********. The file will have its original line endings in your working directory.
27 files changed, 3724 insertions(+) create mode 100644 ***** create mode 100644 ***** create mode 100644 ***** create mode 100644 ****** create mode 100644 ****** create mode 100644 ***** create mode 100644 ******
6.git remote add origin http://username@git:repopath.git press enter this will add to repo
7.git push -u origin master press enter this will upload all from local to repo in this step you need to enter password for the repo where you will be uploading the code. you will see some thing like this below Counting objects: 33, done. Delta compression using up to 12 threads. Compressing objects: 100% (32/32), done. Writing objects: 100% (33/33), 20.10 KiB | 0 bytes/s, done. Total 33 (delta 14), reused 0 (delta 0) To http://username@git:repolocation.git * [new branch] master -> master Branch master set up to track remote branch master from origin.
You can use the Boolean constants - Boolean.TRUE
and Boolean.FALSE
instead of 0
and 1
. You can create your variable as of type boolean
if primitive is what you are after. This way you won't have to create new Boolean
objects.
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
$('.toggle img').each(function(index) {
if($(this).attr('data-id') == '4')
{
$(this).attr('data-block', 'something');
$(this).attr('src', 'something.jpg');
}
});
or
$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');
Actually correct one to one implementation is:
int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
Like @gotgenes pointed out with Jenkins Version. 2.74, the below works, not sure since when, maybe if some one can edit and add the version above
cleanWs()
With, Jenkins Version 2.16 and the Workspace Cleanup Plugin, that I have, I use
step([$class: 'WsCleanup'])
to delete the workspace.
You can view it by going to
JENKINS_URL/job/<any Pipeline project>/pipeline-syntax
Then selecting "step: General Build Step" from Sample step and then selecting "Delete workspace when build is done" from Build step
If you are fetching data from axios and the error still occurs, just wrap the setter inside the condition
let isRendered = useRef(false);
useEffect(() => {
isRendered = true;
axios
.get("/sample/api")
.then(res => {
if (isRendered) {
setState(res.data);
}
return null;
})
.catch(err => console.log(err));
return () => {
isRendered = false;
};
}, []);
Spawning new processes on the server using exec()
or directly on another server using curl doesn't scale all that well at all, if we go for exec you are basically filling your server with long running processes which can be handled by other non web facing servers, and using curl ties up another server unless you build in some sort of load balancing.
I have used Gearman in a few situations and I find it better for this sort of use case. I can use a single job queue server to basically handle queuing of all the jobs needing to be done by the server and spin up worker servers, each of which can run as many instances of the worker process as needed, and scale up the number of worker servers as needed and spin them down when not needed. It also let's me shut down the worker processes entirely when needed and queues the jobs up until the workers come back online.
take a look at the jquery selectedbox plugin
selectOptions(value[, clear]):
Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");
, or a regular expression $("#myselect2").selectOptions(/^val/i);
.
You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);
That's passing a pointer by reference rather than by value. This for example allows altering the pointer (not the pointed-to object) in the function is such way that the calling code sees the change.
Compare:
void nochange( int* pointer ) //passed by value
{
pointer++; // change will be discarded once function returns
}
void change( int*& pointer ) //passed by reference
{
pointer++; // change will persist when function returns
}
This answer explains what's going on behind the scenes, and the basics of how to solve this problem in any language. For reference, see the MDN docs on this topic.
You are making a request for a URL from JavaScript running on one domain (say domain-a.com) to an API running on another domain (domain-b.com). When you do that, the browser has to ask domain-b.com if it's okay to allow requests from domain-a.com. It does that with an HTTP OPTIONS
request. Then, in the response, the server on domain-b.com has to give (at least) the following HTTP headers that say "Yeah, that's okay":
HTTP/1.1 204 No Content // or 200 OK
Access-Control-Allow-Origin: https://domain-a.com // or * for allowing anybody
Access-Control-Allow-Methods: POST, GET, OPTIONS // What kind of methods are allowed
... // other headers
If you're in Chrome, you can see what the response looks like by pressing F12 and going to the "Network" tab to see the response the server on domain-b.com is giving.
So, back to the bare minimum from @threeve's original answer:
header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
This will allow anybody from anywhere to access this data. The other headers he's included are necessary for other reasons, but these headers are the bare minimum to get past the CORS (Cross Origin Resource Sharing) requirements.
I think this statement might do what you want.
INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL
Read http://sqlite.org/datatype3.html to more info.
Python Unittest, Bat process Error Codes:
if __name__ == "__main__":
test_suite = unittest.TestSuite()
test_suite.addTest(RunTestCases("test_aggregationCount_001"))
runner = unittest.TextTestRunner()
result = runner.run(test_suite)
# result = unittest.TextTestRunner().run(test_suite)
if result.wasSuccessful():
print("############### Test Successful! ###############")
sys.exit(1)
else:
print("############### Test Failed! ###############")
sys.exit()
Bat codes:
@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
echo Error found. Waiting here...
pause
) || (
echo This time of test is ok.
)
)
There's absolutely nothing wrong with including the entirety of jQuery within your Greasemonkey script. Just take the source, and place it at the top of your user script. No need to make a script tag, since you're already executing JavaScript!
The user only downloads the script once anyways, so size of script is not a big concern. In addition, if you ever want your Greasemonkey script to work in non-GM environments (such as Opera's GM-esque user scripts, or Greasekit on Safari), it'll help not to use GM-unique constructs such as @require.
Swift 2.x answer:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.getResultSetFromDB(docids)
}
theBoolean = !theBoolean;
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
Sidenote: With modern Git (>= 1.6.6), you are able to use just
git checkout test
(note that it is 'test' not 'origin/test') to perform magical DWIM-mery and create local branch 'test' for you, for which upstream would be remote-tracking branch 'origin/test'.
The * (no branch)
in git branch
output means that you are on unnamed branch, in so called "detached HEAD" state (HEAD points directly to commit, and is not symbolic reference to some local branch). If you made some commits on this unnamed branch, you can always create local branch off current commit:
git checkout -b test HEAD
I found a comment buried below which seems to modernize this answer:
@Dennis:
git checkout <non-branch>
, for examplegit checkout origin/test
results in detached HEAD / unnamed branch, whilegit checkout test
orgit checkout -b test origin/test
results in local branchtest
(with remote-tracking branchorigin/test
as upstream) – Jakub Narebski Jan 9 '14 at 8:17
emphasis on git checkout origin/test
Delegate and Live are easy to use but if you won't have any more li:s added dynamically you could use event delagation with normal bind/click as well. There should be some performance gain using this method since the DOM won't have to be monitored for new matching elements. Haven't got any actual numbers but it makes sense :)
$("#wizard").click(function (e) {
var source = $(e.target);
if(source.is("li")){
// alert index of li relative to ul parent
alert(source.index());
}
});
You could test it at jsFiddle: http://jsfiddle.net/jimmysv/4Sfdh/1/
For me.
Edit .gitattributes file.
add
*.dll binary
Then everything goes well.
The global type Function
serves this purpose.
Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void
matches all functions taking no arguments.
The answer and question here has way too many updoots not to mention the only-slightly more complex yet best-practice method:
Solution to your question
interface Easy_Fix_Solution {
title: string;
callback: Function;
}
NOTE: Please do not use Function
as you most likely do not want any
callback function. It's okay to be a little specific.
Improvement to that solution
interface Safer_Easy_Fix {
title: string;
callback: () => void;
}
interface Alternate_Syntax_4_Safer_Easy_Fix {
title: string;
callback(): void;
}
NOTE: The original author is correct, accepting no arguments and returning void is better.. it's much safer, it tells the consumer of your interface that you will not be doing anything with their return value, and that you will not be passing them any parameters.
And better yet
Use generics. This interface would also work for the same () => void
function types mentioned before.
interface Better_still_safe_but_way_more_flexible_fix {
title: string;
callback: <T = unknown, R = unknown>(args?: T) => R;
}
interface Alternate_Syntax_4_Better_still_safe_but_way_more_flexible_fix {
title: string;
callback<T = unknown, R = unknown>(args?: T): R;
}
NOTE: If you aren't 100% sure about the callback signature right now, please choose the void option above, or this generic option if you think you may extend functionality going forward. Callbacks usually receive some arguments of some sort, and sometimes the callback orchestrator even does something with the return value.
And a slightly more advanced usecase you shouldn't use unless you need it
This allows any number of arguments, of any type in T.
More details here.
interface Alternate_Syntax_4_Advanced {
title: string;
callback<T extends unknown[], R = unknown>(...args?: T): R;
}
ASCII defines 128 characters, as Unicode contains a repertoire of more than 120,000 characters.
You can also do the following;
string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
if (fromIndex > toIndex)
throw new ArgumentOutOfRangeException("fromIndex");
for (var i = fromIndex; i <= toIndex; i++)
col[i] = value;
}
Something that works for all IList<T>
s.
You can also reset page number counter:
\setcounter{page}{1}
However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:
\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...
First, you want to use
model <- lm(Total ~ Coupon, data=df)
not model <-lm(df$Total ~ df$Coupon, data=df)
.
Second, by saying lm(Total ~ Coupon)
, you are fitting a model that uses Total
as the response variable, with Coupon
as the predictor. That is, your model is of the form Total = a + b*Coupon
, with a
and b
the coefficients to be estimated. Note that the response goes on the left side of the ~
, and the predictor(s) on the right.
Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon
, not Total
.
Third, judging by your specification of newdata
, it looks like you're actually after a model to fit Coupon
as a function of Total
, not the other way around. To do this:
model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)
Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.
If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow
How to convert <select> dropdown into an unordered list using jquery?
I had same problem when using VPN. Simple fixed with restarting internet connection.
In all tests I have seen, eAccelerator performs faster than any other cache out there and uses less memeory to do so. It comes with a nifty script to view cache utilisation and clear the cache etc. eAccelerator is compatible with xdebug and Zend Optimizer.
APC is being included in PHP because it is being maintained by the PHP developers. It performs very well, but not as good as eAccelerator. And it has compatability issues with Zend Optimizer.
Xcache was made by the developers of lighttpd, benchmarks show it performs similiarly to eAccelerator, and faster than APC.
So which is the best?
APC = Great if you want an easy cache that will always work with PHP, no fuss. eAccelerator = If you have time to maintain it, keep it up todate and understand how it works, it will perform faster. Long term support not as certain as APC because APC is done by the PHP devs.
SELECT author FROM lyrics WHERE author LIKE 'B%';
Make sure you have an index on author
, though!
If you want to add an empty folder you can add a '.keep' file in your folder.
This is because git does not care about folders.
This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically
select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'
exec (@sql)
of course #tables is a dynamic table in the stored procedure
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
You need to checkout the branch:
git checkout master
See the Git cheat sheets for more information.
Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.
Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
in your Xcode:
screen -X -S SCREENID kill
alternatively, you can use the following command
screen -S SCREENNAME -p 0 -X quit
You can view the list of the screen sessions by executing screen -ls
See my article on understanding vertical alignment. There are multiple techniques to accomplish what you want at the end of the discussion.
(Super-short summary: either set the line-height of the child equal to the height of the container, or set positioning on the container and absolutely position the child at top:50%
with margin-top:-YYYpx
, YYY being half the known height of the child.)
Click on the Project in Visual Studio and then click on the button titled "Show all files" on the Solution Explorer toolbar. That will show files that aren't in the project. Now you'll see that image, right click in it, and select "Include in project" and that will add the image to the project!
I created the following function to generate an html table from an arbitrary JSON object:
function toTable(json, colKeyClassMap, rowKeyClassMap){
let tab;
if(typeof colKeyClassMap === 'undefined'){
colKeyClassMap = {};
}
if(typeof rowKeyClassMap === 'undefined'){
rowKeyClassMap = {};
}
const newTable = '<table class="table table-bordered table-condensed table-striped" />';
if($.isArray(json)){
if(json.length === 0){
return '[]'
} else {
const first = json[0];
if($.isPlainObject(first)){
tab = $(newTable);
const row = $('<tr />');
tab.append(row);
$.each( first, function( key, value ) {
row.append($('<th />').addClass(colKeyClassMap[key]).text(key))
});
$.each( json, function( key, value ) {
const row = $('<tr />');
$.each( value, function( key, value ) {
row.append($('<td />').addClass(colKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap)))
});
tab.append(row);
});
return tab;
} else if ($.isArray(first)) {
tab = $(newTable);
$.each( json, function( key, value ) {
const tr = $('<tr />');
const td = $('<td />');
tr.append(td);
$.each( value, function( key, value ) {
td.append(toTable(value, colKeyClassMap, rowKeyClassMap));
});
tab.append(tr);
});
return tab;
} else {
return json.join(", ");
}
}
} else if($.isPlainObject(json)){
tab = $(newTable);
$.each( json, function( key, value ) {
tab.append(
$('<tr />')
.append($('<th style="width: 20%;"/>').addClass(rowKeyClassMap[key]).text(key))
.append($('<td />').addClass(rowKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap))));
});
return tab;
} else if (typeof json === 'string') {
if(json.slice(0, 4) === 'http'){
return '<a target="_blank" href="'+json+'">'+json+'</a>';
}
return json;
} else {
return ''+json;
}
};
So you can simply call:
$('#mydiv').html(toTable([{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]));
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
An alternative is to call the pip
module by using python2.7, as below:
python2.7 -m pip <commands>
For example, you could run python2.7 -m pip install <package>
to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.
In case the pip module has not yet been installed for this version of python, you can run the following:
python2.7 -m ensurepip
Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo
). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.
I like to do this
input[type="text"]
{
background: rgba(0, 0, 0, 0);
border: none;
outline: none;
}
Setting the outline
property to none
stops the browser from highlighting the box when the cursor enters
As you pointed out in your question it is a documented behavior. I still find it strange though. I use to repopulate the test database and even though I do not rely on the values of identity fields it was a bit of annoying to have different values when populating the database for the first time from scratch and after removing all data and populating again.
A possible solution is to use truncate to clean the table instead of delete. But then you need to drop all the constraints and recreate them afterwards
In that way it always behaves as a newly created table and there is no need to call DBCC CHECKIDENT. The first identity value will be the one specified in the table definition and it will be the same no matter if you insert the data for the first time or for the N-th
Code for Yes and No Message
int n = JOptionPane.showConfirmDialog(
null,
"sample question?!" ,
"",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Opening...");
}
else
{
JOptionPane.showMessageDialog(null, "Goodbye");
System.exit(0);
To do it on page load:
window.onload = function () {_x000D_
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();_x000D_
}
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
On my data I got these benchmarks:
>>> data.select(col).rdd.flatMap(lambda x: x).collect()
0.52 sec
>>> [row[col] for row in data.collect()]
0.271 sec
>>> list(data.select(col).toPandas()[col])
0.427 sec
The result is the same
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend
statement is called before the complete
statement i
will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
If you have opened a file in preview mode and want to open new file in another tab:
For Mac: use cmd
+ p
-> find the file and alt
+ enter
.
Another alternative would be to show a Toast
/Snackbar
on the first back press asking to press back again to Exit, which is a lot less intrusive than showing an AlertDialog
to confirm if user wants to exit the app.
You can use the DoubleBackPress Android Library
to achieve this with a few lines of code. Example GIF showing similar behaviour.
To begin with, add the dependency to your application :
dependencies {
implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}
Next, in your Activity, implement the required behaviour.
// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);
// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
@Override
public void actionCall() {
// TODO : Exit the application
finish();
System.exit(0);
}
};
// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
.withDoublePressDuration(3000) // msec - wait for second back press
.withFirstBackPressAction(firstBackPressAction)
.withDoubleBackPressAction(doubleBackPressAction);
Finally, set this as the behaviour on back press.
@Override
public void onBackPressed() {
doubleBackPress.onBackPressed();
}
I solved mine because the other project was coded with .NET 4.5 and the other one was coded 4.0
Shorter variation of Dirk's answer:
# Create a Color Palette Dictionary
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')
> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
>
> color_palette
$navy.blue
[1] "#336A91"
$gold
[1] "#F3C117"
$dark.gray
[1] "#7F7F7F"
press Windows key + R write "services.msc" enter search for "MYSQL56" write click on it and start the service
Document has already explain the usage. So I am using SQL to explain these methods
Assuming there is an Order (orders)
has many OrderItem (order_items)
.
And you have already build the relationship between them.
// App\Models\Order:
public function orderItems() {
return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}
These three methods are all based on a relationship.
Result: with()
return the model object and its related results.
Advantage: It is eager-loading which can prevent the N+1 problem.
When you are using the following Eloquent Builder:
Order::with('orderItems')->get();
Laravel change this code to only two SQL:
// get all orders:
SELECT * FROM orders;
// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);
And then laravel merge the results of the second SQL as different from the results of the first SQL by foreign key. At last return the collection results.
So if you selected columns without the foreign_key in closure, the relationship result will be empty:
Order::with(['orderItems' => function($query) {
// $query->sum('quantity');
$query->select('quantity'); // without `order_id`
}
])->get();
#=> result:
[{ id: 1,
code: '00001',
orderItems: [], // <== is empty
},{
id: 2,
code: '00002',
orderItems: [], // <== is empty
}...
}]
Has
will return the model's object that its relationship is not empty.
Order::has('orderItems')->get();
Laravel change this code to one SQL:
select * from `orders` where exists (
select * from `order_items` where `order`.`id` = `order_item`.`order_id`
)
whereHas
and orWhereHas
methods to put where
conditions on your has
queries. These methods allow you to add customized constraints to a relationship constraint.
Order::whereHas('orderItems', function($query) {
$query->where('status', 1);
})->get();
Laravel change this code to one SQL:
select * from `orders` where exists (
select *
from `order_items`
where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)
In my case, I was using the ASP.NET Identity Framework. I had used the built in UserManager.FindByNameAsync
method to retrieve an ApplicationUser
entity. I then tried to reference this entity on a newly created entity on a different DbContext
. This resulted in the exception you originally saw.
I solved this by creating a new ApplicationUser
entity with only the Id
from the UserManager
method and referencing that new entity.
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.
Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.
Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps
UPDATE:
Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:
Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages
Building on Matt's answer, here's one that searches across newlines and is easy to modify for your own use
$String="----start----`nHello World`n----end----"
$SearchStart="----start----`n" #Will not be included in results
$SearchEnd="`n----end----" #Will not be included in results
$String -match "(?s)$SearchStart(?<content>.*)$SearchEnd"
$result=$matches['content']
$result
--
NOTE: if you want to run this against a file keep in mind Get-Content returns an array not a single string. You can work around this by doing the following:
$String=[string]::join("`n", (Get-Content $Filename))
Instead of using np.hist2d, which in general produces quite ugly histograms, I would like to recycle py-sphviewer, a python package for rendering particle simulations using an adaptive smoothing kernel and that can be easily installed from pip (see webpage documentation). Consider the following code, which is based on the example:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import sphviewer as sph
def myplot(x, y, nb=32, xsize=500, ysize=500):
xmin = np.min(x)
xmax = np.max(x)
ymin = np.min(y)
ymax = np.max(y)
x0 = (xmin+xmax)/2.
y0 = (ymin+ymax)/2.
pos = np.zeros([len(x),3])
pos[:,0] = x
pos[:,1] = y
w = np.ones(len(x))
P = sph.Particles(pos, w, nb=nb)
S = sph.Scene(P)
S.update_camera(r='infinity', x=x0, y=y0, z=0,
xsize=xsize, ysize=ysize)
R = sph.Render(S)
R.set_logscale()
img = R.get_image()
extent = R.get_extent()
for i, j in zip(xrange(4), [x0,x0,y0,y0]):
extent[i] += j
print extent
return img, extent
fig = plt.figure(1, figsize=(10,10))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)
#Plotting a regular scatter plot
ax1.plot(x,y,'k.', markersize=5)
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)
heatmap_16, extent_16 = myplot(x,y, nb=16)
heatmap_32, extent_32 = myplot(x,y, nb=32)
heatmap_64, extent_64 = myplot(x,y, nb=64)
ax2.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')
ax2.set_title("Smoothing over 16 neighbors")
ax3.imshow(heatmap_32, extent=extent_32, origin='lower', aspect='auto')
ax3.set_title("Smoothing over 32 neighbors")
#Make the heatmap using a smoothing over 64 neighbors
ax4.imshow(heatmap_64, extent=extent_64, origin='lower', aspect='auto')
ax4.set_title("Smoothing over 64 neighbors")
plt.show()
which produces the following image:
As you see, the images look pretty nice, and we are able to identify different substructures on it. These images are constructed spreading a given weight for every point within a certain domain, defined by the smoothing length, which in turns is given by the distance to the closer nb neighbor (I've chosen 16, 32 and 64 for the examples). So, higher density regions typically are spread over smaller regions compared to lower density regions.
The function myplot is just a very simple function that I've written in order to give the x,y data to py-sphviewer to do the magic.
Bootstrap 4.x uses the new .d-none
class. Instead of using either .hidden
, or .hide
if you're using Bootstrap 4.x use .d-none
.
<div id="myId" class="d-none">Foobar</div>
$("#myId").removeClass('d-none');
$("#myId").addClass('d-none');
$("#myId").toggleClass('d-none');
(thanks to the comment by Fangming)
First, don't use .hide
! Use .hidden
. As others have said, .hide
is deprecated,
.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1
Second, use jQuery's .toggleClass(), .addClass() and .removeClass()
<div id="myId" class="hidden">Foobar</div>
$("#myId").removeClass('hidden');
$("#myId").addClass('hidden');
$("#myId").toggleClass('hidden');
Don't use the css class .show
, it has a very small use case. The definitions of show
, hidden
and invisible
are in the docs.
// Classes
.show {
display: block !important;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.invisible {
visibility: hidden;
}
There is a significant problem with some of the answers posted so far: unicode()
decodes from the default encoding, which is often ASCII; in fact, unicode()
tries to make "sense" of the bytes it is given by converting them into characters. Thus, the following code, which is essentially what is recommended by previous answers, fails on my machine:
# -*- coding: utf-8 -*-
author = 'éric'
print '{0}'.format(unicode(author))
gives:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print '{0}'.format(unicode(author))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
The failure comes from the fact that author
does not contain only ASCII bytes (i.e. with values in [0; 127]), and unicode()
decodes from ASCII by default (on many machines).
A robust solution is to explicitly give the encoding used in your fields; taking UTF-8 as an example:
u'{0} in {1}'.format(unicode(self.author, 'utf-8'), unicode(self.publication, 'utf-8'))
(or without the initial u
, depending on whether you want a Unicode result or a byte string).
At this point, one might want to consider having the author
and publication
fields be Unicode strings, instead of decoding them during formatting.
//an easy way:
str := fmt.Sprint(data)
There is a pretty library at http://256stuff.com/sources/md5/, with example of use. This is the simplest library for MD5.
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
In your table dbo.Sup_Item_Cat
, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help
'dbo.Sup_Item_Cat
'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
Let me know if you need anything explained better!
I would agree with Tuomas about using ssh-agent. I also wanted to add a second private key for work and this tutorial worked like a charm for me.
Steps are as below:
$ ssh-agent bash
$ ssh-add /path.to/private/key
e.g ssh-add ~/.ssh/id_rsa
$ ssh-add -l
$ssh -v <host url>
e.g ssh -v [email protected]
Here is what you need to do -
Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.
detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.
detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-
$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64
it will ask for password, put android that's all. u will get a key-hash
I realized the solution to this problem stems from Eclipse memory allocation when you run the application in normal mode. I just checked the "Run as Administrator" box under the shortcut properties for Eclipse and now it allows me to allocate more memory for the AVD.
Hope that helps.
Here are step-by-step instructions, How to install Sun Java JDK in Ubuntu 10.10 Maverick Meerkat.
This approach can be used to automate this (the following exemplary solution is in python, although obviously it can be ported to any language):
you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:
def regex_search_ignore_space(regex, string):
no_spaces = ''
char_positions = []
for pos, char in enumerate(string):
if re.match(r'\S', char): # upper \S matches non-whitespace chars
no_spaces += char
char_positions.append(pos)
match = re.search(regex, no_spaces)
if not match:
return match
# match.start() and match.end() are indices of start and end
# of the found string in the spaceless string
# (as we have searched in it).
start = char_positions[match.start()] # in the original string
end = char_positions[match.end()] # in the original string
matched_string = string[start:end] # see
# the match WITH spaces is returned.
return matched_string
with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'
If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.
And the performance of this function can of course also be optimized, this example is just to show the path to a solution.
You can still do this in top. While top is running, press '1' on your keyboard, it will then show CPU usage per core.
Limit the processes shown by having that specific process run under a specific user account and use Type 'u' to limit to that user
Assume you saved adb path into your Windows environment path
Activate debug mode in Android
Connect to PC via USB
Open command prompt type: adb tcpip 5555
Disconnect your tablet or smartphone from pc
Open command prompt type: adb connect IPADDRESS
(IPADDRESS is the DHCP/IP address of your tablet or smartphone, which you can find by Wi-Fi -> current connected network)
Now in command prompt you should see the result like: connected to xxx.xxx.xxx.xxx:5555
SQLite has a printf
function which does exactly that:
SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
I had the same problem, you should do:
File -> Invalidate Caches / Restart
How about this?
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))
The "3" at the end means for column C.
If you want to completely wipe the database and resync it in the same go you need something like the following. I also combine adding test data in this command:
#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") # Replace with your app name.
from django.db import connection
from django.core.management import call_command
from django.conf import settings
# If you're using postgres you can't use django's sql stuff for some reason that I
# can't remember. It has to do with that autocommit thing I think.
# import psychodb2 as db
def recreateDb():
print("Wiping database")
dbinfo = settings.DATABASES['default']
# Postgres version
#conn = db.connect(host=dbinfo['HOST'], user=dbinfo['USER'],
# password=dbinfo['PASSWORD'], port=int(dbinfo['PORT'] or 5432))
#conn.autocommit = True
#cursor = conn.cursor()
#cursor.execute("DROP DATABASE " + dbinfo['NAME'])
#cursor.execute("CREATE DATABASE " + dbinfo['NAME'] + " WITH ENCODING 'UTF8'") # Default is UTF8, but can be changed so lets be sure.
# Mysql version:
print("Dropping and creating database " + dbinfo['NAME'])
cursor = connection.cursor()
cursor.execute("DROP DATABASE " + dbinfo["NAME"] + "; CREATE DATABASE " + dbinfo["NAME"] + "; USE " + dbinfo["NAME"] + ";")
print("Done")
if __name__ == "__main__":
recreateDb();
print("Syncing DB")
call_command('syncdb', interactive=False)
print("Adding test data")
addTestData() # ...
It would be nice to be able to do cursor.execute(call_command('sqlclear', 'main'))
but call_command
prints the SQL to stdout rather than returning it as a string, and I can't work out the sql_delete
code...
A good option is Node-supervisor and Node.js Restart on File Change is good article on how to use it, typically:
npm install supervisor -g
and after migrating to the root of your application use the following
supervisor app.js
double
.*gasp*
Because it can represent any 15 digit number with no constraints on where the decimal point is. All for a measly 8 bytes!
So it can represent:
0.123456789012345
123456789012345.0
...and anything in between.
This is useful because we're dealing with global currencies, and double
can store the various numbers of decimal places we'll likely encounter.
A single double
field can represent 999,999,999,999,999s in Japanese yens, 9,999,999,999,999.99s in US dollars and even 9,999,999.99999999s in bitcoins
If you try doing the same with decimal
, you need decimal(30, 15)
which costs 14 bytes.
Of course, using double
isn't without caveats.
However, it's not loss of accuracy as some tend to point out. Even though double
itself may not be internally exact to the base 10 system, we can make it exact by rounding the value we pull from the database to its significant decimal places. If needed that is. (e.g. If it's going to be outputted, and base 10 representation is required.)
The caveats are, any time we perform arithmetic with it, we need to normalize the result (by rounding it to its significant decimal places) before:
Another kind of caveat is, unlike decimal(m, d)
where the database will prevent programs from inserting a number with more than m
digits, no such validations exists with double
. A program could insert a user inputted value of 20 digits and it'll end up being silently recorded as an inaccurate amount.
I got the solution by using comm
comm -23 file1 file2
will give you the desired output.
The files need to be sorted first anyway.
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file
I'm working on a Mac, OSX 10.9. I recently had to update my JDK to 1.7 for some VPN software. The application I'm working runs on JDK 1.6, so a GlassFish had to run with JDK 1.6. It took a minute to iron this out, but here's how it went for me. I work with the NetBeans IDE by the way.
My GlssFish configuration file
/Applications/NetBeans/glassfish-3.1.2.2/glassfish/config/asenv.conf
Path to JDK 1.6
/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
I added the following line to the bottom of my asenv.conf
file
AS_JAVA=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
If you are trying to run the Flutter Project in Android Studio, and the run button is disabled then here is the solution
Click on add configuration
and select Flutter and then select the main class in dataentrypoint
I'm running postgres (9.5) in a docker container (on CentOS, as it happens), and as Skippy le Grand Gourou mentions in a comment above, the files are located in /var/lib/postgresql/data/
.
$ docker exec -it my-postgres-db-container bash
root@c7d61efe2a5d:/# cd /var/lib/postgresql/data/
root@c7d61efe2a5d:/var/lib/postgresql/data# ls -lh
total 56K
drwx------. 7 postgres postgres 71 Apr 5 2018 base
drwx------. 2 postgres postgres 4.0K Nov 2 02:42 global
drwx------. 2 postgres postgres 18 Dec 27 2017 pg_clog
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_commit_ts
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_dynshmem
-rw-------. 1 postgres postgres 4.4K Dec 27 2017 pg_hba.conf
-rw-------. 1 postgres postgres 1.6K Dec 27 2017 pg_ident.conf
drwx------. 4 postgres postgres 39 Dec 27 2017 pg_logical
drwx------. 4 postgres postgres 36 Dec 27 2017 pg_multixact
drwx------. 2 postgres postgres 18 Nov 2 02:42 pg_notify
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_replslot
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_serial
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_snapshots
drwx------. 2 postgres postgres 6 Sep 16 21:15 pg_stat
drwx------. 2 postgres postgres 63 Nov 8 02:41 pg_stat_tmp
drwx------. 2 postgres postgres 18 Oct 24 2018 pg_subtrans
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_tblspc
drwx------. 2 postgres postgres 6 Dec 27 2017 pg_twophase
-rw-------. 1 postgres postgres 4 Dec 27 2017 PG_VERSION
drwx------. 3 postgres postgres 92 Dec 20 2018 pg_xlog
-rw-------. 1 postgres postgres 88 Dec 27 2017 postgresql.auto.conf
-rw-------. 1 postgres postgres 21K Dec 27 2017 postgresql.conf
-rw-------. 1 postgres postgres 37 Nov 2 02:42 postmaster.opts
-rw-------. 1 postgres postgres 85 Nov 2 02:42 postmaster.pid
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
Explore the folder where your website is store and see you will get one extra folder "aspnet_client" delete that folder and it will work for you.
I tried this my problem is solved.
If it works for you please make it as answer so that some body else will also get solution.
Not sure if you can do this with MySQL, but you can use a CTE in T-SQL
; WITH tmpPeople AS (
SELECT
DISTINCT(FirstName),
MIN(Id)
FROM People
)
SELECT
tP.Id,
tP.FirstName,
P.LastName
FROM tmpPeople tP
JOIN People P ON tP.Id = P.Id
Otherwise you might have to use a temporary table.
As pointed out in another answer and as you can read in PEP 3140, str
on a list
calls for each item __repr__
. There is not much you can do about that part.
If you implement __repr__
, you will get something more descriptive, but if implemented correctly, not exactly what you expected.
The fast, but wrong solution is to alias __repr__
to __str__
.
__repr__
should not be set to __str__
unconditionally. __repr__
should create a representation, that should look like a valid Python expression that could be used to recreate an object with the same value. In this case, this would rather be Node(2)
than 2
.
A proper implementation of __repr__
makes it possible to recreate the object. In this example, it should also contain the other significant members, like neighours
and distance
.
An incomplete example:
class Node:
def __init__(self, id, neighbours=[], distance=0):
self.id = id
self.neighbours = neighbours
self.distance = distance
def __str__(self):
return str(self.id)
def __repr__(self):
return "Node(id={0.id}, neighbours={0.neighbours!r}, distance={0.distance})".format(self)
# in an elaborate implementation, members that have the default
# value could be left out, but this would hide some information
uno = Node(1)
due = Node(2)
tri = Node(3)
qua = Node(4)
print uno
print str(uno)
print repr(uno)
uno.neighbours.append([[due, 4], [tri, 5]])
print uno
print uno.neighbours
print repr(uno)
Note: print repr(uno)
together with a proper implementation of __eq__
and __ne__
or __cmp__
would allow to recreate the object and check for equality.
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
Try this:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
You can also do like this :
$("#table-filters li").parent().find('li').removeClass("active");
String is a special class in Java. It is Thread Safe which means "Once a String instance is created, the content of the String instance will never changed ".
Here is what is going on for
zText += "foo";
First, Java compiler will get the value of zText String instance, then create a new String instance whose value is zText appending "foo". So you know why the instance that zText point to does not changed. It is totally a new instance. In fact, even String "foo" is a new String instance. So, for this statement, Java will create two String instance, one is "foo", another is the value of zText append "foo". The rule is simple: The value of String instance will never be changed.
For method fillString, you can use a StringBuffer as parameter, or you can change it like this:
String fillString(String zText) {
return zText += "foo";
}
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs
to be the result of the .map()
I just pushed the values into an array.
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = [];
$("#find-table input:checkbox:checked").map(function(){
searchIDs.push($(this).val());
});
console.log(searchIDs);
});
I created a fiddle with the code running.
If there is space between the letters of the font, you need to use quote.
font-family:"Calibri (Body)";
If you really want to use Xcode on linux you could get Virtual Box and install Hackintosh on a VM. Edit: Virtual Box Guest Additions is not supported with MacOS Movaje. You will want to use VMware
By using this code, you'll get your live time zone.
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
This is what the difference i found. Please let me know if any .
heroku ps:restart [web|worker] --app app_name
works for all processes declared in your Procfile. So if you have multiple web processes or worker processes, each labeled with a number, you can selectively restart one of them:
heroku ps:restart web.2 --app app_name
heroku ps:restart worker.3 --app app_name
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
Here other solution to only unlock the blocked user. From your command prompt log as SYSDBA:
sqlplus "/ as sysdba"
Then type the following command:
alter user <your_username> account unlock;
There is a plugin called show functions which lists all the function definitions in a file. It also allows you to sort the function so can search them easily.
Since there are so many ways to delete a word, let's illustrate them.
Assuming you edit:
foo-bar quux
and invoke a command while the cursor is on the 'a' in 'bar':
foo-bquux # dw: letters then spaces right of cursor
foo-quux # daw: letters on both sides of cursor then spaces on the right
foo- quux # diw: letters on both sides of cursor
foo-bquux # dW: non-whitespace then spaces right of cursor
quux # daW: non-whitespace on both sides of cursor then spaces on the right
quux # diW: non-whitespace on both sides of cursor
Alternatively, this solution works with both Apache2 version < 2.4 as well as >= 2.4. Make sure that the "version" module is enabled:
a2enmod version
And then use this code instead:
<IfVersion < 2.4>
Allow from all
</IfVersion>
<IfVersion >= 2.4>
Require all granted
</IfVersion>
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.
HTML:
<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />
JavaScript:
var counter = 0;
$("#SubtractDay").click(function() {
counter--;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
counter++;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
That library does a lot of work concerning overlap, intersecting them, etc. It's too big to copy/paste all of it, but I'll see which specific parts which can be useful to you.
To complete Wiktor Stribizew and Dougui answers I would say that /regex/.match?("string")
about as fast as "string".match?(/regex/)
.
Ruby 2.4.0 (10 000 000 ~2 sec)
2.4.0 > require 'benchmark'
=> true
2.4.0 > Benchmark.measure{ 10000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
=> #<Benchmark::Tms:0x005563da1b1c80 @label="", @real=2.2060338060000504, @cstime=0.0, @cutime=0.0, @stime=0.04000000000000001, @utime=2.17, @total=2.21>
2.4.0 > Benchmark.measure{ 10000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
=> #<Benchmark::Tms:0x005563da139eb0 @label="", @real=2.260814556000696, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=2.2500000000000004, @total=2.2600000000000007>
Ruby 2.6.2 (100 000 000 ~20 sec)
irb(main):001:0> require 'benchmark'
=> true
irb(main):005:0> Benchmark.measure{ 100000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
=> #<Benchmark::Tms:0x0000562bc83e3768 @label="", @real=24.60139879199778, @cstime=0.0, @cutime=0.0, @stime=0.010000999999999996, @utime=24.565644999999996, @total=24.575645999999995>
irb(main):004:0> Benchmark.measure{ 100000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
=> #<Benchmark::Tms:0x0000562bc846aee8 @label="", @real=24.634255946999474, @cstime=0.0, @cutime=0.0, @stime=0.010046, @utime=24.598276, @total=24.608321999999998>
Note: times varies, sometimes /regex/.match?("string")
is faster and sometimes "string".match?(/regex/)
, the differences maybe only due to the machine activity.
There is no difference. The $_SERVER['PHP_SELF'] just makes the execution time slower by like 0.000001 second.
Try this:
<meta http-equiv="refresh" content="5;URL= your url">
or
<meta http-equiv="refresh" content="5">
I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.
It works (refreshes the graphs) if I put
plt.clf()
plt.cla()
plt.close()
after every plt.show()
You are using this :
mysql_fetch_array($result)
To get the error you're getting, it means that $result
is not a resource.
In your code, $result
is obtained this way :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
If the SQL query fails, $result
will not be a resource, but a boolean -- see mysql_query
.
I suppose there's an error in your SQL query -- so it fails, mysql_query
returns a boolean, and not a resource, and mysql_fetch_array
cannot work on that.
You should check if the SQL query returns a result or not :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
// use $result
} else {
// an error has occured
echo mysql_error();
die; // note : echoing the error message and dying
// is OK while developping, but not in production !
}
With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)
Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !
For example, here, you should make sure that $_GET['id']
contains nothing else than an integer, using something like this :
$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
Or you should check this before trying to execute the query, to display a nicer error message to the user.
late in the game , but this worked for me:
$("#container>table>tbody>tr:first").trigger('click');
Use tput
to calculate color codes. Avoid using the ANSI escape code (e.g. \E[31;1m
for red) because it's less portable. Bash on OS X, for example, does not support it.
BLACK=`tput setaf 0`
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 5`
CYAN=`tput setaf 6`
WHITE=`tput setaf 7`
BOLD=`tput bold`
RESET=`tput sgr0`
echo -e "hello ${RED}some red text${RESET} world"
One option is to directly input the character you're interested in using hex or octal notation:
printf "\x41\n"
printf "\101\n"
Clean and simple:
<form action="/myaction" method="post" target="_blank">
<!-- other elements -->
<a href="#" onclick="this.parentNode.submit();">Submit</a>
</form>
In case of opening form action
url in a new tab (target="_blank"
):
<form action="/myaction" method="post" target="_blank">
<!-- other elements -->
<a href="#" onclick="this.parentNode.submit();">Submit</a>
</form>
Just add the percentage value into a variable and use #{$variable}
for example
$twentyFivePercent:25%;
.selector {
height: calc(#{$twentyFivePercent} - 5px);
}
While setting up log4j properly is great for "real" projects you might want a quick-and-dirty solution, e.g. if you're just testing a new library.
If so a call to the static method
org.apache.log4j.BasicConfigurator.configure();
will setup basic logging to the console, and the error messages will be gone.
The for loop can only contain three parameters, you have used 4. Please restate the question, what do you want to achieve?
The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.
Since version 1.0.0
you define optional parameters with:
<Route path="to/page(/:pathParam)" component={MyPage} />
and for multiple optional parameters:
<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />
You use parenthesis (
)
to wrap the optional parts of route, including the leading slash (/
). Check out the Route Matching Guide page of the official documentation.
Note: The :paramName
parameter matches a URL segment up to the next /
, ?
, or #
. For more about paths and params specifically, read more here.
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
Instead, you are instructed to define a path
parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?
).
As such, to define an optional parameter, you do:
<Route path="/to/page/:pathParam?" component={MyPage} />
and for multiple optional parameters:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
Try this piece of code, rather than ObjectInputStream
.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.
You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.
You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);
final Button btn3 = (Button) findViewById(R.id.btnVisibility);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.INVISIBLE);
bt3.setOnClickListener(new View.OnCLickListener(){
@Override
public void onClick(View view)
{
dp2.setVisibility(View.VISIBLE);
bt2.setVisibility(View.VISIBLE);
}
});
}
I think this should work easily. Hope this helps.
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[@name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
From what I know, it's highly recommended NOT to use the Finalizer / Destructor:
public ~MyClass() {
//dont use this
}
Mostly, this is due to not knowing when or IF it will be called. The dispose method is much better, especially if you us using or dispose directly.
using is good. use it :)
I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain
taken from NSURLError.h
/*!
@enum NSURL-related Error Codes
@abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};
You don't have to do this locally either. You can do it through a remote repository, for example:
svn export http://<repo>/process/test.txt /path/to/code/
I am using httpclient 4.4.
For solr query I used the following way and it worked.
NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
request.setURI(uri);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
respStr = respStr + output;
System.out.println(output);
}
I came to this post because I had the same error.
In my case the database evolutions weren't been executed, so the table wasn't there at all.
My problem was that the folder structure for the evolution scripts was wrong.
from: https://www.playframework.com/documentation/2.0/Evolutions
Play tracks your database evolutions using several evolutions script. These scripts are written in plain old SQL and should be located in the conf/evolutions/{database name} directory of your application. If the evolutions apply to your default database, this path is conf/evolutions/default.
I had a folder called conf/evolutions.default created by eclipse. The issue disappeared after I corrected the folder structure to conf/evolutions/default
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
How about setInterval, to check for complete iteration count, brings guarantee. not sure if it won't overload the scope though but I use it and seems to be the one
_.forEach(actual_JSON, function (key, value) {
// run any action and push with each iteration
array.push(response.id)
});
setInterval(function(){
if(array.length > 300) {
callback()
}
}, 100);
Unfortunately (or fortunately) not. The cross-domain policy is there for a reason, if it were easy to get around it then it wouldn't be very effective as a security measure. Other than JSONP, the only option is to proxy the pages using your own server.
With an iframe, they are subject to the same policy. Of course you can display the data from an external domain, you just can't manipulate it.
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.