Embarrassingly, the problem in my case is that I haven't rebuilt the code after adding the controller.
So maybe the first thing to check is that your controller was built and is present (and public) in the binaries. It might save you few minutes of debugging if you're like me.
index()
method from your controllergoto view
if this action open index.cshtml?
Your problem is the IIS pool is not have permission to access the physical path of the view.
you can test it by giving permission. for example :- go to c:\inetpub\wwwroot\yourweb
then right click on yourweb folder -> property ->security and add group name everyone and allow full control to your site . hope this fix your problem.
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* @author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* @param s
* @return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* @param c
* @return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* @param c
* @return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.
When working collaboratively, or on multiple features at once, it's common that the upstream or even your master contains work that is not included in your branch, and will incorrectly appear in basic diffs.
If your Upstream may have moved, you should do this:
git fetch
git diff origin/master...
Just using git diff master can include, or fail to include, relevant changes.
There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.
In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.
Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.
There is nothing wrong with syntax of
$('#part' + number).html(text);
jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.
In your case you should pass a String to $()
that is
$(<a string>)
Make sure you have access to the variables number
and text
.
To test do:
function(){
alert(number + ":" + text);//or use console.log(number + ":" + text)
$('#part' + number).html(text);
});
If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.
Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:
if(Object.values == null) {
Object.values = function(obj) {
var arr, o;
arr = new Array();
for(o in obj) { arr.push(obj[o]); }
return arr;
}
}
Another option is to put the ListItems into an array and sort.
int i = 0;
string[] array = new string[items.Count];
foreach (ListItem li in dropdownlist.items)
{
array[i] = li.ToString();
i++;
}
Array.Sort(array);
dropdownlist.DataSource = array;
dropdownlist.DataBind();
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.
e.g.
Given a table created like :
create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())
The following should always work :
update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
The following will work :
SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1
However, this won't :
SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1
This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .
The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.
More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
If you prefer a code with a pretty look, you can do a break:
for(int j = 0; ; j++){
if(j < 6
&& j < ( (int) abc[j] & 0xff)){
break;
}
// Put your code here
}
A few ways to extend String.prototype
, or use ES2015 template literals.
var result = document.querySelector('#result');_x000D_
// -----------------------------------------------------------------------------------_x000D_
// Classic_x000D_
String.prototype.format = String.prototype.format ||_x000D_
function () {_x000D_
var args = Array.prototype.slice.call(arguments);_x000D_
var replacer = function (a){return args[a.substr(1)-1];};_x000D_
return this.replace(/(\$\d+)/gm, replacer)_x000D_
};_x000D_
result.textContent = _x000D_
'hello $1, $2'.format('[world]', '[how are you?]');_x000D_
_x000D_
// ES2015#1_x000D_
'use strict'_x000D_
String.prototype.format2 = String.prototype.format2 ||_x000D_
function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };_x000D_
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');_x000D_
_x000D_
// ES2015#2: template literal_x000D_
var merge = ['[good]', '[know]'];_x000D_
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
_x000D_
<pre id="result"></pre>
_x000D_
I had the same issue of accessing localhost while working with virtualHost. I resolved it by adding the name in the virtualHost listen code like below:
In my hosts file, I have added the below code (C:\Windows\System32\drivers\etc\hosts) -
127.0.0.1 main_live
And in my httpd.conf I have added the below code:
<VirtualHost main_live:80>
DocumentRoot H:/wamp/www/raj/main_live/
ServerName main_live
</VirtualHost>
That's it. It works, and I can use both localhost, phpmyadmin, as well as main_live (my virtual project) simultaneously.
For me was not working so worked this way:
Controller:
int selectedId = 1;
ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);
View:
@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)
JQuery:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});
Properties have values only in objects, not classes.
If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static
in the implementation file.
You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.
Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool
in Cocoa.
Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:
Implementors should be aware that this specification is not stable.
Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.
Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.
In vim type
:help vimrc
and check your path to the _vimrc/.vimrc file with
:echo $HOME
:echo $VIM
Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.
:help source
Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
SWIFT 4
In Swift 4 you can use GCDs dispatch queues to lock resources.
class MyObject {
private var internalState: Int = 0
private let internalQueue: DispatchQueue = DispatchQueue(label:"LockingQueue") // Serial by default
var state: Int {
get {
return internalQueue.sync { internalState }
}
set (newState) {
internalQueue.sync { internalState = newState }
}
}
}
Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.
In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.
$('#root')
.append(html)
.ready(function () {
// enter code here
});
You could also use a LEFT JOIN and IS NULL condition:
SELECT
mac,
creation_date
FROM
logs
LEFT JOIN consols ON logs.mac = consols.mac
WHERE
logs_type_id=11
AND
consols.mac IS NULL;
An index on the "mac" columns might improve performance.
Use is
when you want to check against an object's identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, you're checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
For those that come here using MariaDB:
Note that MariaDB allows DROP CONSTRAINT statements in general, for example for dropping check constraints:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
<TextInput
keyboardType = 'numeric'
onChangeText = {(e)=> this.onTextChanged(e)}
value = {this.state.myNumber}
/>
onTextChanged(e) {
if (/^\d+$/.test(e.toString())) {
this.setState({ myNumber: e });
}
}
<TextInput
keyboardType = 'numeric'
onChangeText = {(e)=> this.validations(e)}
value = {this.state.myNumber}
/>
numbersOnly(e) {
return /^\d+$/.test(e.toString()) ? true : false
}
notZero(e) {
return /0/.test(parseInt(e)) ? false : true
}
validations(e) {
return this.notZero(e) && this.numbersOnly(e)
? this.setState({ numColumns: parseInt(e) })
: false
}
In order to replace text using regular expression use the re.sub function:
sub(pattern, repl, string[, count, flags])
It will replace non-everlaping instances of pattern
by the text passed as string
. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string
argument. more info here.
Examples
>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'
>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'
GridView.Columns.Count
will always be 0 when your GridView has its AutoGenerateColumns
property set to true
(default is true
).
You can explicitly declare your columns and set the AutoGenerateColumns
property to false
, or you can use this in your codebehind:
GridView.Rows[0].Cells.Count
to get the column count once your GridView data has been bound, or this:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[index].Visible = false;
}
to set a column invisible using your GridView's RowDataBound
event.
Yes you can.
You need to add in the first controller:
YourController controller = loader.getController();
controller.setclient(client);
Then in the second one declare a client, then at the bottom of your controller:
public void setclien(Client c) {
this.client = c;
}
There is an example at the end of the csv module documentation that demonstrates how to deal with Unicode. Below is copied directly from that example. Note that the strings read or written will be Unicode strings. Don't pass a byte string to UnicodeWriter.writerows
, for example.
import csv,codecs,cStringIO
class UTF8Recoder:
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
'''next() -> unicode
This function reads and returns the next line as a Unicode string.
'''
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
'''writerow(unicode) -> None
This function takes a Unicode string and encodes it to the output.
'''
self.writer.writerow([s.encode("utf-8") for s in row])
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
with open('xxx.csv','rb') as fin, open('lll.csv','wb') as fout:
reader = UnicodeReader(fin)
writer = UnicodeWriter(fout,quoting=csv.QUOTE_ALL)
for line in reader:
writer.writerow(line)
Input (UTF-8 encoded):
American,???
French,???
German,???
Output:
"American","???"
"French","???"
"German","???"
SELECT *
FROM testcases1 t
WHERE NOT EXISTS (
SELECT 1
FROM executions1 i
WHERE t.tc_id = i.tc_id and t.pro_id=i.pro_id and pro_id=7 and version_id=5
) and pro_id=7 ;
Here testcases1 table contains all datas and executions1 table contains some data among testcases1 table. I am retrieving only the datas which are not present in exections1 table. ( and even I am giving some conditions inside that you can also give.) specify condition which should not be there in retrieving data should be inside brackets.
Starting from Java 8, you can also use parallelSort
which is useful if you have arrays containing a lot of elements.
Example:
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "b", "y" };
Arrays.parallelSort(strings);
System.out.println(Arrays.toString(strings)); // [a, b, c, x, y]
}
If you want to ignore the case, you can use:
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "B", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(Arrays.toString(strings)); // [a, B, c, x, y]
}
otherwise B
will be before a
.
If you want to ignore the trailing spaces during the comparison, you can use trim()
:
public static void main(String[] args) {
String[] strings = { "x", " a", "c ", " b", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.trim().compareTo(o2.trim());
}
});
System.out.println(Arrays.toString(strings)); // [ a, b, c , x, y]
}
See:
This worked for me, and it also remembers my credentials:
Run gitbash
Point to the repo directory
Run git config --global credential.helper wincred
Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})
$.ajax({
dataType : 'json',
type : 'POST',
contentType : 'application/json',
url : '<%=request.getContextPath()%>/rest/priceGroups',
data : JSON.stringify({data : param}),
success : function(res) {
if(res.success == true){
$('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
$('#alertMessage').removeClass('alert-danger alert-info');
initPriceGroupsList();
priceGroupId = 0;
resetForm();
}else{
$('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
}
$('#alertMessage').alert();
window.setTimeout(function() {
$('#alertMessage').removeClass('in');
document.getElementById('message').style.display = 'none';
}, 5000);
}
});
I think you can use typeahead.js
. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.
Yes, with set_index you can make Locality
your row index.
data.set_index('Locality', inplace=True)
If inplace=True
is not provided, set_index
returns the modified dataframe as a result.
Example:
> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
> df.loc['ABBOTSFORD'].values
array([427000, 448000])
> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
For very large files I'd do something like this
string tempFile = Path.GetTempFileName();
using(var sr = new StreamReader("file.txt"))
using(var sw = new StreamWriter(tempFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
if(line != "removeme")
sw.WriteLine(line);
}
}
File.Delete("file.txt");
File.Move(tempFile, "file.txt");
Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution
var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(fileName);
File.Move(tempFile, fileName);
The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.
A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.
File.WriteAllLines(fileName,
File.ReadLines(fileName).Where(l => l != "removeme").ToList());
Note that The .ToList
is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.
I was wondering about this specifically for building software in Debian (the installed Debian system can be a 32-bit version with a 32 bit kernel, libraries, etc., or it can be a 64-bit version with stuff compiled for the 64-bit rather than 32-bit compatibility mode).
Debian packages themselves need to know what architecture they are for (of course) when they actually create the package with all of its metadata, including platform architecture, so there is a packaging tool that outputs it for other packaging tools and scripts to use, called dpkg-architecture. It includes both what it's configured to build for, as well as the current host. (Normally these are the same though.) Example output on a 64-bit machine:
DEB_BUILD_ARCH=amd64
DEB_BUILD_ARCH_OS=linux
DEB_BUILD_ARCH_CPU=amd64
DEB_BUILD_GNU_CPU=x86_64
DEB_BUILD_GNU_SYSTEM=linux-gnu
DEB_BUILD_GNU_TYPE=x86_64-linux-gnu
DEB_HOST_ARCH=amd64
DEB_HOST_ARCH_OS=linux
DEB_HOST_ARCH_CPU=amd64
DEB_HOST_GNU_CPU=x86_64
DEB_HOST_GNU_SYSTEM=linux-gnu
DEB_HOST_GNU_TYPE=x86_64-linux-gnu
You can print just one of those variables or do a test against their values with command line options to dpkg-architecture.
I have no idea how dpkg-architecture deduces the architecture, but you could look at its documentation or source code (dpkg-architecture and much of the dpkg system in general are Perl).
Have you tried
git add .
This recurses into sub-directories, whereas I don't think * does.
See here
With the new Tensorflow 2.1 release, the default tensorflow
pip package contains both CPU and GPU versions of TF. In previous TF versions, not finding the CUDA libraries would emit an error and raise an exception, while now the library dynamically searches for the correct CUDA version and, if it doesn't find it, emits the warning (The W in the beginning stands for warnings, errors have an E (or F for fatal errors) and falls back to CPU-only mode. In fact, this is also written in the log as an info message right after the warning (do note that if you have a higher minimum log level that the default, you might not see info messages). The full log is (emphasis mine):
2020-01-20 12:27:44.554767: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-01-20 12:27:44.554964: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
If you don't have a CUDA-enabled GPU on your machine, or if you don't care about not having GPU acceleration, no need to worry. If, on the other hand, you installed tensorflow and wanted GPU acceleration, check your CUDA installation (TF 2.1 requires CUDA 10.1, not 10.2 or 10.0).
If you just want to get rid of the warning, you can adapt TF's logging level to suppress warnings, but that might be overkill, as it will silence all warnings.
Your CUDA setup is broken, ensure you have the correct version installed.
uint
and ulong
are the unsigned versions of int
and long
. That means they can't be negative. Instead they have a larger maximum value.
Type Min Max CLS-compliant int -2,147,483,648 2,147,483,647 Yes uint 0 4,294,967,295 No long –9,223,372,036,854,775,808 9,223,372,036,854,775,807 Yes ulong 0 18,446,744,073,709,551,615 No
To write a literal unsigned int in your source code you can use the suffix u
or U
for example 123U
.
You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.
Read the documentation for more information:
By the way, there is also short and ushort and byte and sbyte.
Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.
And anything by Robert Sedgewick is good too.
You just need to have a module that exports a history
object. Then you would import that object throughout your project.
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory({
/* pass a configuration object here if needed */
})
Then, instead of using one of the built-in routers, you would use the <Router>
component.
// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'
ReactDOM.render((
<Router history={history}>
<App />
</Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')
HTML:
<div id="left"></div>
<div id="content">
<textarea cols="2" rows="10" id="rules"></textarea>
</div>
CSS:
body{
width:100%;
border:1px solid black;
border-radius:5px;
}
#left{
width:20%;
height:400px;
float:left;
border: 1px solid black;
display:block;
}
#content{
width:78%;
height:400px;
float:left;
border:1px solid black;
text-align:center;
}
textarea
{
margin-top:100px;
width:98%;
}
DEMO: HERE
In my case, jvmTarget was already set in build.gradle
file as below.
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
But my issue was still there. Finally, it gets resolved after Changing Target JVM version from 1.6 to 1.8 in Preferences > Other Settings > Kotlin Compiler > Target JVM version. see attached picture,
create user ro_role identified by ro_role;
grant create session, select any table, select any dictionary to ro_role;
Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double
, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double
with 15 decimal places and the convert it back to a double
, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double
. In general, you need over 100 decimal places to do that precisely.
See the Wikipedia page for double-precision and this article on floating-point precision.
To check if a Variant
is Null, you need to do it like:
Isnull(myvar) = True
or
Not Isnull(myvar)
On a related note, if you want to get the int
value from System.Enum
, then given e
here:
Enum e = Question.Role;
You can use:
int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);
The last two are plain ugly. I prefer the first one.
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
.img-wrap:hover img {_x000D_
transform: scale(0.8);_x000D_
}_x000D_
.img-wrap img {_x000D_
display: block;_x000D_
transition: all 0.3s ease 0s;_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="img-wrap">_x000D_
<img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
</div>
_x000D_
This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);
The tag in web.config is based on paths, whereas MVC works with controller actions and routes.
It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.
The first case is covered from the answer of BobRock.
The user should have at least one of the following Roles to access the Controller or the Action
[Authorize(Roles = "Admin, Super User")]
The user should have both these roles in order to be able to access the Controller or Action
[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]
The users that can access the Controller or the Action are Betty and Johnny
[Authorize(Users = "Betty, Johnny")]
In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize]
.
options.AddPolicy("ElevatedRights", policy =>
policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));
[Authorize(Policy = "ElevatedRights")]
The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.
public class CustomAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{ }
}
The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize]
attribute.
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
For a period I had to extract the Media ID myself quite frequently, so I wrote my own script (very likely it's based on some of the examples here). Together with other small scripts I used frequently, I started to upload them on www.findinstaid.com for my own quick access.
I added the option to enter a username to get the media ID of the 12 most recent posts, or to enter a URL to get the media ID of a specific post.
If it's convenient, everyone can use the link (I don't have any adds or any other monetary interests in the website - I only have a referral link on the 'Audit' tab to www.auditninja.io which I do also own, but also on this site, there are no adds or monetary interests - just hobby projects).
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
You can set up a express proxy server using http-proxy-middleware to bypass CORS:
const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.use('/proxy', proxy({
pathRewrite: {
'^/proxy/': '/'
},
target: 'https://server.com',
secure: false
}));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);
console.log('Server started');
From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.
const URL = `/proxy/${PATH}`;
return axios.get(URL);
Try this:
<?php
$servername = "localhost";
$database = "database";
$username = "user";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
you could try to create the same script that popups that error, dividing the script into several script by importing from external script. Example, hello.py expect an error Memory error, so i divide hello.py into several scripts h.py e.py ll.py o.py all of them have to get into a folder "hellohello" into that folder create init.py into init write import h,e,ll,o and then on ide you write import hellohello
Python's if
can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
First, check that whatever you are returning via unicode is a String.
If it is not a string you can change it to a string like this (where self.id is an integer)
def __unicode__(self):
return '%s' % self.id
following which, if it still doesn't work, restart your ./manage.py shell for the changes to take effect and try again. It should work.
Best Regards
Always check your build configuration if you you are running your app with debug or release.
IMPORTANT NOTE: You can't be able to test it without running your app in debug mode
This was my solution
http://api.jqueryui.com/datepicker/#option-maxDate
$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );
For Saturday and Sunday You can do something like this
$('#orderdate').datepicker({
daysOfWeekDisabled: [0,6]
});
We are using Akka in a large scale Telco project (unfortunately I can't disclose a lot of details). Akka actors are deployed and accessed remotely by a web application. In this way, we have a simplified RPC model based on Google protobuffer and we achieve parallelism using Akka Futures. So far, this model has worked brilliantly. One note: we are using the Java API.
Sadly, straight from google, which is where you will want to download if your company firewall blocks other sources, Release 1.6 r1 September 2009 is the latest SDK they have.
I've been troubled with this problem in web printing and solved. Verified result.
a {
text-decoration: none !important;
}
It works!.
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):
INSERT live-db.table1
SELECT *
FROM test-db.table1 t
ON DUPLICATE KEY UPDATE
ColToUpdate1 = t.ColToUpdate1,
ColToUpdate2 = t.ColToUpdate2,
...
As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE
.
No need to list the columns in the INSERT
or SELECT
, though I agree it's probably better practice.
You want $.param()
: http://api.jquery.com/jQuery.param/
Specifically, you want this:
var data = { one: 'first', two: 'second' };
var result = $.param(data);
When given something like this:
{a: 1, b : 23, c : "te!@#st"}
$.param
will return this:
a=1&b=23&c=te!%40%23st
Here's another example. I'm creating a QRCode as a PNG via a ByteArrayOutputStream
. The resource returns a Response
object, and the stream's data is the entity.
To illustrate the response code handling, I've added handling of cache headers (If-modified-since
, If-none-matches
, etc).
@Path("{externalId}.png")
@GET
@Produces({"image/png"})
public Response getAsImage(@PathParam("externalId") String externalId,
@Context Request request) throws WebApplicationException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// do something with externalId, maybe retrieve an object from the
// db, then calculate data, size, expirationTimestamp, etc
try {
// create a QRCode as PNG from data
BitMatrix bitMatrix = new QRCodeWriter().encode(
data,
BarcodeFormat.QR_CODE,
size,
size
);
MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
} catch (Exception e) {
// ExceptionMapper will return HTTP 500
throw new WebApplicationException("Something went wrong …")
}
CacheControl cc = new CacheControl();
cc.setNoTransform(true);
cc.setMustRevalidate(false);
cc.setNoCache(false);
cc.setMaxAge(3600);
EntityTag etag = new EntityTag(HelperBean.md5(data));
Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(
updateTimestamp,
etag
);
if (responseBuilder != null) {
// Preconditions are not met, returning HTTP 304 'not-modified'
return responseBuilder
.cacheControl(cc)
.build();
}
Response response = Response
.ok()
.cacheControl(cc)
.tag(etag)
.lastModified(updateTimestamp)
.expires(expirationTimestamp)
.type("image/png")
.entity(stream.toByteArray())
.build();
return response;
}
Please don't beat me up in case stream.toByteArray()
is a no-no memory wise :) It works for my <1KB PNG files...
We ended up realising that our one server that was experiencing this had busted fpm config resulting in php errors/warnings/notices that'd normally be logged to disk were being sent over the FCGI socket. It looks like there's a parsing bug when part of the header gets split across the buffer chunks.
So setting php_admin_value[error_log]
to something actually writeable and restarting php-fpm was enough to fix the problem.
We could reproduce the problem with a smaller script:
<?php
for ($i = 0; $i<$_GET['iterations']; $i++)
error_log(str_pad("a", $_GET['size'], "a"));
echo "got here\n";
Raising the buffers made the 502s harder to hit but not impossible, e.g native:
bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=121 iterations=30 < HTTP/1.1 502 Bad Gateway
size=109 iterations=33 < HTTP/1.1 502 Bad Gateway
size=232 iterations=33 < HTTP/1.1 502 Bad Gateway
size=241 iterations=48 < HTTP/1.1 502 Bad Gateway
size=145 iterations=51 < HTTP/1.1 502 Bad Gateway
size=226 iterations=51 < HTTP/1.1 502 Bad Gateway
size=190 iterations=60 < HTTP/1.1 502 Bad Gateway
size=115 iterations=63 < HTTP/1.1 502 Bad Gateway
size=109 iterations=66 < HTTP/1.1 502 Bad Gateway
size=163 iterations=69 < HTTP/1.1 502 Bad Gateway
[... there would be more here, but I piped through head ...]
fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;
:
bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=223 iterations=69 < HTTP/1.1 502 Bad Gateway
size=184 iterations=165 < HTTP/1.1 502 Bad Gateway
size=151 iterations=198 < HTTP/1.1 502 Bad Gateway
So I believe the correct answer is: fix your fpm config so it logs errors to disk.
By using event.key we can get values prior entry into HTML Input Text Box. Here is the code.
function checkText()_x000D_
{_x000D_
console.log("Value Entered which was prevented was - " + event.key);_x000D_
_x000D_
//Following will prevent displaying value on textbox_x000D_
//You need to use your validation functions here and return value true or false._x000D_
return false;_x000D_
}
_x000D_
<input type="text" placeholder="Enter Value" onkeypress="return checkText()" />
_x000D_
Could not load type MVCApplication1.MVCApplication
Problem: Web.Config might be corrupted because of some updates in the machine. When I compared the web.config with server web.config then I realized that all the basic configuration were missing like build providers, modules, handlers, namespaces etc.
Resolution: Replace the web.config from the below location with web.config from server from same location (application is running fine in server). C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
I have spent more than 10 days, hence I thought it might be helpful for someone.
#content h2:before {
content: "\f055";
font-family: FontAwesome;
left:0;
position:absolute;
top:0;
}
Example Link: https://codepen.io/bungeedesign/pen/XqeLQg
Get Icon code from: https://fontawesome.com/cheatsheet?from=io
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
Scan your workspace .metadata
directory for files called *.launch
. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core
one.
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
I created a small library that does this, no code change needed other than replacing your wrapping view and import of TextInput:
import { Form, TextInput } from 'react-native-autofocus'
export default () => (
<Form>
<TextInput placeholder="test" />
<TextInput placeholder="test 2" />
</Form>
)
https://github.com/zackify/react-native-autofocus
Explained in detail here: https://zach.codes/autofocus-inputs-in-react-native/
For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:
Take a look at the Google solution. Here is a deletion method only.
ListViewRemovalAnimation project code and Video demonstration
It needs Android 4.1+ (API 16). But we have 2014 outside.
I had the same issue. When I use window.location
, $window.location
or even <a href="..." target="_self">
the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload()
after window.location
to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:
$scope.openPage = function (pageName) {
window.location = '#/html/pages/' + pageName;
window.location.reload();
};
This can be addressed using the following LINQ expression:
var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));
An alternate way of expressing this via LINQ, which some developers find more readable:
var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));
Warning: As noted in the comments, these approaches mandate an O(n*m) operation. That may be fine, but could introduce performance issues, and especially if the data set is quite large. If this doesn't satisfy your performance requirements, you may need to evaluate other options. Since the stated requirement is for a solution in LINQ, however, those options aren't explored here. As always, evaluate any approach against the performance requirements your project might have.
If you want to enable CORS for all routes, then just install flask_cors extension (pip3 install -U flask_cors
) and wrap app
like this: CORS(app)
.
That is enough to do it (I tested this with a POST
request to upload an image, and it worked for me):
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # This will enable CORS for all routes
Important note: if there is an error in your route, let us say you try to print a variable that does not exist, you will get a CORS error related message which, in fact, has nothing to do with CORS.
You can use negated character classes to exclude certain characters: for example [^abcde]
will match anything but a,b,c,d,e characters.
Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w]
(lowercase) will match any "word character" (letter, numbers and underscore), [\W]
(uppercase) will match anything but word characters; similarly, [\d]
will match the 0-9 digits while [\D]
matches anything but the 0-9 digits, and so on.
If you use PHP you can take a look at the regex character classes documentation.
Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value
returns a desired DateTime
object.
public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
object cellValue = cell.Value;
if (cellValue is DateTime result)
{
return result;
}
return null;
}
$('#OvernightOnshore').click(function () {
if ($('#OvernightOnshore').prop("checked") == true) {
if ($('#OvernightOffshore').prop("checked") == true) {
$('#OvernightOffshore').attr('checked', false)
}
}
})
$('#OvernightOffshore').click(function () {
if ($('#OvernightOffshore').prop("checked") == true) {
if ($('#OvernightOnshore').prop("checked") == true) {
$('#OvernightOnshore').attr('checked', false);
}
}
})
This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.
There is a builtin environment: browser
that includes window
.
Example .eslintrc.json
:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
Also see the package.json
answer by chevin99 below.
You can use DBMS_PIPE.SEND_MESSAGE
with a message that is too large for the pipe, for example for a 5 second delay write XXX to a pipe that can only accept one byte using a 5 second timeout as below
dbms_pipe.pack_message('XXX');<br>
dummy:=dbms_pipe.send_message('TEST_PIPE', 5, 1);
But then that requires a grant for DBMS_PIPE
so perhaps no better.
This also could be easiest way to add items in ListBox.
for (int i = 0; i < MyList.Count; i++)
{
listBox1.Items.Add(MyList.ElementAt(i));
}
Further improvisation of this code can add items at runtime.
You may be using a low quality cable/defected cable to connect your device to the PC, I replaced the cable and it worked for me.
Here are two options, the first:
both <- list(first, second)
n <- unique(unlist(lapply(both, names)))
names(n) <- n
lapply(n, function(ni) unlist(lapply(both, `[[`, ni)))
and the second, which works only if they have the same structure:
apply(cbind(first, second),1,function(x) unname(unlist(x)))
Both give the desired result.
You can use
var modal_template_html = $.trim($('#modal_template').html());
var template = $(modal_template_html);
I came across this post
by Minko Gechev which clearly explains the major differences.
If you are using BookId as an combined primary key, then remember to change your interface from:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
to:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:
public class QueuedBook implements Serializable {
@EmbeddedId
@NotNull
private BookId bookId;
...
There is a easier way besides using the close() function. if you create a variable with the InfoWindow property it closes automatically when you open another.
var info_window;
var map;
var chicago = new google.maps.LatLng(33.84659, -84.35686);
function initialize() {
var mapOptions = {
center: chicago,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
info_window = new google.maps.InfoWindow({
content: 'loading'
)};
createLocationOnMap('Location Name 1', new google.maps.LatLng(33.84659, -84.35686), '<p><strong>Location Name 1</strong><br/>Address 1</p>');
createLocationOnMap('Location Name 2', new google.maps.LatLng(33.84625, -84.36212), '<p><strong>Location Name 1</strong><br/>Address 2</p>');
}
function createLocationOnMap(titulo, posicao, conteudo) {
var m = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
title: titulo,
position: posicao,
html: conteudo
});
google.maps.event.addListener(m, 'click', function () {
info_window.setContent(this.html);
info_window.open(map, this);
});
}
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -u root
try this way,I have been solved my problem with this method.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;
};
}, []);
setBackgroundResource(0)
is the best option. From the documentation:
Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.
It works everywhere, because it's since API 1.
setBackground
was added much later, in API 16, so it will not work if your minSdkVersion
is lower than 16.
$("#mydiv").css('top', 200);
$("#mydiv").css('left', 200);
Flex is the better way. Just try..
display: flex;
Try
$(document).on('change','#multiid',function(){
alert('Change Happened');
});
As your select-box is generated from the code, so you have to use event delegation, where in place of $(document)
you can have closest parent element.
Or
$(document.body).on('change','#multiid',function(){
alert('Change Happened');
});
Update:
Second one works fine, there is another change of selector to make it work.
$('#addbasket').on('change','#multiid',function(){
alert('Change Happened');
});
Ideally we should use $("#addbasket")
as it's the closest parent element [As i have mentioned above].
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
The way that worked for me is to use a bind
mount
version: "3.7"
services:
app:
image: app:latest
volumes:
- type: bind
source: ./sourceFile.yaml
target: /location/targetFile.yaml
Thanks mike breed for the answer over at: Mount single file from volume using docker-compose
You need to use the "long syntax" to express a bind
mount using the volumes
key: https://docs.docker.com/compose/compose-file/#long-syntax-3
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
Note: It's just a simple representation. Weighted Edges could be added like
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
--DROP TABLE #Employee
CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)
INSERT INTO #Employee VALUES('M11M','Manager',NULL)
INSERT INTO #Employee VALUES('P11P','Manager',NULL)
INSERT INTO #Employee VALUES('AA','Clerk',1)
INSERT INTO #Employee VALUES('AB','Assistant',1)
INSERT INTO #Employee VALUES('ZC','Supervisor',2)
INSERT INTO #Employee VALUES('ZD','Security',2)
SELECT * FROM #Employee (NOLOCK)
;
WITH Emp_CTE
AS
(
SELECT EmpId,EmpName,Designation, ManagerID
,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
FROM #Employee
)
select EmpId,EmpName,Designation, ManagerID
FROM Emp_CTE
order BY ManagerID_N, EmpId
If none of the above work (like in my case trying to center an input), I used Boostrap 4 offset:
<div class="row">
<div class="col-6 offset-3">
<input class="form-control" id="myInput" type="text" placeholder="Search..">
</div>
</div>
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
shift
spaces.Restrictions:
Pseudocode:
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
Building on dnlbrk's comment, assign can be considerably faster than list2env for big files.
library(readr)
library(stringr)
List_of_file_paths <- list.files(path ="C:/Users/Anon/Documents/Folder_with_csv_files/", pattern = ".csv", all.files = TRUE, full.names = TRUE)
By setting the full.names argument to true, you will get the full path to each file as a separate character string in your list of files, e.g., List_of_file_paths[1] will be something like "C:/Users/Anon/Documents/Folder_with_csv_files/file1.csv"
for(f in 1:length(List_of_filepaths)) {
file_name <- str_sub(string = List_of_filepaths[f], start = 46, end = -5)
file_df <- read_csv(List_of_filepaths[f])
assign( x = file_name, value = file_df, envir = .GlobalEnv)
}
You could use the data.table package's fread or base R read.csv instead of read_csv. The file_name step allows you to tidy up the name so that each data frame does not remain with the full path to the file as it's name. You could extend your loop to do further things to the data table before transferring it to the global environment, for example:
for(f in 1:length(List_of_filepaths)) {
file_name <- str_sub(string = List_of_filepaths[f], start = 46, end = -5)
file_df <- read_csv(List_of_filepaths[f])
file_df <- file_df[,1:3] #if you only need the first three columns
assign( x = file_name, value = file_df, envir = .GlobalEnv)
}
I think what you need might be simply:
\d( \w)?
Note that your regex would have worked too if it was written as \d \w|\d
instead of \d|\d \w
.
This is because in your case, once the regex matches the first option, \d
, it ceases to search for a new match, so to speak.
Simple Oriented Object solution
$file = new \SplFileObject('file.extension');
while($file->valid()) $file->fgets();
var_dump($file->key());
Another way to make this is with PHP_INT_MAX
in SplFileObject::seek
method.
$file = new \SplFileObject('file.extension', 'r');
$file->seek(PHP_INT_MAX);
echo $file->key() + 1;
Right click on the circles +/- sign and under Foldings select Collapse All
This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.
ViewModel looks like this:
public class MyViewModel
{
public List<Person> Persons{get;set;}
}
View(with BeginForm of course):
@model MyViewModel
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
Action:
[HttpPost]public ViewResult(MyViewModel vm)
{
...
Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.
Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
if(i != 4)//conditionally hide 5th item,
{ //but BUG occurs on postback, all items after 5th will not be bound to the the list
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
}
A solution improving on the great one from @sparrow.
Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.
Let's suppose you want to call your new column simply, new_column
First make the list into a Series:
column_values = pd.Series(mylist)
Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)
df.insert(loc=0, column='new_column', value=column_values)
We recently encountered this and discovered that promoting the affected element to a composite layer with translateZ fixed the issue without needing extra javascript.
.willnotrender {
transform: translateZ(0);
}
As these painting issues show up mostly in Webkit/Blink, and this fix mostly targets Webkit/Blink, it's preferable in some cases. Especially since many JavaScript solutions cause a reflow and repaint, not just a repaint.
In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)
<script>
$(document).ready(function(){
GetData('DLState',data,'stateid','statename');
});
var data = [{"stateid" : "1","statename" : "Mumbai"},
{"stateid" : "2","statename" : "Panjab"},
{"stateid" : "3","statename" : "Pune"},
{"stateid" : "4","statename" : "Nagpur"},
{"stateid" : "5","statename" : "kanpur"}];
var Did=document.getElementById("DLState");
function GetData(Did,data,valkey,textkey){
var str= "";
for (var i = 0; i <data.length ; i++){
console.log(data);
str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";
}
$("#"+Did).append(str);
}; </script>
</head>
<body>
<select id="DLState">
</select>
</body>
</html>
To convert you PHP array to JS , you can do it like this :
var js_array = [<?php echo '"'.implode('","', $disabledDaysRange ).'"' ?>];
or using JSON_ENCODE :
var js_array =<?php echo json_encode($disabledDaysRange );?>;
Example without JSON_ENCODE:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
alert(js_array[0]);
</script>
Example with JSON_ENCODE :
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($disabledDaysRange );?>;
alert(js_array[0]);
</script>
How can I create a copy of an object in Python?
So, if I change values of the fields of the new object, the old object should not be affected by that.
You mean a mutable object then.
In Python 3, lists get a copy
method (in 2, you'd use a slice to make a copy):
>>> a_list = list('abc')
>>> a_copy_of_a_list = a_list.copy()
>>> a_copy_of_a_list is a_list
False
>>> a_copy_of_a_list == a_list
True
Shallow copies are just copies of the outermost container.
list.copy
is a shallow copy:
>>> list_of_dict_of_set = [{'foo': set('abc')}]
>>> lodos_copy = list_of_dict_of_set.copy()
>>> lodos_copy[0]['foo'].pop()
'c'
>>> lodos_copy
[{'foo': {'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
You don't get a copy of the interior objects. They're the same object - so when they're mutated, the change shows up in both containers.
Deep copies are recursive copies of each interior object.
>>> lodos_deep_copy = copy.deepcopy(list_of_dict_of_set)
>>> lodos_deep_copy[0]['foo'].add('c')
>>> lodos_deep_copy
[{'foo': {'c', 'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
Changes are not reflected in the original, only in the copy.
Immutable objects do not usually need to be copied. In fact, if you try to, Python will just give you the original object:
>>> a_tuple = tuple('abc')
>>> tuple_copy_attempt = a_tuple.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'copy'
Tuples don't even have a copy method, so let's try it with a slice:
>>> tuple_copy_attempt = a_tuple[:]
But we see it's the same object:
>>> tuple_copy_attempt is a_tuple
True
Similarly for strings:
>>> s = 'abc'
>>> s0 = s[:]
>>> s == s0
True
>>> s is s0
True
and for frozensets, even though they have a copy
method:
>>> a_frozenset = frozenset('abc')
>>> frozenset_copy_attempt = a_frozenset.copy()
>>> frozenset_copy_attempt is a_frozenset
True
Immutable objects should be copied if you need a mutable interior object copied.
>>> tuple_of_list = [],
>>> copy_of_tuple_of_list = tuple_of_list[:]
>>> copy_of_tuple_of_list[0].append('a')
>>> copy_of_tuple_of_list
(['a'],)
>>> tuple_of_list
(['a'],)
>>> deepcopy_of_tuple_of_list = copy.deepcopy(tuple_of_list)
>>> deepcopy_of_tuple_of_list[0].append('b')
>>> deepcopy_of_tuple_of_list
(['a', 'b'],)
>>> tuple_of_list
(['a'],)
As we can see, when the interior object of the copy is mutated, the original does not change.
Custom objects usually store data in a __dict__
attribute or in __slots__
(a tuple-like memory structure.)
To make a copyable object, define __copy__
(for shallow copies) and/or __deepcopy__
(for deep copies).
from copy import copy, deepcopy
class Copyable:
__slots__ = 'a', '__dict__'
def __init__(self, a, b):
self.a, self.b = a, b
def __copy__(self):
return type(self)(self.a, self.b)
def __deepcopy__(self, memo): # memo is a dict of id's to copies
id_self = id(self) # memoization avoids unnecesary recursion
_copy = memo.get(id_self)
if _copy is None:
_copy = type(self)(
deepcopy(self.a, memo),
deepcopy(self.b, memo))
memo[id_self] = _copy
return _copy
Note that deepcopy
keeps a memoization dictionary of id(original)
(or identity numbers) to copies. To enjoy good behavior with recursive data structures, make sure you haven't already made a copy, and if you have, return that.
So let's make an object:
>>> c1 = Copyable(1, [2])
And copy
makes a shallow copy:
>>> c2 = copy(c1)
>>> c1 is c2
False
>>> c2.b.append(3)
>>> c1.b
[2, 3]
And deepcopy
now makes a deep copy:
>>> c3 = deepcopy(c1)
>>> c3.b.append(4)
>>> c1.b
[2, 3]
One way could be by unchecking Bar Visibility "Shows Navigation Bar" In Attribute Inspector.Hope this help someone.
Either call cancel()
on the Timer
if that's all it's doing, or cancel()
on the TimerTask
if the timer itself has other tasks which you wish to continue.
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.
Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.
Use caTools package in R sample code will be as follows:-
data
split = sample.split(data$DependentcoloumnName, SplitRatio = 0.6)
training_set = subset(data, split == TRUE)
test_set = subset(data, split == FALSE)
Objects can be converted to a string using the toString()
method:
String myString = myIntegerObject.toString();
There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.
Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild
Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).
Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.
Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.
Publish to File System
The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.
This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:
<Target Name="PublishToFileSystem"
DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
<Error Condition="'$(PublishDestination)'==''"
Text="The PublishDestination property must be set to the intended publishing destination." />
<MakeDir Condition="!Exists($(PublishDestination))"
Directories="$(PublishDestination)" />
<ItemGroup>
<PublishFiles Include="$(_PackageTempDir)\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PublishFiles)"
DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="True" />
</Target>
This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.
The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.
We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).
To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):
msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem
I'd like to summarize status of the "spread object merge" ES feature, in browsers, and in the ecosystem via tools.
var x = { a: 1, b: 2 };
var y = { c: 3, d: 4, a: 5 };
var z = {...x, ...y};
console.log(z); // { a: 5, b: 2, c: 3, d: 4 }
Again: At time of writing this sample works without transpilation in Chrome (60+), Firefox Developer Edition (preview of Firefox 60), and Node (8.7+).
I'm writing this 2.5 years after the original question. But I had the very same question, and this is where Google sent me. I am a slave to SO's mission to improve the long tail.
Since this is an expansion of "array spread" syntax I found it very hard to google, and difficult to find in compatibility tables. The closest I could find is Kangax "property spread", but that test doesn't have two spreads in the same expression (not a merge). Also, the name in the proposals/drafts/browser status pages all use "property spread", but it looks to me like that was a "first principal" the community arrived at after the proposals to use spread syntax for "object merge". (Which might explain why it is so hard to google.) So I document my finding here so others can view, update, and compile links about this specific feature. I hope it catches on. Please help spread the news of it landing in the spec and in browsers.
Lastly, I would have added this info as a comment, but I couldn't edit them without breaking the authors' original intent. Specifically, I can't edit @ChillyPenguin's comment without it losing his intent to correct @RichardSchulte. But years later Richard turned out to be right (in my opinion). So I write this answer instead, hoping it will gain traction on the old answers eventually (might take years, but that's what the long tail effect is all about, after all).
SUMIF didn't worked for me, had to use SUMIFS.
=SUMIFS(TableAmount,TableMonth,"January")
TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.
Hope this can help someone!
In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.
Add the following accounts and privileges:
GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD
I adapted @shareef's answer to make it concise. I use,
.sort(function(arg1, arg2) { return arg1.length - arg2.length })
Yes! You can create a shortcut to cmd.exe with a command specified after it. Alternatively you could create a batch script, if your goal is just to have a clickable way to run commands.
Steps:
Right click on some empty space in Explorer, and in the context menu go to "New/Shortcut".
When prompted to enter a location put either:
"C:\Windows\System32\cmd.exe /k your-command
" This will run the command and keep (/k) the command prompt open after.
or
"C:\Windows\System32\cmd.exe /c your-command
" This will run the command and the close (/c) the command prompt.
Notes:
Tested, and working on Windows 8 - Core X86-64 September 12 2014
If you want to have more than one command, place an "&" symbol in between them. For example: "C:\Windows\System32\cmd.exe /k command1 & command2
".
Also, I've noticed at different places and at different times the asterisk (
*
) is located either right after the timeNSDate* now
or right before the variableNSDate *now
. What is the difference in the two and why would you use one versus the other?
The compiler doesn't care, but putting the asterisk before the space can be misleading. Here's my example:
int* a, b;
What is the type of b
?
If you guessed int *
, you're wrong. It's just int
.
The other way makes this slightly clearer by keeping the * next to the variable it belongs to:
int *a, b;
Of course, there are two ways that are even clearer than that:
int b, *a;
int *a;
int b;
If your id is incremental then use something like
delete from table where id < (select max(id) from table)-N
DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).
Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/
And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad
To extrapolate a bit on the other answers (in as Beginner-friendly a way as possible):
Check the object type with the GetType Method to see what you're working with: $scriptPath.GetType()
Lastly, a quick tip that helps with making one-liners: Get-Item has the gi
alias and Get-ChildItem has the gci
alias.
In the sense you mean — no, you cannot.
You can declare a va_arg
function like
void my_func(char* format, ...);
, but you'll need to pass some kind of information about number of variables and their types in the first argument — like printf()
does.
firstly I don't think there is just one solution to your problem....
As you know each browser is vastly differant.
But lets see if we can get any closer to the answer you need....
I think IE Might be easy...
Check this link http://support.microsoft.com/kb/181050
For Firefox try this:
Open Firefox, and in the address bar, type "about:config" (without quotes). From there, scroll down to the Network.http.keep-alive and make sure that is set to "true". If it is not, double click it, and it will go from false to true. Now, go one below that to network.http.keep-alive.timeout -- and change that number by double clicking it. if you put in, say, 500 there, you should be good. let us know if this helps at all
spinnerType = (AppCompatSpinner) findViewById(R.id.account_type);
spinnerType.setPrompt("Select Type");
spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TypeItem clickedItem = (TypeItem) parent.getItemAtPosition(position);
String TypeName = clickedItem.getTypeName();
Toast.makeText(AddAccount.this, TypeName + " selected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
you can use this method just pass your date to it
-(NSString *)getDateFromString:(NSString *)string
{
NSString * dateString = [NSString stringWithFormat: @"%@",string];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"your current date format"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"your desired format"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
NSLog(@"%@", stringFromDate);
return stringFromDate;
}
Now with Java 7, you can use the following try-with-resource syntax:
public static void copyFile( File from, File to ) throws IOException {
if ( !to.exists() ) { to.createNewFile(); }
try (
FileChannel in = new FileInputStream( from ).getChannel();
FileChannel out = new FileOutputStream( to ).getChannel() ) {
out.transferFrom( in, 0, in.size() );
}
}
Or, better yet, this can also be accomplished using the new Files class introduced in Java 7:
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Pretty snazzy, eh?
it is now End of 2015 and after developing my structure for 3 years and in small and large projects. Conclusion?
Do not do one large MVC, but separate it in modules
So...
Why?
Usually one works on one module (e.g. Products), which you can change independently.
You are able to reuse modules
You are able to test it separatly
You are able to replace it separatly
They have clear (stable) interfaces
-At latest, if there were multiple developers working, module separation helps
The nodebootstrap project has a similar approach to my final structure. (github)
How does this structure look like?
Small, capsulated modules, each with separate MVC
Each module has a package.json
Testing as a part of the structure (in each module)
Global configuration, libraries and Services
Integrated Docker, Cluster, forever
Folderoverview (see lib folder for modules):
According to the API, the headers can all be passed in using requests.get
:
import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})
The final
keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all. But that's enough.
Some programmers (like me) think that's a very good thing and use final
on almost every parameter. It makes it easier to understand a long or complex method (though one could argue that long and complex methods should be refactored.) It also shines a spotlight on method parameters that aren't marked with final
.
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
Borrowing from what Ivo van der Wijk and gnibbler have developed earlier, this is a dynamic solution
import cStringIO
import PIL.Image
image_data = None
def imagetopy(image, output_file):
with open(image, 'rb') as fin:
image_data = fin.read()
with open(output_file, 'w') as fout:
fout.write('image_data = '+ repr(image_data))
def pytoimage(pyfile):
pymodule = __import__(pyfile)
img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data))
img.show()
if __name__ == '__main__':
imagetopy('spot.png', 'wishes.py')
pytoimage('wishes')
You can then decide to compile the output image file with Cython to make it cool. With this method, you can bundle all your graphics into one module.
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
To invoke a dry run:
make -n
This will show what make
is attempting to do.
For the facts, a performance test at jsperf and checking some things in the console are performed. For the research, the website irt.org is used. Below is a collection of all these sources put together plus an example function at the bottom.
+-----------------------------------------------------------------------------+ ¦ Method ¦Concat¦slice&push.apply ¦ push.apply x2 ¦ ForLoop ¦Spread ¦ ¦---------------+------+-----------------+---------------+---------+----------¦ ¦ mOps/Sec ¦179 ¦104 ¦ 76 ¦ 81 ¦28 ¦ ¦---------------+------+-----------------+---------------+---------+----------¦ ¦ Sparse arrays ¦YES! ¦Only the sliced ¦ no ¦ Maybe2 ¦no ¦ ¦ kept sparse ¦ ¦array (1st arg) ¦ ¦ ¦ ¦ ¦---------------+------+-----------------+---------------+---------+----------¦ ¦ Support ¦MSIE 4¦MSIE 5.5 ¦ MSIE 5.5 ¦ MSIE 4 ¦Edge 12 ¦ ¦ (source) ¦NNav 4¦NNav 4.06 ¦ NNav 4.06 ¦ NNav 3 ¦MSIENNav¦ ¦---------------+------+-----------------+---------------+---------+----------¦ ¦Array-like acts¦no ¦Only the pushed ¦ YES! ¦ YES! ¦If have ¦ ¦like an array ¦ ¦array (2nd arg) ¦ ¦ ¦iterator1 ¦ +-----------------------------------------------------------------------------+ 1 If the array-like object does not have a Symbol.iterator property, then trying to spread it will throw an exception. 2 Depends on the code. The following example code "YES" preserves sparseness.
function mergeCopyTogether(inputOne, inputTwo){
var oneLen = inputOne.length, twoLen = inputTwo.length;
var newArr = [], newLen = newArr.length = oneLen + twoLen;
for (var i=0, tmp=inputOne[0]; i !== oneLen; ++i) {
tmp = inputOne[i];
if (tmp !== undefined || inputOne.hasOwnProperty(i)) newArr[i] = tmp;
}
for (var two=0; i !== newLen; ++i, ++two) {
tmp = inputTwo[two];
if (tmp !== undefined || inputTwo.hasOwnProperty(two)) newArr[i] = tmp;
}
return newArr;
}
As seen above, I would argue that Concat is almost always the way to go for both performance and the ability to retain the sparseness of spare arrays. Then, for array-likes (such as DOMNodeLists like document.body.children
), I would recommend using the for loop because it is both the 2nd most performant and the only other method that retains sparse arrays. Below, we will quickly go over what is meant by sparse arrays and array-likes to clear up confusion.
At first, some people may think that this is a fluke and that browser vendors will eventually get around to optimizing Array.prototype.push to be fast enough to beat Array.prototype.concat. WRONG! Array.prototype.concat will always be faster (in principle at least) because it is a simple copy-n-paste over the data. Below is a simplified persuado-visual diagram of what a 32-bit array implementation might look like (please note real implementations are a LOT more complicated)
Byte ¦ Data here -----+----------- 0x00 ¦ int nonNumericPropertiesLength = 0x00000000 0x01 ¦ ibid 0x02 ¦ ibid 0x03 ¦ ibid 0x00 ¦ int length = 0x00000001 0x01 ¦ ibid 0x02 ¦ ibid 0x03 ¦ ibid 0x00 ¦ int valueIndex = 0x00000000 0x01 ¦ ibid 0x02 ¦ ibid 0x03 ¦ ibid 0x00 ¦ int valueType = JS_PRIMITIVE_NUMBER 0x01 ¦ ibid 0x02 ¦ ibid 0x03 ¦ ibid 0x00 ¦ uintptr_t valuePointer = 0x38d9eb60 (or whereever it is in memory) 0x01 ¦ ibid 0x02 ¦ ibid 0x03 ¦ ibid
As seen above, all you need to do to copy something like that is almost as simple as copying it byte for byte. With Array.prototype.push.apply, it is a lot more than a simple copy-n-paste over the data. The ".apply" has to check each index in the array and convert it to a set of arguments before passing it to Array.prototype.push. Then, Array.prototype.push has to additionally allocate more memory each time, and (for some browser implementations) maybe even recalculate some position-lookup data for sparseness.
An alternative way to think of it is this. The source array one is a large stack of papers stapled together. The source array two is also another large stack of papers. Would it be faster for you to
In the above analogy, option #1 represents Array.prototype.concat while #2 represents Array.prototype.push.apply. Let us test this out with a similar JSperf differing only in that this one tests the methods over sparse arrays, not solid arrays. One can find it right here.
Therefore, I rest my case that the future of performance for this particular use case lies not in Array.prototype.push, but rather in Array.prototype.concat.
When certain members of the array are simply missing. For example:
// This is just as an example. In actual code,
// do not mix different types like this.
var mySparseArray = [];
mySparseArray[0] = "foo";
mySparseArray[10] = undefined;
mySparseArray[11] = {};
mySparseArray[12] = 10;
mySparseArray[17] = "bar";
console.log("Length: ", mySparseArray.length);
console.log("0 in it: ", 0 in mySparseArray);
console.log("arr[0]: ", mySparseArray[0]);
console.log("10 in it: ", 10 in mySparseArray);
console.log("arr[10] ", mySparseArray[10]);
console.log("20 in it: ", 20 in mySparseArray);
console.log("arr[20]: ", mySparseArray[20]);
_x000D_
Alternatively, javascript allows you to initialize spare arrays easily.
var mySparseArray = ["foo",,,,,,,,,,undefined,{},10,,,,,"bar"];
An array-like is an object that has at least a length
property, but was not initialized with new Array
or []
; For example, the below objects are classified as array-like.
{0: "foo", 1: "bar", length:2}
document.body.children
new Uint8Array(3)
(function(){return arguments})()
Observe what happens using a method that does coerce array-likes into arrays like slice.
var slice = Array.prototype.slice;
// For arrays:
console.log(slice.call(["not an array-like, rather a real array"]));
// For array-likes:
console.log(slice.call({0: "foo", 1: "bar", length:2}));
console.log(slice.call(document.body.children));
console.log(slice.call(new Uint8Array(3)));
console.log(slice.call( function(){return arguments}() ));
_x000D_
Observe what happens using a method that does not coerce array-likes into arrays like concat.
var empty = [];
// For arrays:
console.log(empty.concat(["not an array-like, rather a real array"]));
// For array-likes:
console.log(empty.concat({0: "foo", 1: "bar", length:2}));
console.log(empty.concat(document.body.children));
console.log(empty.concat(new Uint8Array(3)));
console.log(empty.concat( function(){return arguments}() ));
_x000D_
This worked for me for deserializing JSON into an array of objects:
List<TheUser> friends = JsonConvert.DeserializeObject<List<TheUser>>(response);
Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.
The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.
I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.
References:
https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/
var Hello = React.createClass({
render: function() {
return (
<div className="divClass">
<img src={this.props.url} alt={`${this.props.title}'s picture`} className="img-responsive" />
<span>Hello {this.props.name}</span>
</div>
);
}
});
You can also use DEV_RANDOM, where 128 = 1/2 the generated token length. Code below generates 256 token.
$token = bin2hex(mcrypt_create_iv(128, MCRYPT_DEV_RANDOM));
An integer value is a mathematical representation of a number and is ignorant of leading zeroes.
You can get a string with leading zeroes like this:
someNumber.ToString("00000000")
"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0
and so you try to read from the memory address 0x0
, which the operating system detects and prevents you from doing.
Check and make sure that the array invaders[]
is what you think it should be.
Also, you don't seem to be updating i
ever - meaning that you keep placing the same Invader
object into location 0
of invaders[]
at every loop iteration.
You probably missed package declaration
package my.demo.service;
public class CarService {
...
}
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'And so on and so forth.
"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source
This is how I do it:
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime);
You might get even better results if you try:
console.log(JSON.stringify(obj, null, 4));
First you get full URL using
HttpContext.Current.Request.Url.ToString();
then replace your method url using Replace("user/login", "").
Full code will be
string host = HttpContext.Current.Request.Url.ToString().Replace("user/login", "")
According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.
Following the instructions from this page,
manager-osx.app
).Manage Servers
tab -> select Apache Web Server
-> click Configure
.Open Conf File
. Provide credentials if asked.Change
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User daemon
Group daemon
</IfModule>
to
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User your_username
Group staff
</IfModule>
Save and close.
Navigate to the document root of your server and make yourself the owner. The default is /Applications/XAMPP/xamppfiles/htdocs
.
$ cd your_document_root
$ sudo chown -R your_username:staff .
Navigate to the xamppfiles
directory and change the permission for logs
and temp
directory.
$ cd /Applications/XAMPP/xamppfiles
$ sudo chown -R your_username:staff logs
$ sudo chown -R your_username:staff temp
To be able to use phpmyadmin you have to change the permissions for config.inc.php
.
$ cd /Applications/XAMPP/xamppfiles/phpmyadmin
$ sudo chown your_username:staff config.inc.php
I haven't seen a multiplication-based solution yet. Logarithm, divison, and string-based solutions will become rather unwieldy against millions of test cases, so here's one for ints
:
/**
* Returns the number of digits needed to represents an {@code int} value in
* the given radix, disregarding any sign.
*/
public static int len(int n, int radix) {
radixCheck(radix);
// if you want to establish some limitation other than radix > 2
n = Math.abs(n);
int len = 1;
long min = radix - 1;
while (n > min) {
n -= min;
min *= radix;
len++;
}
return len;
}
In base 10, this works because n is essentially being compared to 9, 99, 999... as min is 9, 90, 900... and n is being subtracted by 9, 90, 900...
Unfortunately, this is not portable to long
just by replacing every instance of int
due to overflow. On the other hand, it just so happens it will work for bases 2 and 10 (but badly fails for most of the other bases). You'll need a lookup table for the overflow points (or a division test... ew)
/**
* For radices 2 &le r &le Character.MAX_VALUE (36)
*/
private static long[] overflowpt = {-1, -1, 4611686018427387904L,
8105110306037952534L, 3458764513820540928L, 5960464477539062500L,
3948651115268014080L, 3351275184499704042L, 8070450532247928832L,
1200757082375992968L, 9000000000000000000L, 5054470284992937710L,
2033726847845400576L, 7984999310198158092L, 2022385242251558912L,
6130514465332031250L, 1080863910568919040L, 2694045224950414864L,
6371827248895377408L, 756953702320627062L, 1556480000000000000L,
3089447554782389220L, 5939011215544737792L, 482121737504447062L,
839967991029301248L, 1430511474609375000L, 2385723916542054400L,
3902460517721977146L, 6269893157408735232L, 341614273439763212L,
513726300000000000L, 762254306892144930L, 1116892707587883008L,
1617347408439258144L, 2316231840055068672L, 3282671350683593750L,
4606759634479349760L};
public static int len(long n, int radix) {
radixCheck(radix);
n = abs(n);
int len = 1;
long min = radix - 1;
while (n > min) {
len++;
if (min == overflowpt[radix]) break;
n -= min;
min *= radix;
}
return len;
}
You could use the following to replace the first occurrence of a word within the body of the page:
var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);
If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g
:
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
If you wanted a one liner:
$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));
You are basically taking all of the HTML within the <body>
tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.
See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.
By referring this(http://www.excelforum.com/excel-programming-vba-macros/867665-application-cutcopymode-false.html) link the answer is as below:
Application.CutCopyMode=False
is seen in macro recorder-generated code when you do a copy/cut cells and paste . The macro recorder does the copy/cut and paste in separate statements and uses the clipboard as an intermediate buffer. I think Application.CutCopyMode = False
clears the clipboard. Without that line you will get the warning 'There is a large amount of information on the Clipboard....'
when you close the workbook with a large amount of data on the clipboard.
With optimised VBA code you can usually do the copy/cut and paste operations in one statement, so the clipboard isn't used and Application.CutCopyMode = False
isn't needed and you won't get the warning.
A more elegant solution
echo "Enter the file name"
read x
if [ -f $x ]
then
echo "This is a regular file"
else
echo "This is a directory"
fi
Some code to walk through a list of titles (circularily or one-shot):
var titles = [
" title",
"> title",
">> title",
">>> title"
];
// option 1:
function titleAniCircular(i) {
// from first to last title and back again, forever
i = (!i) ? 0 : (i*1+1) % titles.length;
$('title').html(titles[i]);
setTimeout(titleAniCircular, 1000, [i]);
};
// option 2:
function titleAniSequence(i) {
// from first to last title and stop
i = (!i) ? 0 : (i*1+1);
$('title').html(titles[i]);
if (i<titles.length-1) setTimeout(titleAniSequence, 1000, [i]);
};
// then call them when you like.
// e.g. to call one on document load, uncomment one of the rows below:
//$(document).load( titleAniCircular() );
//$(document).load( titleAniSequence() );
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
I had the same issue. When I checked it out I found that the name of the XML resource under layout was not having the correct naming convention. It had some capital letters. So I renamed it to make all letters lowercase and the magic worked.
$('#tabs').tabs('select', index);
Methods `'select' isn't support in jquery ui 1.10.0.http://api.jqueryui.com/tabs/
I use this code , and work correctly:
$('#tabs').tabs({ active: index });
While matt b's answer will work, you can also use .serializeArray()
to get an array from the form data, modify it, and use jQuery.param()
to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.
var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
type: 'POST',
url: this.action,
data: $.param(data),
});
There's a plugin called SublimeHtmlTidy which works pretty well
I read many topics about this error and the solution to me was to simply restart the postgres with:
sudo service postgresql restart
Which is not mentioned here.
There would be another way to do this:
var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();
To iterate over keys, it is slower but better to use my_dict.keys()
. If you tried to do something like this:
for key in my_dict:
my_dict[key+"-1"] = my_dict[key]-1
it would create a runtime error because you are changing the keys while the program is running. If you are absolutely set on reducing time, use the for key in my_dict
way, but you have been warned.
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
You can also remove all the git related stuff using one command. The .gitignore file will also be deleted with this one.
rm -rf .git*
So one day, I decided that I'd had enough. I would learn piano. Seeing people like Elton John command such mastery of the keyboard assured me that this was what I wanted to do.
Actually learning piano was a huge letdown. Even after completing eight grades of piano lessons, I was still not impressed with how my mental image of playing piano was so different from my original vision of enjoying the activity.
However, what I thoroughly enjoyed was my mere three grades of rudiments of music theory. I learned about the construction of music. I was finally able to step from the world of performing written music to writing my own music. Subsequently, I was able to start playing what I wanted to play.
Don't try to dazzle new programmers, especially young programmers. The whole notion of "less than ten lines of simple code" seems to elicit a mood of "Show me something clever".
You can show a new programmer something clever. You can then teach that same programmer how to replicate this "performance". But this is not what gets them hooked on programming. Teach them the rudiments, and let them synthesize their own clever ten lines of code.
I would show a new programmer the following Python code:
input = open("input.txt", "r")
output = open("output.txt", "w")
for line in input:
edited_line = line
edited_line = edited_line.replace("EDTA", "ethylenediaminetetraacetic acid")
edited_line = edited_line.replace("ATP", "adenosine triphosphate")
output.write(edited_line)
I realize that I don't need to assign line
to edited_line
. However, that's just to keep things clear, and to show that I'm not editing the original document.
In less than ten lines, I've verbosified a document. Of course, also be sure to show the new programmer all the string methods that are available. More importantly, I've showed three fundamentally interesting things I can do: variable assignment, a loop, file IO, and use of the standard library.
I think you'll agree that this code doesn't dazzle. In fact, it's a little boring. No - actually, it's very boring. But show that code to a new programmer and see if that programmer can't repurpose every part of that script to something much more interesting within the week, if not the day. Sure, it'll be distasteful to you (maybe using this script to make a simple HTML parser), but everything else just takes time and experience.
It's not that different in bash
.
workdone=0
while : ; do
...
if [ "$workdone" -ne 0 ]; then
break
fi
done
:
is the no-op command; its exit status is always 0, so the loop runs until workdone
is given a non-zero value.
There are many ways you could set and test the value of workdone
in order to exit the loop; the one I show above should work in any POSIX-compatible shell.
Change the line where you print the output to:
printf("\nmaximum of %d and %d is = %d",a,b,c);
See the docs here
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
If it had been in PostgreSQL, use double quotes around the name, like:
select "from" from "table";
Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.
Optionals and default parameters are two different things.
An Optional is a variable that can be nil
, that's it.
Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)
If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil
. If your function looks like this func test(param: Int?)
, you can't call it like this test()
. Even though the parameter is optional, it doesn't have a default value.
You can also combine the two and have a parameter that takes an optional where nil
is the default value, like this: func test(param: Int? = nil)
.
If it is a game(may be app also) and you have some static libraries like cocos2d or other third party library ... then you just have to select *ONLY THE* static library (NOT THE APP) and in its build settings under Deployment , set Skip Install flag to YES
and Archive it dats it...!!
You can access the event from onclick like this:
<button onclick="yourFunc(event);">go</button>
and at your javascript function, my advice is adding that first line statement as:
function yourFunc(e) {
e = e ? e : event;
}
then use everywhere e as event variable
What's a "block scheme"?
If I were drawing it, I might draw a box with "for each x in y" written in it.
If you're drawing a flowchart, there's always a loop with a decision box.
Nassi-Schneiderman diagrams have a loop construct you could use.
You can create a new sorted copy using Java 8 Stream or Guava:
// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names);
Another option is to sort in-place via Collections API:
Collections.sort(names);
You could achieve this with an extra <span>
:
HTML
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>
CSS
h2 {
position: relative;
}
h2 span {
background-color: white;
padding-right: 10px;
}
h2:after {
content:"";
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 0.5em;
border-top: 1px solid black;
z-index: -1;
}
http://jsfiddle.net/myajouri/pkm5r/
Another solution without the extra <span>
but requires an overflow: hidden
on the <h2>
:
h2 {
overflow: hidden;
}
h2:after {
content:"";
display: inline-block;
height: 0.5em;
vertical-align: bottom;
width: 100%;
margin-right: -100%;
margin-left: 10px;
border-top: 1px solid black;
}
I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
If you are interested in determining this in a script, you can try the following:
sc \\server_name query | grep MSSQL
Note: grep is part of gnuwin32 tools
set vimdiff to ignore case
Having started vim diff with
gvim -d main.sql backup.sql &
I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line
:set diffopt+=icase
this updates the screen dynamically & you can just as easily switch it off again
This should be lightning fast:
int msb(unsigned int v) {
static const int pos[32] = {0, 1, 28, 2, 29, 14, 24, 3,
30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19,
16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v = (v >> 1) + 1;
return pos[(v * 0x077CB531UL) >> 27];
}
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
$request->fullUrl()
will also work if you are injecting Illumitate\Http\Request
.
I had a similar problem with flasgger.
The reason for that was that I always use
sudo pip install flask
but for some reason that's not always the way to go. Sometimes, you have to do just
pip install flask
Another gotcha is that sometimes people type pip install Flask
with the cap F
Posting this here in case somebody gets stuck. Let me know if it helped.
Useful Link: What is the difference between pip install and sudo pip install?
Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: ItemID, TagID
The 1*y
method works in Numpy too:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
If you are asking for a way to convert Python lists from Boolean to int, you can use map
to do it:
>>> testList = [False, False, True, True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]
Or using list comprehensions:
>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]
Starting in Java 1.5 and up, there is a new feature called auto-boxing. The compiler does this itself. When it sees an opportunity, it converts a primitive type into its appropriate wrapper class.
What is probably happening here is when you declare
Object o = i;
The compiler will compile this statement as saying
Object o = Integer.valueOf(i);
This is auto-boxing. This would explain the output you are receiving. This page from the Java 1.5 spec explains auto-boxing more in detail.
Javac Reporter.java
java Reporter
Similarily, you can set it in windows environment variables. for example, in Win7
Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila