The Pyzo IDE has similar capabilities as the OP asked for. You don't have to start in debug mode. Similarly to MATLAB, the commands are executed in the shell. When you set up a break-point in some source code line, the IDE stops the execution there and you can debug and issue regular IPython commands as well.
It does seem however that step-into doesn't (yet?) work well (i.e. stopping in one line and then stepping into another function) unless you set up another break-point.
Still, coming from MATLAB, this seems the best solution I've found.
Assume the path of
Project A
C:\Projects\ProjectA
Project B
C:\Projects\ProjectB
and the dll of ProjectB is in
C:\Projects\ProjectB\bin\Debug\
To debug into ProjectB
from ProjectA
, do the following
B
's dll with dll's .PDB
to the ProjectA
's compiling directory. ProjectA
. When code reaches the part where you need to call dll's method or events etc while debugging, press F11
to step into the dll's code. NOTE : DO NOT MISS TO COPY THE .PDB FILE
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
if you do not want to be bothered by the date format, you could compare the column with the general date format, for example
select *
From table
where cast (RegistrationDate as date) between '20161201' and '20161220'
make sure the date is in DATE format, otherwise cast (col as DATE)
Found this works for me:
In the link:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>
In the modal:
<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<?php echo $row['id'];?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I've got a one liner to make HTML Tables look BootStrapped:
<table class="table table-striped table-bordered table-hover">
The theme suits other controls and it supports alternate row highlighting.
When I am reading numbers from contact book, then it doesn't worked I used
number=number.replaceAll("\\s+", "");
It worked and for url you may use
url=url.replaceAll(" ", "%20");
On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:
def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE
If you are using goovy from file, simple System.getenv('MY_VARIABLE')
is sufficient
Use Map<Integer, List<String>>
:
Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();
map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...
To add a new key/value pair in this map:
public void add(Integer key, String newValue) {
List<String> currentValue = map.get(key);
if (currentValue == null) {
currentValue = new ArrayList<String>();
map.put(key, currentValue);
}
currentValue.add(newValue);
}
There is no such thing as "SOAP protocol". SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
Other way:
echo "db.dropDatabase()" | mongo <database name>
For SQL Server 2012:
SELECT
o.OrderId,
IIF( o.NegotiatedPrice >= o.SuggestedPrice,
o.NegotiatedPrice,
ISNULL(o.SuggestedPrice, o.NegiatedPrice)
)
FROM
Order o
You can find through below query :
SELECT OBJECT_NAME (FK.referenced_object_id) 'Referenced Table',
OBJECT_NAME(FK.parent_object_id) 'Referring Table', FK.name 'Foreign Key',
COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) 'Referenced Column',
COL_NAME(FK.parent_object_id,FKC.parent_column_id) 'Referring Column'
FROM sys.foreign_keys AS FK
INNER JOIN sys.foreign_key_columns AS FKC
ON FKC.constraint_object_id = FK.OBJECT_ID
WHERE OBJECT_NAME (FK.referenced_object_id) = 'YourTableName'
AND COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) = 'YourColumnName'
order by OBJECT_NAME(FK.parent_object_id)
Here is my solution, I have been reading a lot of posts and they were really helpful. Finally I wrote some code for small files, with cURL and PHP that I think its really useful.
public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}
With this we should be get on the "api.endpoint.post" the following vars posted. You can easily test with this script, and you should be receive this debugs on the function postFile()
at the last row.
print_r($response); //print response
public function getPostFile()
{
echo "\n\n_SERVER\n";
echo "<pre>";
print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
echo "/<pre>";
echo "_POST\n";
echo "<pre>";
print_r($_POST['sometext']);
echo "/<pre>";
echo "_FILES\n";
echo "<pre>";
print_r($_FILEST['somefile']);
echo "/<pre>";
}
It should work well, they may be better solutions but this works and is really helpful to understand how the Boundary and multipart/from-data mime works on PHP and cURL library.
If you are looking for something easier:
public MyTextView extends TextView{
public void resize(String text, float textViewWidth, float textViewHeight) {
Paint p = new Paint();
Rect bounds = new Rect();
p.setTextSize(1);
p.getTextBounds(text, 0, text.length(), bounds);
float widthDifference = (textViewWidth)/bounds.width();
float heightDifference = (textViewHeight);
textSize = Math.min(widthDifference, heightDifference);
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.
So how the psql
command line tool achieves batched response (its FETCH_COUNT
setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:
static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
boolean originalAutoCommit = conn.getAutoCommit();
if (originalAutoCommit) {
conn.setAutoCommit(false); // start temp transaction
}
try (Statement statement = conn.createStatement()) {
statement.setFetchSize(fetchCount);
ResultSet rs = statement.executeQuery(originalQuery);
while (rs.next()) {
consumer.accept(rs); // or just do you work here
}
} finally {
if (originalAutoCommit) {
conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
}
}
}
@FunctionalInterface
public interface ConsumerWithException<T, E extends Exception> {
void accept(T t) throws E;
}
This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).
And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.
Another option would be to have autoCommit
mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
If you're designing for an iOS device or just webkit, you can do it with no JS whatsoever:
CSS:
@-webkit-keyframes spin {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
.wheel {
width:40px;
height:40px;
background:url(wheel.png);
-webkit-animation-name: spin;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-duration: 3s;
}
This would trigger the animation on load. If you wanted to trigger it on hover, it might look like this:
.wheel {
width:40px;
height:40px;
background:url(wheel.png);
}
.wheel:hover {
-webkit-animation-name: spin;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: ease-in-out;
-webkit-animation-duration: 3s;
}
In phpstorm + vagrant autoReconnect driver option helped.
The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.
You simply misspelled $stateParam
, it should be $stateParams
(with an s). That's why you get undefined ;)
Try something like this in your aspx page
<asp:Label ID="myLabel" runat="server"></asp:Label>
and then in your codebehind you can just do
myLabel.Text = "My Label";
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
To change action value of form dynamically, you can try below code:
below code is if you are opening some dailog box and inside that dailog box you have form and you want to change the action of it. I used Bootstrap dailog box and on opening of that dailog box I am assigning action value to the form.
$('#your-dailog-id').on('show.bs.modal', function (event) {
var link = $(event.relatedTarget);// Link that triggered the modal
var cURL= link.data('url');// Extract info from data-* attributes
$("#delUserform").attr("action", cURL);
});
If you are trying to change the form action on regular page, use below code
$("#yourElementId").change(function() {
var action = <generate_action>;
$("#formId").attr("action", action);
});
If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:
<meta property="og:image" content="/uploads/..." />
just replacing /uploads/... with the copied image address. Click Publish to apply the change.
You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
After that you have two way to back from current activity to previous activity:
Simply call: finish()
under button click listener,
Or
Override the following method to back using system back button:
@Override
public void onBackPressed() {
super.onBackPressed();
}
When there is no records returned from Database for a particular condition and When I tried to access the rs.getString(1); I got this error "exhausted resultset".
Before the issue, my code was:
rs.next();
sNr= rs.getString(1);
After the fix:
while (rs.next()) {
sNr = rs.getString(1);
}
On this MSDN blog: Troubleshooting HTTP 500.19 Errors in IIS 7 in scenario 8 for error code 0x80070005
(E_ACCESSDENIED
- General access denied error) it says:
Grant Read permission to the
IIS_IUSRS
group ....... the worker process identity (and/or the
IIS_IUSRS
group) needs at least Read access to the directory so that it can check for a web.config file in that directory.
This is a JQuery code for Preventing Submit
$('form').submit(function (e) {
if (radioButtonValue !== "0") {
e.preventDefault();
}
});
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
package com.test.utitlity;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class readExcel extends globalVariables {
/**
* @param args
* @throws IOException
*/
public static void readExcel(int rowcounter) throws IOException{
XSSFWorkbook srcBook = new XSSFWorkbook("./prop.xlsx");
XSSFSheet sourceSheet = srcBook.getSheetAt(0);
int rownum=rowcounter;
XSSFRow sourceRow = sourceSheet.getRow(rownum);
XSSFCell cell1=sourceRow.getCell(0);
XSSFCell cell2=sourceRow.getCell(1);
XSSFCell cell3=sourceRow.getCell(2);
System.out.println(cell1);
System.out.println(cell2);
System.out.println(cell3);
}
}
I found this is in the runtime permissions example from Google's github.
private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS};
private static final int REQUEST_CONTACTS = 1;
ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
Each elapsed event will fire in the same thread unless a previous Elapsed is still running.
So it handles the collision for you
try putting this in a console
static void Main(string[] args)
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
var timer = new Timer(1000);
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
you will get something like this
10
6
12
6
12
where 10 is the calling thread and 6 and 12 are firing from the bg elapsed event. If you remove the Thread.Sleep(2000); you will get something like this
10
6
6
6
6
Since there are no collisions.
But this still leaves u with a problem. if u are firing the event every 5 seconds and it takes 10 seconds to edit u need some locking to skip some edits.
If you want to add the elements in a list (list2) to the end of other list (list), then you can use the list extend method
list = [1, 2, 3]
list2 = [4, 5, 6]
list.extend(list2)
print list
[1, 2, 3, 4, 5, 6]
Or if you want to concatenate two list then you can use + sign
list3 = list + list2
print list3
[1, 2, 3, 4, 5, 6]
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
As people mentioned in the comments you probably don't want to do that... The answer from mipadi is absolutely correct if you know what you're doing.
I would say:
git checkout master
git pull # to update the state to the latest remote master state
git merge develop # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch
Open MySQL Workbench. In the home screen click 'Create EER Model From Existing Database'. We are doing this for the case that we have already made the data base and now we want to make an ER diagram of that database.
Then you will see the 'Reverse Engineer Database' dialouge. Here if you are asked for the password, provided the admin password. Do not get confused here with the windows password. Here you need to provide the MySQL admin password. Then click on Next.
In the next dialouge box, you'll see that the connection to DBMS is started and schema is revrieved from Database. Go next.
Now Select the Schema you created earlier. It is the table you want to create the ER diagram of.
Click Next and go to Select Objects menu. Here you can click on 'Show Filter' to use the selected Table Objects in the diagram. You can both add and remove tables here.Then click on Execute.
6.When you go Next and Finish, the required ER diagram is on the screen.
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
bool boolValue = intValue != 0;
Use Timer for this
private System.Windows.Forms.Timer timer1;
private int counter = 60;
private void btnStart_Click_1(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
lblCountDown.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
lblCountDown.Text = counter.ToString();
}
Additional useful info:
You can provide several og:images, whatsapp will use the last one. This will help with the problem that e.g. facebook want 1.91:1 ratio and whatsapp 1:1
<html>
<head>
<meta charset="UTF-8">
<title>LoginDB</title>
</head>
<body>
<?php
$con= mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
if(!$con)
{
die('not connected');
}
$con= mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
?>
<div>
<td>Login Page Database</td>
<table border="1">
<th> First Name</th>
<th>Last Name</th>
<th>UserName</th>
<th>Password</th>
<th>Gender</th>
<th>D.O.B.</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
<?php
while($row= mysqli_fetch_array($con))
<!-- Fetch each row from signup Table -->
{
?>
<tr>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Username']; ?></td>
<td><?php echo $row['Password'] ;?></td>
<td><?php echo $row['Gender'] ;?></td>
<td><?php echo $row['DOB'] ;?></td>
<td><?php echo $row['PhoneNumber'] ;?></td>
<td><?php echo $row['Address'] ;?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
You have a couple of questions here, so I'll address them separately:
My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).
You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:
Base table (what you have now):
| id primary_key sequence
| -- other columns here.
Items table:
| id primary_key sequence
| descript VARCHAR(30) UNIQUE
Map table:
| base_id bigint
| items_id bigint
Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.
And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.
If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.
Personally, I would use TEXT
. It does not sound like you'd gain much by making this a BLOB
, and TEXT
, in my experience, is easier to read if you're using some form of IDE.
Best performance on this method :
imageview.setBackgroundResource(R.drawable.location_light_green);
Use this.
After mapping of Application follow these steps
Open IIS Click on Applications Pools Double click on website Change Manage pipeline mode to "classic" click Ok.
Ow change .Net Framework Version to Lower version
Then click Ok
I know this is in the above answers, but my point is that I think all you need is
new Date(collectionDate);
if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").
DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;
Why can't you do it? Because the language doesn't allow you to initializa a base class' members in the derived class' initializer list.
How can you get this done? Like this:
class A
{
public:
A(int a, int b) : a_(a), b_(b) {};
int a_, b_;
};
class B : public A
{
public:
B() : A(0,0)
{
}
};
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
Search the registry for the install path of the office component you are interested in, e.g. for Excel 2010 look in SOFTWARE(Wow6432Node)\Microsoft\Office\14.0\Excel\InstallRoot. It will only be either in the 32-bit registry or the 64-bit registry not both.
What about:
SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a
To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function
Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function
Two parameter interface
BiConsumer
BiPredicate
BiFunction
For more than two, you have to create functional interface as follow(Consumer type):
@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
public void accept(T t, U u, V v, W w, X x);
}
If you go through the npm config documentation, it says:
proxy
Default: HTTP_PROXY or http_proxy environment variable, or null
Type: url
As per this, to disable usage of proxy, proxy
setting must be set to null
. To set proxy value to null, one has to make sure that HTTP_PROXY
or http_proxy
environment variable is not set. So unset these environment variables and make sure that npm config ls -l
shows proxy = null
.
Also, it is important to note that:
It would have been better if npm had made the type of proxy setting to boolean to switch on/off the proxy usage. Or, they can introduce a new setting of sort use_proxy
of type boolean.
As per this example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
will produce:
To unpack your data from pairs into lists use zip
:
x, y = zip(*li)
So, the one-liner:
plt.scatter(*zip(*li))
Try this one if you want to create a virtual column "age" within a select statement:
select brand, name, "10" as age from cars...
My approach was to make a virtual attribute instead of adding database columns.
class Choice
belongs_to :user
belongs_to :answer
# ------- Helpers -------
def question
answer.question
end
# extra sugar
def question_id
answer.question_id
end
end
This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer
from the db, and then question
. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})
), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.
There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.
<?php
require 'db_config.php';
$id = $_POST["id"];
$post = $_POST;
$sql = "UPDATE items SET title = '".$post['title']."'
,description = '".$post['description']."'
WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
%timeit
is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).
From the docs:
%timeit
Time execution of a Python statement or expression Usage, in line mode: %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
To use it, for example if we want to find out whether using xrange
is any faster than using range
, you can simply do:
In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop
In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop
And you will get the timings for them.
The major advantage of %timeit
are:
that you don't have to import timeit.timeit
from the standard library, and run the code multiple times to figure out which is the better approach.
%timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit
to built the variable that is built in an another environment that timeit works.
Try this one:
echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"
The ps
command produces output like this, with the PID in the first column and the executable name (only) in the second column:
bookworm% ps -ceo pid=,comm=
1 launchd
10 kextd
11 UserEventAgent
12 mDNSResponder
13 opendirectoryd
14 notifyd
15 configd
...which awk
processes, printing the first column (pid) and exiting after the first match.
No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.
That means that
If you add absolute positioning to an element with display: inline-flex
, it will become block-level (like display: flex
), but will still generate a flex formatting context.
If you add absolute positioning to an element with display: flex
, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.
That said, absolutely positioning conflicts with flex children.
As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.
Here is an extension/edit of VonCs solution just in case someone doesn´t want to go through the hassle of implementing their own filter to do this. It also shows how to output a JAXB element without the namespace present. This is all accomplished using a SAX Filter.
Filter implementation:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;
public class NamespaceFilter extends XMLFilterImpl {
private String usedNamespaceUri;
private boolean addNamespace;
//State variable
private boolean addedNamespace = false;
public NamespaceFilter(String namespaceUri,
boolean addNamespace) {
super();
if (addNamespace)
this.usedNamespaceUri = namespaceUri;
else
this.usedNamespaceUri = "";
this.addNamespace = addNamespace;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
if (addNamespace) {
startControlledPrefixMapping();
}
}
@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {
super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {
super.endElement(this.usedNamespaceUri, arg1, arg2);
}
@Override
public void startPrefixMapping(String prefix, String url)
throws SAXException {
if (addNamespace) {
this.startControlledPrefixMapping();
} else {
//Remove the namespace, i.e. don´t call startPrefixMapping for parent!
}
}
private void startControlledPrefixMapping() throws SAXException {
if (this.addNamespace && !this.addedNamespace) {
//We should add namespace since it is set and has not yet been done.
super.startPrefixMapping("", this.usedNamespaceUri);
//Make sure we dont do it twice
this.addedNamespace = true;
}
}
}
This filter is designed to both be able to add the namespace if it is not present:
new NamespaceFilter("http://www.example.com/namespaceurl", true);
and to remove any present namespace:
new NamespaceFilter(null, false);
The filter can be used during parsing as follows:
//Prepare JAXB objects
JAXBContext jc = JAXBContext.newInstance("jaxb.package");
Unmarshaller u = jc.createUnmarshaller();
//Create an XMLReader to use with our filter
XMLReader reader = XMLReaderFactory.createXMLReader();
//Create the filter (to add namespace) and set the xmlReader as its parent.
NamespaceFilter inFilter = new NamespaceFilter("http://www.example.com/namespaceurl", true);
inFilter.setParent(reader);
//Prepare the input, in this case a java.io.File (output)
InputSource is = new InputSource(new FileInputStream(output));
//Create a SAXSource specifying the filter
SAXSource source = new SAXSource(inFilter, is);
//Do unmarshalling
Object myJaxbObject = u.unmarshal(source);
To use this filter to output XML from a JAXB object, have a look at the code below.
//Prepare JAXB objects
JAXBContext jc = JAXBContext.newInstance("jaxb.package");
Marshaller m = jc.createMarshaller();
//Define an output file
File output = new File("test.xml");
//Create a filter that will remove the xmlns attribute
NamespaceFilter outFilter = new NamespaceFilter(null, false);
//Do some formatting, this is obviously optional and may effect performance
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setNewlines(true);
//Create a new org.dom4j.io.XMLWriter that will serve as the
//ContentHandler for our filter.
XMLWriter writer = new XMLWriter(new FileOutputStream(output), format);
//Attach the writer to the filter
outFilter.setContentHandler(writer);
//Tell JAXB to marshall to the filter which in turn will call the writer
m.marshal(myJaxbObject, outFilter);
This will hopefully help someone since I spent a day doing this and almost gave up twice ;)
If you're using data binding, then you need to use the ContentRendered event.
For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.
<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />
You can not Uninstall/Reinstall JRE if you are having this error. That's why because previous installation has copied 3 files namely Java.exe, Javaw.exe, javaws.exe in the c:/windows/system32 folder. Simply go there and remove these files and download a fresh version of jre from oracle and install it. I will prefer JDK 1.6 update 45. Which is very stable.
I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:
import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk
class UI:
def __init__(self):
self.root = tk.Tk()
self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
self.button = tk.Button(text="Do Task", command=self.do_task).pack()
def do_task(self):
rx.empty().subscribe(
on_completed=self.long_running_task,
scheduler=self.pool_scheduler
)
def long_running_task(self):
# your long running task here... eg:
time.sleep(3)
# if you want a callback on the main thread:
self.root.after(5, self.on_task_complete)
def on_task_complete(self):
pass # runs on main thread
if __name__ == "__main__":
ui = UI()
ui.root.mainloop()
Another way to use this construct which might be cleaner (depending on preference):
tk.Button(text="Do Task", command=self.button_clicked).pack()
...
def button_clicked(self):
def do_task(_):
time.sleep(3) # runs on background thread
def on_task_done():
pass # runs on main thread
rx.just(1).subscribe(
on_next=do_task,
on_completed=lambda: self.root.after(5, on_task_done),
scheduler=self.pool_scheduler
)
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
You could take a Set
and filter the values who are alreday seen.
var array = ["q", "w", "w", "e", "i", "u", "r"],_x000D_
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));_x000D_
_x000D_
console.log(seen);
_x000D_
window.location = '/';
Should usually do the trick, but it depends on your sites directories. This will work for your example
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID
column. In the right grid, select the CustomerID
column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
Just call: ruby your_program.rb
or
#!/usr/bin/env ruby
,chmod +x your_program.rb
./your_program.rb some_param
@broc.seib has a sophisticated answer, I just want to point out that instead of pressing y
to get the permanent link, github now has a very simple UI that helps you to achieve it
Select line by clicking on the line number or select multiple lines by downholding shift
(same as how you select multiple folders in file explorer)
on the right hand corner of the first line you selected, expand ...
and click copy permalink
https://github.com/python/cpython/blob/c82b7f332aff606af6c9c163da75f1e86514125e/Doc/Makefile#L1-L4
thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);
Similarly you can get the text view by adding a id to it.
I wasted couple of hours on the same issue. In my case, I had to reset_index() of a dataframe before using apply function. Before merging, or looking up from another indexed dataset, you need to reset the index as 1 dataset can have only 1 Index.
For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:
hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }
hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}
Here is how you can do it and it works fine
func refreshCollectionView(_ count: Int) {
let collectionViewHeight = collectionView.bounds.height
let collectionViewWidth = collectionView.bounds.width
let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
if numberOfItemsThatCanInCollectionView > count {
let totalCellWidth = collectionViewHeight * CGFloat(count)
let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
// leftInset, rightInset are the global variables which I am passing to the below function
leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
rightInset = -leftInset
} else {
leftInset = 0.0
rightInset = -collectionViewHeight
}
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}
Here is my first try at an answer:
void xprintfloat(char *format, float f) { char s[50]; char *p; sprintf(s, format, f); for(p=s; *p; ++p) if('.' == *p) { while(*++p); while('0'==*--p) *p = '\0'; } printf("%s", s); }
Known bugs: Possible buffer overflow depending on format. If "." is present for other reason than %f wrong result might happen.
If you have vps or dedicated server, You can code your own module using C programming.
para.h
/*
* File: para.h
* Author: rahul
*
* Created on 10 February, 2016, 11:24 AM
*/
#ifndef PARA_H
#define PARA_H
#ifdef __cplusplus
extern "C" {
#endif
#define From "<[email protected]>"
#define To "<[email protected]>"
#define From_header "Rahul<[email protected]>"
#define TO_header "Mini<[email protected]>"
#define UID "smtp server account ID"
#define PWD "smtp server account PWD"
#define domain "dfgdfgdfg.com"
#ifdef __cplusplus
}
#endif
#endif
/* PARA_H */
main.c
/*
* File: main.c
* Author: rahul
*
* Created on 10 February, 2016, 10:29 AM
*/
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "time.h"
#include "para.h"
/*
*
*/
my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message);
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused)));
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error);
/*
* base64
*/
int Base64encode_len(int len);
int Base64encode(char * coded_dst, const char *plain_src,int len_plain_src);
int Base64decode_len(const char * coded_src);
int Base64decode(char * plain_dst, const char *coded_src);
/* aaaack but it's fast and const should make it shared text page. */
static const unsigned char pr2six[256] =
{
/* ASCII table */
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};
int Base64decode_len(const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
return nbytesdecoded + 1;
}
int Base64decode(char *bufplain, const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register unsigned char *bufout;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
bufout = (unsigned char *) bufplain;
bufin = (const unsigned char *) bufcoded;
while (nprbytes > 4) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
}
if (nprbytes > 2) {
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
}
if (nprbytes > 3) {
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
}
*(bufout++) = '\0';
nbytesdecoded -= (4 - nprbytes) & 3;
return nbytesdecoded;
}
static const char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int Base64encode_len(int len)
{
return ((len + 2) / 3 * 4) + 1;
}
int Base64encode(char *encoded, const char *string, int len)
{
int i;
char *p;
p = encoded;
for (i = 0; i < len - 2; i += 3) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2) |
((int) (string[i + 2] & 0xC0) >> 6)];
*p++ = basis_64[string[i + 2] & 0x3F];
}
if (i < len) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
if (i == (len - 1)) {
*p++ = basis_64[((string[i] & 0x3) << 4)];
*p++ = '=';
}
else {
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2)];
}
*p++ = '=';
}
*p++ = '\0';
return p - encoded;
}
/*
end of base64
*/
const char* GetIPAddress(const char* target_domain) {
const char* target_ip;
struct in_addr *host_address;
struct hostent *raw_list = gethostbyname(target_domain);
int i = 0;
for (i; raw_list->h_addr_list[i] != 0; i++) {
host_address = raw_list->h_addr_list[i];
target_ip = inet_ntoa(*host_address);
}
return target_ip;
}
char * MailHeader(const char* from, const char* to, const char* subject, const char* mime_type, const char* charset) {
time_t now;
time(&now);
char *app_brand = "Codevlog Test APP";
char* mail_header = NULL;
char date_buff[26];
char Branding[6 + strlen(date_buff) + 2 + 10 + strlen(app_brand) + 1 + 1];
char Sender[6 + strlen(from) + 1 + 1];
char Recip[4 + strlen(to) + 1 + 1];
char Subject[8 + 1 + strlen(subject) + 1 + 1];
char mime_data[13 + 1 + 3 + 1 + 1 + 13 + 1 + strlen(mime_type) + 1 + 1 + 8 + strlen(charset) + 1 + 1 + 2];
strftime(date_buff, (33), "%a , %d %b %Y %H:%M:%S", localtime(&now));
sprintf(Branding, "DATE: %s\r\nX-Mailer: %s\r\n", date_buff, app_brand);
sprintf(Sender, "FROM: %s\r\n", from);
sprintf(Recip, "To: %s\r\n", to);
sprintf(Subject, "Subject: %s\r\n", subject);
sprintf(mime_data, "MIME-Version: 1.0\r\nContent-type: %s; charset=%s\r\n\r\n", mime_type, charset);
int mail_header_length = strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject) + strlen(mime_data) + 10;
mail_header = (char*) malloc(mail_header_length);
memcpy(&mail_header[0], &Branding, strlen(Branding));
memcpy(&mail_header[0 + strlen(Branding)], &Sender, strlen(Sender));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender)], &Recip, strlen(Recip));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip)], &Subject, strlen(Subject));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject)], &mime_data, strlen(mime_data));
return mail_header;
}
my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message){
if (!(arg->arg_count == 2)) {
strcpy(message, "Expected two arguments");
return 1;
}
arg->arg_type[0] = STRING_RESULT;// smtp server address
arg->arg_type[1] = STRING_RESULT;// email body
initid->ptr = (char*) malloc(2050 * sizeof (char));
memset(initid->ptr, '\0', sizeof (initid->ptr));
return 0;
}
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused))){
if (initid->ptr) {
free(initid->ptr);
}
}
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error){
char *header = MailHeader(From_header, TO_header, "Hello Its a test Mail from Codevlog", "text/plain", "US-ASCII");
int connected_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
struct sockaddr_in addr;
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(25);
if (inet_pton(AF_INET, GetIPAddress(arg->args[0]), &addr.sin_addr) == 1) {
connect(connected_fd, (struct sockaddr*) &addr, sizeof (addr));
}
if (connected_fd != -1) {
int recvd = 0;
const char recv_buff[4768];
int sdsd;
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char buff[1000];
strcpy(buff, "EHLO "); //"EHLO sdfsdfsdf.com\r\n"
strcat(buff, domain);
strcat(buff, "\r\n");
send(connected_fd, buff, strlen(buff), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd2[1000];
strcpy(_cmd2, "AUTH LOGIN\r\n");
int dfdf = send(connected_fd, _cmd2, strlen(_cmd2), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd3[1000];
Base64encode(&_cmd3, UID, strlen(UID));
strcat(_cmd3, "\r\n");
send(connected_fd, _cmd3, strlen(_cmd3), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd4[1000];
Base64encode(&_cmd4, PWD, strlen(PWD));
strcat(_cmd4, "\r\n");
send(connected_fd, _cmd4, strlen(_cmd4), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd5[1000];
strcpy(_cmd5, "MAIL FROM: ");
strcat(_cmd5, From);
strcat(_cmd5, "\r\n");
send(connected_fd, _cmd5, strlen(_cmd5), 0);
char skip[1000];
sdsd = recv(connected_fd, skip, sizeof (skip), 0);
char _cmd6[1000];
strcpy(_cmd6, "RCPT TO: ");
strcat(_cmd6, To); //
strcat(_cmd6, "\r\n");
send(connected_fd, _cmd6, strlen(_cmd6), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd7[1000];
strcpy(_cmd7, "DATA\r\n");
send(connected_fd, _cmd7, strlen(_cmd7), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
send(connected_fd, header, strlen(header), 0);
send(connected_fd, arg->args[1], strlen(arg->args[1]), 0);
char _cmd9[1000];
strcpy(_cmd9, "\r\n.\r\n.");
send(connected_fd, _cmd9, sizeof (_cmd9), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd10[1000];
strcpy(_cmd10, "QUIT\r\n");
send(connected_fd, _cmd10, sizeof (_cmd10), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
memcpy(initid->ptr, recv_buff, strlen(recv_buff));
*length = recvd;
}
free(header);
close(connected_fd);
return initid->ptr;
}
To configure your project go through this video: https://www.youtube.com/watch?v=Zm2pKTW5z98 (Send Email from MySQL on Linux) It will work for any mysql version (5.5, 5.6, 5.7)
I will resolve if any error appear in above code, Just Inform in comment
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
No. I don't see any advantage. Second one is more straitforward.
btw: Second style is found in every corners of JDK source.
I would suggest good approach how to deal with configuration in your application at all. There are three basic rules:
To have more detailed overview follow this link: Rails configuration in the proper way
Since your config file is a normal text file, just read it using the open
function:
file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
print path.split(" = ")[1]
This will print your paths. You can also store them using dictionaries or lists.
path_list = []
path_dict = {}
for path in paths:
p = path.split(" = ")
path_list.append(p)[1]
path_dict[p[0]] = p[1]
More on reading/writing file here. Hope this helps!
Highest voted answer uses Lodash _.chain
function which is considered a bad practice now "Why using _.chain
is a mistake."
Here is a fewliner that approaches the problem from functional programming perspective:
import tap from "lodash/fp/tap";
import flow from "lodash/fp/flow";
import groupBy from "lodash/fp/groupBy";
const map = require('lodash/fp/map').convert({ 'cap': false });
const result = flow(
groupBy('color'),
map((users, color) => ({color, users})),
tap(console.log)
)(input)
Where input
is an array that you want to convert.
It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the
overflow-x: scroll;
What happens if you remove that?
I installed python2.7 to solve this issue. I wish can help you.
Remove the library from your Podfile
Run pod install
on the terminal
$('b').contents().unwrap();
This selects all <b>
elements, then uses .contents()
to target the text content of the <b>
, then .unwrap()
to remove its parent <b>
element.
For the greatest performance, always go native:
var b = document.getElementsByTagName('b');
while(b.length) {
var parent = b[ 0 ].parentNode;
while( b[ 0 ].firstChild ) {
parent.insertBefore( b[ 0 ].firstChild, b[ 0 ] );
}
parent.removeChild( b[ 0 ] );
}
This will be much faster than any jQuery solution provided here.
I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!
Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)
The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).
server.php (source code which will respond to all the client's request)
client.php/client.html (source code which will do the requesting stuffs)
So basically, you right the code first on you server.php and start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start
Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in
C:/xampp/htdocs/websocket/server.php
C:/xampp/htdocs/websocket/client.php or client.html
Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.
https://github.com/walkor/Workerman
https://github.com/walkor/phpsocket.io
I usually download it via composer and just autoload those files in my php scripts.
And also check this one. This is really important! You need this javascript libary in order for you client.php or client.html to communicate with the server.php when you run it.
https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client
I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php
Here is the server.php sourcecode
<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
use PHPSocketIO\SocketIO;
// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
$socket->on('send message', function($msg)use($io){
$io->emit('new message', $msg);
});
});
Worker::runAll();
And here is the client.php or client.html sourcecode
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="chat-messages" style="overflow-y: scroll; height: 100px; "></div>
<input type="text" class="message">
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="socket.io-client/socket.io.js"></script>
<script>
var socket = io.connect("ws://127.0.0.1:2021");
$('.message').on('change', function(){
socket.emit('send message', $(this).val());
$(this).val('');
});
socket.on('new message', function(data){
$('#chat-messages').append('<p>' + data +'</p>');
});
</script>
</html>
Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php start and press enter.
Then go to you browser and type http://localhost/websocket/client.php to visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!
You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!
Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached
from .gitignore
:
cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached
Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files
. That's just for the files which haven't been modified.
Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:
var rows = $('table.someclass tr');
$('#showBlackButton').click(function() {
var black = rows.filter('.black').show();
rows.not( black ).hide();
});
$('#showWhiteButton').click(function() {
var white = rows.filter('.white').show();
rows.not( white ).hide();
});
$('#showAll').click(function() {
rows.show();
});
<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr class="black">
...
</tr>
</thead>
<tbody>
<tr class="white">
...
</tr>
<tr class="black">
...
</tr>
</tbody>
</table>
It uses the filter()
[docs] method to filter the rows with the black
or white
class (depending on the button).
Then it uses the not()
[docs] method to do the opposite filter, excluding the black
or white
rows that were previously found.
EDIT: You could also pass a selector to .not()
instead of the previously found set. It may perform better that way:
rows.not( `.black` ).hide();
// ...
rows.not( `.white` ).hide();
...or better yet, just keep a cached set of both right from the start:
var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode
when using the v2 YAML format.
The best way could be to save all the emails in a database.
You can try this code, assuming you have your email in a database
/*Your connection to your database comes here*/
$query="select email from yourtable";
$result =mysql_query($query);
/the above code depends on where you saved your email addresses, so make sure you replace it with your parameters/
Then you can make a comma separated string from the result,
while($row=$result->fetch_array()){
if($rows=='') //this prevents from inserting comma on before the first element
$rows.=$row['email'];
else
$rows.=','.$row['email'];
}
Now you can use
$to = explode(',',$rows); // to change to array
$string =implode(',',$cc); //to get back the string separated by comma
With above code you can send the email like this
mail($string, "Test", "Hi, Happy X-Mas and New Year");
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);
If you are using PHP's curl
bindings, you can check the error code using curl_getinfo
as such:
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
/* Handle 404 here. */
}
curl_close($handle);
/* Handle $response here. */
If your jenkins is running as service instead of process you should stop it first using
sudo service jenkins stop
After stopping it you can follow the normal flow of removing it using commands respective to your linux flavour
For centos it will be
sudo yum remove jenkins
For ubuntu it will
sudo apt-get remove --purge jenkins
I hope this will solve your issue.
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
I am not experiented .But i think XmlReader is unnecessary.
It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});
@page margin:0mm now works in Firefox 19.0a2 (2012-12-07).
While searching this very question I discovered this example in the documentation.
QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);
Mutatis mutandis for your particular action of course.
Along with this note.
It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.
It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()
MediaQuery.of(context).size.width
and MediaQuery.of(context).size.height
works great, but every time need to write expressions like width/20 to set specific height width.
I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.
Yes, flutter_screenutil
plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!
Usage:
Add dependency:
Please check the latest version before installation.
dependencies:
flutter:
sdk: flutter
# add flutter_ScreenUtil
flutter_screenutil: ^0.4.2
Add the following imports to your Dart code:
import 'package:flutter_screenutil/flutter_screenutil.dart';
Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option
//fill in the screen size of the device in the design
//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);
//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);
Use:
//for example:
//rectangle
Container(
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
...
),
////If you want to display a square:
Container(
width: ScreenUtil().setWidth(300),
height: ScreenUtil().setWidth(300),
),
Please refer updated documentation for more details
Note: I tested and using this plugin, which really works great with all devices including iPad
Hope this will helps someone
The specific value in your database isn't what you should be focusing on. This is likely the result of an attacker fuzzing your system to see if it is vulnerable to a set of standard attacks, instead of a targeted attack exploiting a known vulnerability.
You should instead focus on ensuring that your application is secure against these types of attacks; OWASP is a good resource for this.
If you're using parameterized queries to access the database, then you're secure against Sql injection, unless you're using dynamic Sql in the backend as well.
If you're not doing this, you're vulnerable and you should resolve this immediately.
Also, you should consider performing some sort of validation of e-mail addresses.
FOR SQLALCHEMY AND PYTHON
The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
I wanted to elaborate the answer by lifeless a bit because when I started reading about how to use super() in a multiple inheritance hierarchy in Python, I did't get it immediately.
What you need to understand is that super(MyClass, self).__init__()
provides the next __init__
method according to the used Method Resolution Ordering (MRO) algorithm in the context of the complete inheritance hierarchy.
This last part is crucial to understand. Let's consider the example again:
#!/usr/bin/env python2
class First(object):
def __init__(self):
print "First(): entering"
super(First, self).__init__()
print "First(): exiting"
class Second(object):
def __init__(self):
print "Second(): entering"
super(Second, self).__init__()
print "Second(): exiting"
class Third(First, Second):
def __init__(self):
print "Third(): entering"
super(Third, self).__init__()
print "Third(): exiting"
According to this article about Method Resolution Order by Guido van Rossum, the order to resolve __init__
is calculated (before Python 2.3) using a "depth-first left-to-right traversal" :
Third --> First --> object --> Second --> object
After removing all duplicates, except for the last one, we get :
Third --> First --> Second --> object
So, lets follow what happens when we instantiate an instance of the Third
class, e.g. x = Third()
.
Third.__init__
executes.
Third(): entering
super(Third, self).__init__()
executes and MRO returns First.__init__
which is called.First.__init__
executes.
First(): entering
super(First, self).__init__()
executes and MRO returns Second.__init__
which is called.Second.__init__
executes.
Second(): entering
super(Second, self).__init__()
executes and MRO returns object.__init__
which is called.object.__init__
executes (no print statements in the code there)Second.__init__
which then prints Second(): exiting
First.__init__
which then prints First(): exiting
Third.__init__
which then prints Third(): exiting
This details out why instantiating Third() results in to :
Third(): entering
First(): entering
Second(): entering
Second(): exiting
First(): exiting
Third(): exiting
The MRO algorithm has been improved from Python 2.3 onwards to work well in complex cases, but I guess that using the "depth-first left-to-right traversal" + "removing duplicates expect for the last" still works in most cases (please comment if this is not the case). Be sure to read the blog post by Guido!
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
AGE
is defined as "42"
so the line:
str += "Do you feel " + AGE + " years old?";
is converted to:
str += "Do you feel " + "42" + " years old?";
Which isn't valid since "Do you feel "
and "42"
are both const char[]
. To solve this, you can make one a std::string
, or just remove the +
:
// 1.
str += std::string("Do you feel ") + AGE + " years old?";
// 2.
str += "Do you feel " AGE " years old?";
vi your_filename
hit esc
Type :%!xxd
to view the hex strings, the n :%!xxd -r
to return to normal editing.
I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.
To achieve goto-like functionality while keeping the call stack clean, I am using this method:
// in other languages:
// tag1:
// doSomething();
// tag2:
// doMoreThings();
// if (someCondition) goto tag1;
// if (otherCondition) goto tag2;
function tag1() {
doSomething();
setTimeout(tag2, 0); // optional, alternatively just tag2();
}
function tag2() {
doMoreThings();
if (someCondition) {
setTimeout(tag1, 0); // those 2 lines
return; // imitate goto
}
if (otherCondition) {
setTimeout(tag2, 0); // those 2 lines
return; // imitate goto
}
setTimeout(tag3, 0); // optional, alternatively just tag3();
}
// ...
Please note that this code is slow since the function calls are added to timeouts queue, which is evaluated later, in browser's update loop.
Please also note that you can pass arguments (using setTimeout(func, 0, arg1, args...)
in browser newer than IE9, or setTimeout(function(){func(arg1, args...)}, 0)
in older browsers.
AFAIK, you shouldn't ever run into a case that requires this method unless you need to pause a non-parallelable loop in an environment without async/await support.
Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use
document.getElementById("a").className
instead of
$("#a").className
set a WebViewClient
to your WebView, start your progress dialog on you onCreate()
method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
}
}
your main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@string/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
You can use the Y-combinator: (Wikipedia)
// ES5 syntax
var Y = function Y(a) {
return (function (a) {
return a(a);
})(function (b) {
return a(function (a) {
return b(b)(a);
});
});
};
// ES6 syntax
const Y = a=>(a=>a(a))(b=>a(a=>b(b)(a)));
// If the function accepts more than one parameter:
const Y = a=>(a=>a(a))(b=>a((...a)=>b(b)(...a)));
And you can use it as this:
// ES5
var fn = Y(function(fn) {
return function(counter) {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
}
});
// ES6
const fn = Y(fn => counter => {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
});
The following seems to work:
import datetime
print (datetime.datetime.now().strftime("%y"))
The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()
In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:
Than, pick Unused declaration:
And finally, uncheck the Include test sources:
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
E.g. if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
If you want input to disable on some statement.
use [readonly]=true
or false
instead of disabled.
<input [readonly]="this.isEditable"
type="text"
formControlName="reporteeName"
class="form-control"
placeholder="Enter Name" required>
If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:
http://sourceforge.net/projects/win32svn/
After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.
svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only
Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__
is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype
and all other objects are descendants of this one. The __proto__
property of the root object is null
, which represents the end of inheritance chain.
You'll notice that prototype
is a property of functions. Cat
is a function, but also Function
and Object
are (native) functions. tom
is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new
operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor
which points back to the respective function object. For brevity reasons this was not depicted.
Indeed, when we create the tom
object with new Cat()
, the created object will have the __proto__
property set to the prototype
object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__
property points to the same object as Cat.prototype
.
Cat.__proto__
points to the Function.prototype
object, just like Function.__proto__
and Object.__proto__
do.
Cat.prototype.__proto__
and tom.__proto__.__proto__
point to the same object and that is Object.prototype
.
Cheers!
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
id
columnCredit is given to @resnyanskiy who gave this answer in a comment.
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
What is the reason to use the strings as file names? If human readability is not a factor I would go with base64 module which can produce file system safe strings. It won't be readable but you won't have to deal with collisions and it is reversible.
import base64
file_name_string = base64.urlsafe_b64encode(your_string)
Update: Changed based on Matthew comment.
I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI
to create a config file. The reason is, with the config file, the CLI
or the SDK
will automatically look for credentials in the ~/.aws
folder. And the good thing is that AWS CLI
is written in python.
You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal
$> pip install awscli #can add user flag
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:
After this you can access boto
and any of the api without having to specify keys (unless you want to use a different credentials).
We can define the so-called foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: ['bio101', 'bio102'] // <= ids of the courses
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
The courses
field contains _id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane
, we need to perform another operation to retrieve the course
document via _id
.
If the course bio101
is removed, we need to perform another operation to update the courses
field in the student
document.
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Example:
student
{
name: 'Kate Monster',
addresses : [
{ street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
{ street: '123 Avenue Q', city: 'New York', cc: 'USA' }
]
}
Like the student
/course
example above.
Suitable for one-to-squillions, such as log messages.
host
{
_id : ObjectID('AAAB'),
name : 'goofy.example.com',
ipaddr : '127.66.66.66'
}
logmsg
{
time : ISODate("2014-03-28T09:42:41.382Z"),
message : 'cpu is on fire!',
host: ObjectID('AAAB') // Reference to the Host document
}
Virtually, a host
is the parent of a logmsg
. Referencing to the host
id saves much space given that the log messages are squillions.
References:
For methods which may fail, that is you specify boolean as return type, I would use the prefix try
:
if (tryCreateFreshSnapshot())
{
// ...
}
For all other cases use prefixes like is..
has..
was..
can..
allows..
..
If you can't import MockMultipartFile
using
import org.springframework.mock.web.MockMultipartFile;
you need to add the below dependency into pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME
or TIMESTAMP
differs between one WITH TIME ZONE
or WITHOUT TIME ZONE
. It doesn't affect how the values are stored; it affects how they are interpreted.
The effects of time zones on these data types is covered specifically in the docs. The difference arises from what the system can reasonably know about the value:
With a time zone as part of the value, the value can be rendered as a local time in the client.
Without a time zone as part of the value, the obvious default time zone is UTC, so it is rendered for that time zone.
The behaviour differs depending on at least three factors:
WITH TIME ZONE
or WITHOUT TIME ZONE
) of the value.Here are examples covering the combinations of those factors:
foo=> SET TIMEZONE TO 'Japan';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+09
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 06:00:00+09
(1 row)
foo=> SET TIMEZONE TO 'Australia/Melbourne';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+11
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 08:00:00+11
(1 row)
My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.
As it is written in the documentation you have to change the cell type to a markdown.
If you need Unicode support in the lower case function see this question: Light C Unicode Library
Since you're accessing a web.config
you should probably use
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
If you are using SQL Server 2012+ you can use CONCAT function in which we don't have to do any explicit conversion
SET @ActualWeightDIMS = Concat(@Actual_Dims_Lenght, 'x', @Actual_Dims_Width, 'x'
, @Actual_Dims_Height)
There are free, easy APIs you can use, like those:
Which one looks the most trustworthy is up to you :)
Otherwise, there are scripts which are based on local databases on your server. The database data needs to be updated regularly, though. Check out this one:
HTH!
Edit: And of course, depending on your project you might want to look at HTML5 Location features. You can't use them yet on the Internet Explorer (IE9 will support it, long way to go yet), but in case your audience is mainly on mobile devices or using Safari/Firefox it's definitely worth to look at it!
Once you have the coordinates, you can reverse geocode them to a country code. Again there are APIs like this one:
Update, April 2013
Today I would recommend using Geocoder, a PHP library which makes it very easy to geocode ip addresses as well as postal address data.
***Update, September 2016
Since Google's privacy politics has changed, you can't use HTML5 Geolocation API if your server doesn't have HTPPS certificate or user doesn't allow you check his location. So now you can use user's IP and check in in PHP or get HTTPS certificate.
With ES6 now widely supported, the best answer to this question has changed. ES6 provides the let
and const
keywords for this exact circumstance. Instead of messing around with closures, we can just use let
to set a loop scope variable like this:
var funcs = [];_x000D_
_x000D_
for (let i = 0; i < 3; i++) { _x000D_
funcs[i] = function() { _x000D_
console.log("My value: " + i); _x000D_
};_x000D_
}
_x000D_
val
will then point to an object that is specific to that particular turn of the loop, and will return the correct value without the additional closure notation. This obviously significantly simplifies this problem.
const
is similar to let
with the additional restriction that the variable name can't be rebound to a new reference after initial assignment.
Browser support is now here for those targeting the latest versions of browsers. const
/let
are currently supported in the latest Firefox, Safari, Edge and Chrome. It also is supported in Node, and you can use it anywhere by taking advantage of build tools like Babel. You can see a working example here: http://jsfiddle.net/ben336/rbU4t/2/
Docs here:
Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let
but get the above wrong (they don't create a new i
each time, so all the functions above would log 3 like they would if we used var
). Edge 14 finally gets it right.
git reset --hard && git clean -dfx
or, zsh provides a 'gpristine' alias:
alias gpristine='git reset --hard && git clean -dfx'
Which is really handy. (warning: The "-x" will also delete 'git ignored' files, so remove this if it is not what you want)
If working on a forked repo, make sure to fetch and reset from the correct repo/branch, for example:
git fetch upstream && git reset --hard upstream/master && git clean -df
Use RGB values combined with opacity to get the transparency that you wish.
For instance,
<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;"> </div>
Similarly, with actual values without opacity, will give the below.
<div style=" background: rgb(243, 191, 189) ; "> </div>
<div style=" background: rgb(246, 143, 142) ; "> </div>
<div style=" background: rgb(249, 95 , 94) ; "> </div>
<div style=" background: rgb(252, 47, 47) ; "> </div>
<div style=" background: rgb(255, 0, 0) ; "> </div>
You can have a look at this WORKING EXAMPLE.
Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.
The HTML
<div class="social">
<img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>
The CSS:
social img{
opacity:0.5;
}
.social img:hover {
opacity:1;
background-color:black;
cursor:pointer;
background: rgb(255, 0, 0) ; opacity: 0.5;
}
Hope this helps Now.
add a
as follows:
<a href="http://foo.com" onclick="return false;">....</a>
or return false;
from click handler for #clickable
like:
$("#clickable").click(function() {
var url = $("#clickable a").attr("href");
window.location = url;
return false;
});
Currently this is the most up to date way reload page if the user clicks the back button.
const [entry] = performance.getEntriesByType("navigation");
// Show it in a nice table in the developer console
console.table(entry.toJSON());
if (entry["type"] === "back_forward")
location.reload();
See here for source
I got this issue when installing Bootstrap.
The following commands are what worked for me:
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
From MySQL docs:
A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.
Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.
Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.
In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).
The problem could also come because of a lack of SQL driver
in your Tomcat installation directory.
I had to had mysql-connector-java-5.1.23-bin.jar
in apache-tomcat-9.0.12/lib/
folder.
I'd go with @sandeep's display: table-cell
answer if you don't care about IE7.
Otherwise, here's an alternative, with one downside: the "right" div
has to come first in the HTML.
See: http://jsfiddle.net/thirtydot/qLTMf/
and exactly the same, but with the "right div" removed: http://jsfiddle.net/thirtydot/qLTMf/1/
#parent {
overflow: hidden;
border: 1px solid red
}
.right {
float: right;
width: 100px;
height: 100px;
background: #888;
}
.left {
overflow: hidden;
height: 100px;
background: #ccc
}
<div id="parent">
<div class="right">right</div>
<div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper porta sem, at ultrices ante interdum at. Donec condimentum euismod consequat. Ut viverra lorem pretium nisi malesuada a vehicula urna aliquet. Proin at ante nec neque commodo bibendum. Cras bibendum egestas lacus, nec ullamcorper augue varius eget.</div>
</div>
One of my friends is writing a graphics app using NVIDIA CUDA. Application fits in very nicely with OOP paradigm and the problem can be decomposed into modules neatly. However, to use CUDA you need to use C, which doesn't support inheritance. Therefore, you need to be clever.
a) You devise a clever system which will emulate inheritance to a certain extent. It can be done!
i) You can use a hook system, which expects every child C of parent P to have a certain override for function F. You can make children register their overrides, which will be stored and called when required.
ii) You can use struct memory alignment feature to cast children into parents.
This can be neat but it's not easy to come up with future-proof, reliable solution. You will spend lots of time designing the system and there is no guarantee that you won't run into problems half-way through the project. Implementing multiple inheritance is even harder, if not almost impossible.
b) You can use consistent naming policy and use divide and conquer approach to create a program. It won't have any inheritance but because your functions are small, easy-to-understand and consistently formatted you don't need it. The amount of code you need to write goes up, it's very hard to stay focused and not succumb to easy solutions (hacks). However, this ninja way of coding is the C way of coding. Staying in balance between low-level freedom and writing good code. Good way to achieve this is to write prototypes using a functional language. For example, Haskell is extremely good for prototyping algorithms.
I tend towards approach b. I wrote a possible solution using approach a, and I will be honest, it felt very unnatural using that code.
The data containing the date column can be read by using the below code:
data = pd.csv(file_path,parse_dates=[date_column])
Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time()
like:
pd.date_time(data[date_column], format = '%d/%m/%y')
to change the format of date as per the requirement.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
S3_REGION="eu-central-1"
bucket="mybucket1"
name="objectname"
import boto3
from botocore.client import Config
client = boto3.client('s3',region_name=S3_REGION,config=Config(signature_version='s3v4'))
list = client.list_objects_v2(Bucket=bucket,Prefix=name)
for obj in list.get('Contents', []):
if obj['Key'] == name: return True
return False
> library(plyr)
> as.matrix(ldply(a))
V1 V2 V3 V4 V5 V6
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Try to change the compatibility level, worked for me.
Verify what level it is
USE VJ_DATABASE;
GO
SELECT compatibility_level
FROM sys.databases WHERE name = 'VJ_DATABASE';
GO
Then make it compatible with the older version
ALTER DATABASE VJ_DATABASE
SET COMPATIBILITY_LEVEL = 110;
GO
By default, Sql Server 2014 will change the db versions compatibility to only 2014, using the @@ version
you should be able to tell, which version Sql Server is.
Then run the command above to change it the version you have.
Additional step: Ensure you look at the accessibility of the DB is not reset, do this by right clicking on properties of the folder and the database. (make sure you have rights so you don't get an access denied)
If you installed gradle with homebrew, then the path is:
/usr/local/Cellar/gradle/X.X/libexec
Where X.X is the version of gradle (currently 2.1)
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
type in Windows cmd.exe
cd %userprofile%\.android
dir
copy adbkey.pub adb_keys
dir
copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.
from: How to solve ADB device unauthorized in Android ADB host device?
now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
The simplest solution to the problem is to change your for loop statement :
Instead of using
for (i in **0**:n))
Use
for (i in **1**:n))
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
You can also use for 1080 hd values:
240p: &vq=small , 360p: &vq=medium , 480p: &vq=large , 720p: &vq=hd720 , &vq=hd1080
Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components.
ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
Image img=background.getImage();
Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
background=new ImageIcon(temp);
JLabel back=new JLabel(background);
back.setLayout(null);
back.setBounds(0,0,500,600);
For others that have a similar problem but with live share.
In the visual studio installer there was a warning that live share was not installed correctly and a modification was pending, that would download live share again.
After completion of the modification the error was resolved.
If you want to use jQuery you can use .replaceAll()
If you want a specific margin e.g. 20px, you can put the table inside a div.
<div id="tableDiv">
<table>
<tr>
<th> test heading </th>
</tr>
<tr>
<td> test data </td>
</tr>
</table>
</div>
So the #tableDiv has a margin of 20px but the table itself has a width of 100%, forcing the table to be the full width except for the margin on either sides.
#tableDiv {
margin: 20px;
}
table {
width: 100%;
}
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.
If I understand correctly what you want to do, you can create your figure and set the size of the window. Afterwards, you can save your graph with the matplotlib toolbox button. Here an example:
from pylab import get_current_fig_manager,show,plt,imshow
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_geometry("500x500+0+0")
#in this case 500 is the size (in pixel) of the figure window. In your case you want to maximise to the size of your screen or whatever
imshow(your_data)
show()
I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select
input, assign its text to the newVal
variable and then apply that variable to the value
attribute of the #costLabel
label:
$(document).ready(
function() {
$('select[name=package]').change(
function(){
var newText = $('option:selected',this).text();
$('#costLabel').text('Total price: ' + newText);
}
);
}
);
<form name="thisForm" id="thisForm" action="#" method="post">
<fieldset>
<select name="package" id="package">
<option value="standard">Standard - €55 Monthly</option>
<option value="standardAnn">Standard - €49 Monthly</option>
<option value="premium">Premium - €99 Monthly</option>
<option value="premiumAnn" selected="selected">Premium - €89 Monthly</option>
<option value="platinum">Platinum - €149 Monthly</option>
<option value="platinumAnn">Platinum - €134 Monthly</option>
</select>
</fieldset>
<fieldset>
<label id="costLabel" name="costLabel">Total price: </label>
</fieldset>
</form>
Working demo of the above at: JS Bin
if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk
On Ubuntu Server 16, I have the same problem with python27. Try this:
Change
from pip import main
if __name__ == '__main__':
sys.exit(main())
To
from pip._internal import main
if __name__ == '__main__':
sys.exit(main())
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text
with the class name title
. If you use >
instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
You can use this method in the ObjectUtils
class from org.apache.commons.lang3 library :
public static <T> T defaultIfNull(T object, T defaultValue)
How to create CascadeClassifier :
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.
import javafx.fxml.Initializable;
class MyController implements Initializable {
@FXML private TableView<MyModel> tableView;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.getItems().addAll(getDataFromSource());
}
}
Parameters:
location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized.
And the note of the docs why the simple way of using @FXML public void initialize()
works:
NOTE
This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.
First of all you assign temp to array elemets and you should remove arr[i] = temp;
statment. Next problem is that you are printing temp variable which shows only half of array elements(in your for loop). If you don't want to use STL vectors I would suggest this solution:
#include <iostream>
void reverseArray(int userArray[], int size);
void printArray(int userArray[], int size);
int main(int arg, char**argv) {
int arr[]{ 1,2,3,4,5,6,7,8,9,10 };
int sizeOfArray = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, sizeOfArray);
printArray(arr, sizeOfArray);
system("pause");
return(0);
}
void reverseArray(int userArray[], int size) {
int* ptrHead = userArray;
int* ptrTail = userArray + (size-1);
while (ptrTail > ptrHead) {
int temp = *ptrHead;
*ptrHead = *ptrTail;
*ptrTail = temp;
ptrHead++;
ptrTail--;
}
}
void printArray(int userArray[], int size) {
for (int i = 0; i < size; i++) {
std::cout << userArray[i] << " ";
}
}
If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'
I'm passing to Django's template a function, which returns me some records
Why don't you pass to Django template the variable storing function's return value, instead of the function?
I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.
You should set variables in Django views instead of templates, and then pass them to the template.
SHA-1 generation in android studio:
Select Gradle in android studio from right panel
Select Your App
In Tasks -> android-> signingReport
Double click signingReport
.
You will find the SHA-1 fingerprint in the "Gradle Console"
Add this SHA-1 fingerprint in firebase console
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.
SELECT
col1,
col2,
col3,
CASE WHEN condition THEN
CASE WHEN condition1 THEN
CASE WHEN condition2 THEN calculation1
ELSE calculation2 END
ELSE
CASE WHEN condition2 THEN calculation3
ELSE calculation4 END
END
ELSE CASE WHEN condition1 THEN
CASE WHEN condition2 THEN calculation5
ELSE calculation6 END
ELSE CASE WHEN condition2 THEN calculation7
ELSE calculation8 END
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
For the MVC Controller method, use a nullable boolean type:
public ActionResult Index( string responsables, bool? checkResp) { etc. }
Then if the check box is checked, checkResp will be true. If not, it will be null.
If you want to add a primary key constraint to an existing column all of the previously listed syntax will fail.
To add a primary key constraint to an existing column use the form:
ALTER TABLE `goods`
MODIFY COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
How about using a custom jQuery event with an angular watch type interface;
// adds a custom jQuery event which gives the previous and current values of an input on change
(function ($) {
// new event type tl_change
jQuery.event.special.tl_change = {
add: function (handleObj) {
// use mousedown and touchstart so that if you stay focused on the
// element and keep changing it, it continues to update the prev val
$(this)
.on('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.on('change.tl_change', handleObj.selector, function (e) {
// use an anonymous funciton here so we have access to the
// original handle object to call the handler with our args
var $el = $(this);
// call our handle function, passing in the event, the previous and current vals
// override the change event name to our name
e.type = "tl_change";
handleObj.handler.apply($el, [e, $el.data('tl-previous-val'), $el.val()]);
});
},
remove: function (handleObj) {
$(this)
.off('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.off('change.tl_change', handleObj.selector)
.removeData('tl-previous-val');
}
};
// on focus lets set the previous value of the element to a data attr
function focusHandler(e) {
var $el = $(this);
$el.data('tl-previous-val', $el.val());
}
})(jQuery);
// usage
$('.some-element').on('tl_change', '.delegate-maybe', function (e, prev, current) {
console.log(e); // regular event object
console.log(prev); // previous value of input (before change)
console.log(current); // current value of input (after change)
console.log(this); // element
});
Follow the below steps it will helps you.
step 1: Go to to your site root folder and you can find the .htaccess
file there. Open it with a text editor and find the line #RewriteBase /magento/
. Just replace it with #RewriteBase /
take out just the 'magento/'
step 2: Then go to your admin panel and enable the Rewrites(set yes for Use Web Server Rewrites). You can find it at System->Configuration->Web->Search Engine Optimization.
step 3: Then go to Cache management page (system cache management ) and refresh your cache and refresh to check the site.
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
To make things efficient, you need to do declare that one of the columns to be a primary key:
ALTER TABLE #mytable
ADD PRIMARY KEY(KeyColumn)
That won't take a variable for the column name.
Trust me, you are MUCH better off doing a: CREATE #myTable TABLE
(or possibly a DECLARE TABLE @myTable
) , which allows you to set IDENTITY
and PRIMARY KEY
directly.
Short of actually performing the merge in a throw away fashion (see Kasapo's answer), there doesn't seem to be a reliable way of seeing this.
Having said that, here's a method that comes marginally close:
git log TARGET_BRANCH...SOURCE_BRANCH --cherry
This gives a fair indication of which commits will make it into the merge. To see diffs, add -p
. To see file names, add any of --raw
, --stat
, --name-only
, --name-status
.
The problem with the git diff TARGET_BRANCH...SOURCE_BRANCH
approach (see Jan Hudec's answer) is, you'll see diffs for changes already in your target branch if your source branch contains cross merges.
As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!
<script >
window.onload = setInterval(clock,1000);
function clock()
{
var d = new Date();
var date = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var monthArr = ["January", "February","March", "April", "May", "June", "July", "August", "September", "October", "November","December"];
month = monthArr[month];
document.getElementById("date").innerHTML=date+" "+month+", "+year;
}
It's valid in C for historical reasons. C traditionally specified that the type of a string literal was char *
rather than const char *
, although it qualified it by saying that you're not actually allowed to modify it.
When you use a cast, you're essentially telling the compiler that you know better than the default type matching rules, and it makes the assignment OK.
You could also download Xcode to your mac and use iPhone simulator.
Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed.
The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not.
EDIT: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!
You can't add i
tag in option
tag because tags are stripped.
But you can add it after the select
like this
One way is using the immediate selector and negative margin. This rule will select a list right after a paragraph, so it's just setting a negative margin-top.
p + ul {
margin-top: -XX;
}
You might have to be more specific and specify the app name as well (this is the name of the app as you have it in heroku). For example:
heroku ps:scale web=0 --app myAppName
Otherwise you might get the following message:
% heroku ps:scale web=0
Scaling dynos... failed
! No app specified.
! Run this command from an app folder or specify which app to use with --app APP.
Test like this.Sometimes, permission problem.
cmd => dcomcnfg
Click
Component services >Computes >My Computer>Dcom config> and select micro soft Excel Application
Right Click on microsoft Excel Application
Properties>Give Asp.net Permissions
Select Identity table >Select interactive user >select ok
// npm install --save-dev gulp gulp-if gulp-uglify minimist
var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minimist = require('minimist');
var knownOptions = {
string: 'env',
default: { env: process.env.NODE_ENV || 'production' }
};
var options = minimist(process.argv.slice(2), knownOptions);
gulp.task('scripts', function() {
return gulp.src('**/*.js')
.pipe(gulpif(options.env === 'production', uglify())) // only minify in production
.pipe(gulp.dest('dist'));
});
Then run gulp with:
$ gulp scripts --env development
I read the go help gopath
docs and was still incredibly confused, but found this little nugget from another go doc page:
The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you'll need to set when developing Go code.
Edit: see the end examples for ES6 updated examples.
This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.
While they still work fine, other answers are missing something very important.
Is there not a simple way to pass a child's props to its parent using events, in React.js?
The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?
Child: it really does not have to be more complicated than that.
var Child = React.createClass({
render: function () {
return <button onClick={this.props.onClick}>{this.props.text}</button>;
},
});
Parent with single child: using the value it passes to the child
var Parent = React.createClass({
getInitialState: function() {
return {childText: "Click me! (parent prop)"};
},
render: function () {
return (
<Child onClick={this.handleChildClick} text={this.state.childText}/>
);
},
handleChildClick: function(event) {
// You can access the prop you pass to the children
// because you already have it!
// Here you have it in state but it could also be
// in props, coming from another parent.
alert("The Child button text is: " + this.state.childText);
// You can also access the target of the click here
// if you want to do some magic stuff
alert("The Child HTML is: " + event.target.outerHTML);
}
});
Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.
var Parent = React.createClass({
getInitialState: function() {
return {childrenData: [
{childText: "Click me 1!", childNumber: 1},
{childText: "Click me 2!", childNumber: 2}
]};
},
render: function () {
var children = this.state.childrenData.map(function(childData,childIndex) {
return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
}.bind(this));
return <div>{children}</div>;
},
handleChildClick: function(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
});
It is also possible to use this.handleChildClick.bind(null,childIndex)
and then use this.state.childrenData[childIndex]
Note we are binding with a null
context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.
This is for me a bad idea in term of coupling and encapsulation:
var Parent = React.createClass({
handleClick: function(childComponent) {
// using childComponent.props
// using childComponent.refs.button
// or anything else using childComponent
},
render: function() {
<Child onClick={this.handleClick} />
}
});
Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.
Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:
<Child ref="theChild" .../>
And access the DOM node in the parent with
React.findDOMNode(this.refs.theChild)
For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.
The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.
To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:
They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.
The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.
If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.
About using anything else
Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...)
or childComponent.forceUpdate()
, or assigning it new variables, inside the parent, making the whole app much harder to reason about.
Edit: ES6 examples
As many people now use ES6, here are the same examples for ES6 syntax
The child can be very simple:
const Child = ({
onClick,
text
}) => (
<button onClick={onClick}>
{text}
</button>
)
The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:
class Parent1 extends React.Component {
handleChildClick(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
render() {
return (
<div>
{this.props.childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => this.handleChildClick(child,e)}
/>
))}
</div>
);
}
}
But it can also be simplified if it does not need to manage state:
const Parent2 = ({childrenData}) => (
<div>
{childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => {
alert("The Child button data is: " + child.childText + " - " + child.childNumber);
alert("The Child HTML is: " + e.target.outerHTML);
}}
/>
))}
</div>
)
PERF WARNING (apply to ES5/ES6): if you are using PureComponent
or shouldComponentUpdate
, the above implementations will not be optimized by default because using onClick={e => doSomething()}
, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this
in class constructor) so that PureComponent
optimization can kick in, or you can implement your own shouldComponentUpdate
and ignore the callback in the props comparison check.
You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:
// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}
// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)
// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)
In this case you could optimize the Child component by using:
const OptimizedChild = onlyUpdateForKeys(['text'])(Child)
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
To kill from the application, you can do:
android.os.Process.killProcess(android.os.Process.myPid());
there are many ways. using wc
is one.
wc -l file
others include
awk 'END{print NR}' file
sed -n '$=' file
(GNU sed)
grep -c ".*" file
Try this:
if ($.browser.msie)
{
// Some other solution as applies to whatever IE compatible video player used.
}
else
{
$('video')[0].pause();
}
But, consider that $.browser is deprecated, but I haven't found a comparable solution.