Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes:
def plotHistogram(p, o):
"""
p and o are iterables with the values you want to
plot the histogram of
"""
plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
plt.show()
<input type="text" disabled="disabled" />
See the W3C HTML Specification on the input tag for more information.
One of the many ways it can be achieved is this:
$fileDownloadCount = (int) column_data_from_db;
$fileDownloadCount++;
The second line increments the value by 1.
A bit late of a answer, but here is a reusable solution:
/**
* An extension of TextWatcher which stops further callbacks being called as
* a result of a change happening within the callbacks themselves.
*/
public abstract class EditableTextWatcher implements TextWatcher {
private boolean editing;
@Override
public final void beforeTextChanged(CharSequence s, int start,
int count, int after) {
if (editing)
return;
editing = true;
try {
beforeTextChange(s, start, count, after);
} finally {
editing = false;
}
}
protected abstract void beforeTextChange(CharSequence s, int start,
int count, int after);
@Override
public final void onTextChanged(CharSequence s, int start,
int before, int count) {
if (editing)
return;
editing = true;
try {
onTextChange(s, start, before, count);
} finally {
editing = false;
}
}
protected abstract void onTextChange(CharSequence s, int start,
int before, int count);
@Override
public final void afterTextChanged(Editable s) {
if (editing)
return;
editing = true;
try {
afterTextChange(s);
} finally {
editing = false;
}
}
public boolean isEditing() {
return editing;
}
protected abstract void afterTextChange(Editable s);
}
So when the above is used, any setText()
calls happening within the TextWatcher will not result in the TextWatcher being called again:
/**
* A setText() call in any of the callbacks below will not result in TextWatcher being
* called again.
*/
public class MyTextWatcher extends EditableTextWatcher {
@Override
protected void beforeTextChange(CharSequence s, int start, int count, int after) {
}
@Override
protected void onTextChange(CharSequence s, int start, int before, int count) {
}
@Override
protected void afterTextChange(Editable s) {
}
}
You can use formControlName
only on directives which implement ControlValueAccessor
.
So, in order to do what you want, you have to create a component which implements ControlValueAccessor
, which means implementing the following three functions:
writeValue
(tells Angular how to write value from model into view)registerOnChange
(registers a handler function that is called when the view changes)registerOnTouched
(registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).Then, you have to tell Angular that this directive is a ControlValueAccessor
(interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by registering a provider.
The provider should provide NG_VALUE_ACCESSOR
and use an existing value. You'll also need a forwardRef
here. Note that NG_VALUE_ACCESSOR
should be a multi provider.
For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to @Component
decorator:
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyControlComponent),
}
]
Your component is ready to be used. With template-driven forms, ngModel
binding will now work properly.
With reactive forms, you can now properly use formControlName
and the form control will behave as expected.
Assuming you are using this for a web service, you can just apply the following attribute to the class:
[System.Web.Script.Services.ScriptService]
Then the following attribute to each method that should return Json:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And set the return type for the methods to be "object"
This may be platform specific, I somehow doubt it, but anyway, the best explanation I've seen is here on this msdn page where they explain about shutdown, linger options, socket closure and general connection termination sequences.
In summary, use shutdown to send a shutdown sequence at the TCP level and use close to free up the resources used by the socket data structures in your process. If you haven't issued an explicit shutdown sequence by the time you call close then one is initiated for you.
If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:
Try this:
Swift 2.0:
textField.userInteractionEnabled = false
Swift 3.0:
textField.isUserInteractionEnabled = false
Or in storyboard uncheck "User Interaction Enabled"
Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.
Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after
method and binding a change method allows you to change color and do other operations.
Label.destroy
is another example of the after method.
def export_win():
//Some Operation
orig_color = export_finding_graph.cget("background")
export_finding_graph.configure(background = "green")
tt = "Exported"
label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)
def change(orig_color):
export_finding_graph.configure(background = orig_color)
tab1_closed_observations.after(1000, lambda: change(orig_color))
tab1_closed_observations.after(500, label.destroy)
export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)
You can also revert to the original color.
Also check whether you have any falsy value or not. Angularjs will insert an empty option if you do have falsy value. I struggled for 2 days just due to falsy value. I hope it will be helpful for someone.
I had options as [0, 1] and initially I was set the model to 0 due to that it was inserted empty option. Workaround for this was ["0" , "1"].
A lot of big examples, let me explain in clear and crispy way.
ViewModel = Model that is created to serve the view.
ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.
View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.
Few examples of View Models are below
ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.
The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.
Here is a small example of List data using ViewModel.
Hope this will be useful.
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
Delete the .sdf file that is in your solution directory. It's just the Intellisense database, and Visual Studio will recreate it the next time you open that solution. This db can get corrupted and cause the IDE to not be able to find things, and since the compiler generates this information for itself on the fly, it wouldn't be affected.
firstly you have to change the drive, which is allocated to your usb.
follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.
A more elegant solution could be:
def progressBar(current, total, barLength = 20):
percent = float(current) * 100 / total
arrow = '-' * int(percent/100 * barLength - 1) + '>'
spaces = ' ' * (barLength - len(arrow))
print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
call this function with value
and endvalue
, result should be
Progress: [-------------> ] 69 %
Note: Python 2.x version here.
Must be a reference bug from Microsoft.
I cleaned, rebuild on all my libraries and still got the same problem and couldnt resolve this.
All i did was close the Visual Studio Application and opened it again. That did the trick.
Its very frustrating that such a simple issue can take that long to fix because you wouldnt think that it will be something like that.
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
MainActivity.java
package com.zeustechnocrats.countdown;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private String EVENT_DATE_TIME = "2020-12-31 10:30:00";
private String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private LinearLayout linear_layout_1, linear_layout_2;
private TextView tv_days, tv_hour, tv_minute, tv_second;
private Handler handler = new Handler();
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.count_down);
initUI();
countDownStart();
}
private void initUI() {
linear_layout_1 = findViewById(R.id.linear_layout_1);
linear_layout_2 = findViewById(R.id.linear_layout_2);
tv_days = findViewById(R.id.tv_days);
tv_hour = findViewById(R.id.tv_hour);
tv_minute = findViewById(R.id.tv_minute);
tv_second = findViewById(R.id.tv_second);
}
private void countDownStart() {
runnable = new Runnable() {
@Override
public void run() {
try {
handler.postDelayed(this, 1000);
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date event_date = dateFormat.parse(EVENT_DATE_TIME);
Date current_date = new Date();
if (!current_date.after(event_date)) {
long diff = event_date.getTime() - current_date.getTime();
long Days = diff / (24 * 60 * 60 * 1000);
long Hours = diff / (60 * 60 * 1000) % 24;
long Minutes = diff / (60 * 1000) % 60;
long Seconds = diff / 1000 % 60;
//
tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
} else {
linear_layout_1.setVisibility(View.VISIBLE);
linear_layout_2.setVisibility(View.GONE);
handler.removeCallbacks(runnable);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
protected void onStop() {
super.onStop();
handler.removeCallbacks(runnable);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:gravity="center_horizontal"
android:visibility="gone">
<TextView
android:id="@+id/tv_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Android Event Start"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:id="@+id/linear_layout_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tv_days"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_days_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Days"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tv_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_hour_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hour"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tv_minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_minute_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Minute"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tv_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_second_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Second"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
You have here available an example of DNS Caching in Debian using dnsmasq.
Configuration summary:
# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"
# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888
nameserver 127.0.0.1
Then just restart dnsmasq.
Benchmark test using DNS 1.1.1.1:
for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Benchmark test using you local cached DNS:
for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Just ran into this problem myself. OSx Lion hides scrollbars while not in use to make it seem more "slick", but at the same time the issue you addressed comes up: people sometimes cannot see whether a div has a scroll feature or not.
The fix: In your css include -
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0, 0, 0, .5);
box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}
/* always show scrollbars */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
-webkit-appearance: none;_x000D_
width: 7px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
border-radius: 4px;_x000D_
background-color: rgba(0, 0, 0, .5);_x000D_
box-shadow: 0 0 1px rgba(255, 255, 255, .5);_x000D_
}_x000D_
_x000D_
_x000D_
/* css for demo */_x000D_
_x000D_
#container {_x000D_
height: 4em;_x000D_
/* shorter than the child */_x000D_
overflow-y: scroll;_x000D_
/* clip height to 4em and scroll to show the rest */_x000D_
}_x000D_
_x000D_
#child {_x000D_
height: 12em;_x000D_
/* taller than the parent to force scrolling */_x000D_
}_x000D_
_x000D_
_x000D_
/* === ignore stuff below, it's just to help with the visual. === */_x000D_
_x000D_
#container {_x000D_
background-color: #ffc;_x000D_
}_x000D_
_x000D_
#child {_x000D_
margin: 30px;_x000D_
background-color: #eee;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="child">Example</div>_x000D_
</div>
_x000D_
customize the apperance as needed. Source
I've been bothered by this issue for a long time. For me, the version of node
was the problem.
My npm
and node
were 6.1.0 and 8.11.3, respectively. However, I didn't realize that I had updated my node
accidentally to 12.*.*.
It then began to install GCX stuff whenever npm i
, which was unnecessary before.
I downgraded my node
to 8 and it worked!
This was tagged as a bootstrap 3, but maybe this will be helpful: In Bootstrap 4.0.0 (non beta) : Inside the col class, use
<div class="col text-center text-md-left">
"text-center" centers the text for all window sizes, then adding the "text-md-left" or "text-md-right" to change it above sm. You could make it "text-sm-left", "text-lg-left" or whatever. But having it set to center always first sets up it up.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<body>
<footer>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 text-center text-md-left">
<p>
© 2015 example.com. All rights reserved.
</p>
</div>
<div class="col-xs-12 col-sm-6 text-center text-md-right">
<p>
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-google-plus"></i></a>
</p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
With JDBC 4.2 or later and java 8 or later:
myPreparedStatement.setObject( … , myLocalDate )
…and…
myResultSet.getObject( … , LocalDate.class )
The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
In java.time, the java.time.LocalDate
class represents a date-only value without time-of-day and without time zone.
If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date
class. You can pass/fetch LocalDate
objects directly to/from your database via PreparedStatement::setObject
and ResultSet::getObject
.
LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate );
…and…
LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );
If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.
New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date
see the valueOf
and toLocalDate
methods.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
…and…
LocalDate localDate = sqlDate.toLocalDate();
Be wary of using 0000-00-00
as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01
.
LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
dd()
dumps the variable and ends the execution of the script (1), so surrounding it with <pre>
tags will leave it broken. Just use good ol' var_dump()
(or print_r()
if you know it's an array)
Route::get('/', function()
{
echo '<pre>';
var_dump(User::all());
echo '</pre>';
//exit; <--if you want
});
Update:
I think you could format down what's shown by having Laravel convert the model object to array:
Route::get('/', function()
{
echo '<pre>';
$user = User::where('person_id', '=', 1);
var_dump($user->toArray()); // <---- or toJson()
echo '</pre>';
//exit; <--if you want
});
(1) For the record, this is the implementation of dd():
function dd()
{
array_map(function($x) { var_dump($x); }, func_get_args()); die;
}
It looks like you are calling a non static member (a property or method, specifically setTextboxText
) from a static method (specifically SumData
). You will need to either:
Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
Create an instance of Form1
within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1
would be an option also.
Make the calling method a non-static instance method (of Form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
More info about this error can be found on MSDN.
If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt"
, the watch command should be:
watch -n 5 'ls -l | grep "txt"'
If you are running on Redhat, do following
Stop Jenkins
$sudo service jenkins stop
change port number in /etc/sysconfig/jenkins
like i did for port 8081
JENKINS_PORT="8081"
start Jenkins again
$sudo service jenkins start
These commands worked for Artik 10 :
and these others didn't :
In case your assemblies will be ngen-ed, you might want to take a look at TargetedPatchingOptOut. This will help ngen decide whether to inline methods. MSDN reference
It is still only a declarative hint to optimize though, not an imperative command.
reference here
!== is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:
a !== b
a !== "2"
4 !== '4'
We never store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string:
public enum Suit { Spade, Heart, Diamond, Club }
Suit theSuit = Suit.Heart;
szQuery = "INSERT INTO Customers (Name, Suit) " +
"VALUES ('Ian Boyd', %s)".format(theSuit.name());
and then read back with:
Suit theSuit = Suit.valueOf(reader["Suit"]);
The problem was in the past staring at Enterprise Manager and trying to decipher:
Name Suit
================== ==========
Shelby Jackson 2
Ian Boyd 1
verses
Name Suit
================== ==========
Shelby Jackson Diamond
Ian Boyd Heart
the latter is much easier. The former required getting at the source code and finding the numerical values that were assigned to the enumeration members.
Yes it takes more space, but the enumeration member names are short, and hard drives are cheap, and it is much more worth it to help when you're having a problem.
Additionally, if you use numerical values, you are tied to them. You cannot nicely insert or rearrange the members without having to force the old numerical values. For example, changing the Suit enumeration to:
public enum Suit { Unknown, Heart, Club, Diamond, Spade }
would have to become :
public enum Suit {
Unknown = 4,
Heart = 1,
Club = 3,
Diamond = 2,
Spade = 0 }
in order to maintain the legacy numerical values stored in the database.
The question comes up: lets say i wanted to order the values. Some people may want to sort them by the enum's ordinal value. Of course, ordering the cards by the numerical value of the enumeration is meaningless:
SELECT Suit FROM Cards
ORDER BY SuitID; --where SuitID is integer value(4,1,3,2,0)
Suit
------
Spade
Heart
Diamond
Club
Unknown
That's not the order we want - we want them in enumeration order:
SELECT Suit FROM Cards
ORDER BY CASE SuitID OF
WHEN 4 THEN 0 --Unknown first
WHEN 1 THEN 1 --Heart
WHEN 3 THEN 2 --Club
WHEN 2 THEN 3 --Diamond
WHEN 0 THEN 4 --Spade
ELSE 999 END
The same work that is required if you save integer values is required if you save strings:
SELECT Suit FROM Cards
ORDER BY Suit; --where Suit is an enum name
Suit
-------
Club
Diamond
Heart
Spade
Unknown
But that's not the order we want - we want them in enumeration order:
SELECT Suit FROM Cards
ORDER BY CASE Suit OF
WHEN 'Unknown' THEN 0
WHEN 'Heart' THEN 1
WHEN 'Club' THEN 2
WHEN 'Diamond' THEN 3
WHEN 'Space' THEN 4
ELSE 999 END
My opinion is that this kind of ranking belongs in the user interface. If you are sorting items based on their enumeration value: you're doing something wrong.
But if you wanted to really do that, i would create a Suits
dimension table:
| Suit | SuitID | Rank | Color |
|------------|--------------|---------------|--------|
| Unknown | 4 | 0 | NULL |
| Heart | 1 | 1 | Red |
| Club | 3 | 2 | Black |
| Diamond | 2 | 3 | Red |
| Spade | 0 | 4 | Black |
This way, when you want to change your cards to use Kissing Kings New Deck Order you can change it for display purposes without throwing away all your data:
| Suit | SuitID | Rank | Color | CardOrder |
|------------|--------------|---------------|--------|-----------|
| Unknown | 4 | 0 | NULL | NULL |
| Spade | 0 | 1 | Black | 1 |
| Diamond | 2 | 2 | Red | 1 |
| Club | 3 | 3 | Black | -1 |
| Heart | 1 | 4 | Red | -1 |
Now we are separating an internal programming detail (enumeration name, enumeration value) with a display setting meant for users:
SELECT Cards.Suit
FROM Cards
INNER JOIN Suits ON Cards.Suit = Suits.Suit
ORDER BY Suits.Rank,
Card.Rank*Suits.CardOrder
I use ActiveRecord Migrations. This Ruby gem can be used outside of a Rails project and there are adapters to handle most databases you'll come across. My tip: if you are able to run your project off Postgres, you get transactional schema migrations. That means you don't end up with a broken database if a migration only half-applies.
After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>var $j = jQuery.noConflict(true);</script>
<script>
$(document).ready(function(){
console.log($().jquery); // This prints v1.4.2
console.log($j().jquery); // This prints v1.9.1
});
</script>
So then adding the "j" after the "$" was all I needed to do.
$j(function () {
$j('.button-pro').on('click', function () {
var el = $('#cnt' + this.id.replace('btn', ''));
$j('#contentnew > div').not(el).animate({
height: "toggle",
opacity: "toggle"
}, 100).hide();
el.toggle();
});
});
Just to share my idea...
I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.
public partial class ucLabel : Label
{
private ToolTip _tt = new ToolTip();
public string TooltipText { get; set; }
public ucLabel() : base() {
_tt.AutoPopDelay = 1500;
_tt.InitialDelay = 400;
// _tt.IsBalloon = true;
_tt.UseAnimation = true;
_tt.UseFading = true;
_tt.Active = true;
this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
}
private void ucLabel_MouseEnter(object sender, EventArgs ea)
{
if (!string.IsNullOrEmpty(this.TooltipText))
{
_tt.SetToolTip(this, this.TooltipText);
_tt.Show(this.TooltipText, this.Parent);
}
}
}
In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:
this.lblMyLabel = new ucLabel();
Also, change the private variable reference in the Designer code:
private ucLabel lblMyLabel;
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
You can just put it in on the file system. Eclipse will pick up the change on the next refresh. Click the folder and press F5 to refresh. BTW, make sure the file name does not have any capital letters... it will break android... and eclipse will let you know.
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click()
function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!
There are actually several ways to import an excel file in to a MySQL database with varying degrees of complexity and success.
Excel2MySQL. Hands down, the easiest and fastest way to import Excel data into MySQL. It supports all verions of Excel and doesn't require Office install.
LOAD DATA INFILE: This popular option is perhaps the most technical and requires some understanding of MySQL command execution. You must manually create your table before loading and use appropriately sized VARCHAR field types. Therefore, your field data types are not optimized. LOAD DATA INFILE has trouble importing large files that exceed 'max_allowed_packet' size. Special attention is required to avoid problems importing special characters and foreign unicode characters. Here is a recent example I used to import a csv file named test.csv.
phpMyAdmin: Select your database first, then select the Import tab. phpMyAdmin will automatically create your table and size your VARCHAR fields, but it won't optimize the field types. phpMyAdmin has trouble importing large files that exceed 'max_allowed_packet' size.
MySQL for Excel: This is a free Excel Add-in from Oracle. This option is a bit tedious because it uses a wizard and the import is slow and buggy with large files, but this may be a good option for small files with VARCHAR data. Fields are not optimized.
A very simple Java 8 solution:
File[] directories = new File("/your/path/").listFiles(File::isDirectory);
It's equivalent to using a FileFilter (works with older Java as well):
File[] directories = new File("/your/path/").listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
});
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
I used pyplot
's axes
object to manually adjust the sizes without using GridSpec
:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02
rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]
fig = plt.figure()
cones = plt.axes(rect_cones)
box = plt.axes(rect_box)
cones.plot(x, y)
box.plot(y, x)
plt.show()
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.
I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()
-method which was working with an ZoomButtonsController
-object to enable and disable the zoom controls depending on the current scale of the browser.
I searched for a method to return the ZoomButtonsController
-instance and found the getZoomButtonsController()
-method, that returned this very instance.
Although the method is declared public
, it is not documented in the WebView
-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView
-subclass to override the onTouchEvent()
-method, which triggered the controls.
public class NoZoomControllWebView extends WebView {
private ZoomButtonsController zoom_controll = null;
public NoZoomControllWebView(Context context) {
super(context);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs) {
super(context, attrs);
disableControls();
}
/**
* Disable the controls
*/
private void disableControls(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
} else {
// Use the reflection magic to make it work on earlier APIs
getControlls();
}
}
/**
* This is where the magic happens :D
*/
private void getControlls() {
try {
Class webview = Class.forName("android.webkit.WebView");
Method method = webview.getMethod("getZoomButtonsController");
zoom_controll = (ZoomButtonsController) method.invoke(this, null);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
return true;
}
}
You might want to remove the unnecessary constructors and react on probably on the exceptions.
Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).
As @jayellos pointed out in the comments, the private getZoomButtonsController()
-method is no longer existing on Android 4.0.4 and later.
However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.
I updated the example code above to do exactly that.
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
Another thing to check, which happened to be my solution (found here), is how data is being returned from your server. In my application, I'm using PDO to connect from PHP to MySQL. I needed to add a flag to the connection which said get the data back in UTF-8 format
The answer was
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
ret,frame = cap.read()
if ret == True:
print(frame.shape)
out.write(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()`enter code here`
cv2.destroyAllWindows()
This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour
I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
SYSDATETIME() 2007-04-30 13:10:02.0474381
SYSDATETIMEOFFSET()2007-04-30 13:10:02.0474381 -07:00
SYSUTCDATETIME() 2007-04-30 20:10:02.0474381
CURRENT_TIMESTAMP 2007-04-30 13:10:02.047 +
GETDATE() 2007-04-30 13:10:02.047
GETUTCDATE() 2007-04-30 20:10:02.047
I guess NOW() doesn't work sometime and gives error 'NOW' is not a recognized built-in function name.
Hope it helps!!! Thank You. https://docs.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
As of InteliJ IDEA 2017.2.5
, you can change the editor font size by going to:
Settings ? Editor ? Font
if u have optgroup inside select, u got error in DOM.
I think a best way:
$("#select option:last").after($('<option value="1">my option</option>'));
Many answers are not correct, but get many counts. Here I just write a solution programmatically, the three views are horizontal align, without using spacer views, but it only work when the widths of labels are known when used in storyboard.
NSDictionary *views = NSDictionaryOfVariableBindings(_redView, _yellowView, _blueView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|->=0-[_redView(40)]->=0-[_yellowView(40)]->=0-[_blueView(40)]->=0-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_redView(60)]" options:0 metrics:nil views:views]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_redView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeLeading multiplier:0.5 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_blueView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeLeading multiplier:1.5 constant:40]];
There's a whole API for managing portfolios. *Link removed. Google no longer provides a developer API for this.
Getting stock quotes is a little harder. I found one article where someone got stock quotes using Google Spreadsheets.
You can also use the gadgets but I guess that's not what you're after.
The API you mention is interesting but doesn't seem to be documented (as far as I've been able to find anyway).
Here is some information on historical prices, just for reference sake.
If you'r using LINUX, first let's check apache's user, since in some distros it can be different:
egrep -i '^user|^group' /etc/httpd/conf/httpd.conf
Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:
chown -R http:http path_to_folder
chmod -R g+rw path_to_folder
You can also use bitwise operators to truncate the decimal.
e.g.
var x = 9 / 2;
console.log(x); // 4.5
x = ~~x;
console.log(x); // 4
x = -3.7
console.log(~~x) // -3
console.log(x | 0) // -3
console.log(x << 0) // -3
Bitwise operations are considerably more efficient than the Math functions. The double not bitwise operator also seems to slightly outperform the x | 0
and x << 0
bitwise operations by a negligible amount.
// 952 milliseconds
for (var i = 0; i < 1000000; i++) {
(i * 0.5) | 0;
}
// 1150 milliseconds
for (var i = 0; i < 1000000; i++) {
(i * 0.5) << 0;
}
// 1284 milliseconds
for (var i = 0; i < 1000000; i++) {
Math.trunc(i * 0.5);
}
// 939 milliseconds
for (var i = 0; i < 1000000; i++) {
~~(i * 0.5);
}
Also worth noting is that the bitwise not operator takes precedence over arithmetic operations, so you may need to surround calculations with parentheses to have the intended result:
x = -3.7
console.log(~~x * 2) // -6
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7
console.log(~~(x * 2)) // -7
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7
More info about the double bitwise not operator can be found at Double bitwise NOT (~~)
What about using rawurlencode() ? http://www.php.net/manual/en/function.rawurlencode.php
Here is a function that sanitize even Chinese Chars:
public static function normalizeString ($str = '')
{
$str = strip_tags($str);
$str = preg_replace('/[\r\n\t ]+/', ' ', $str);
$str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
$str = strtolower($str);
$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
$str = htmlentities($str, ENT_QUOTES, "utf-8");
$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
$str = str_replace(' ', '-', $str);
$str = rawurlencode($str);
$str = str_replace('%', '-', $str);
return $str;
}
Here is the explaination
OK, some filename will not be releavant but in most case it will work.
ex. Original Name: "???????-??-????????????.jpg"
Output Name: "-E1-83-A1-E1-83-90-E1-83-91-E1-83-94-E1-83-AD-E1-83-93-E1-83-98--E1-83-93-E1-83-90--E1-83-A2-E1-83-98-E1-83-9E-E1-83-9D-E1-83-92-E1-83-A0-E1-83-90-E1-83-A4-E1-83-98-E1-83-A3-E1-83-9A-E1-83-98.jpg"
It's better like that than an 404 error.
Hope that was helpful.
Carl.
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
I've written an extension class to help me deserializing from JSON sources (string, stream, file).
public static class JsonHelpers
{
public static T CreateFromJsonStream<T>(this Stream stream)
{
JsonSerializer serializer = new JsonSerializer();
T data;
using (StreamReader streamReader = new StreamReader(stream))
{
data = (T)serializer.Deserialize(streamReader, typeof(T));
}
return data;
}
public static T CreateFromJsonString<T>(this String json)
{
T data;
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(json)))
{
data = CreateFromJsonStream<T>(stream);
}
return data;
}
public static T CreateFromJsonFile<T>(this String fileName)
{
T data;
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
data = CreateFromJsonStream<T>(fileStream);
}
return data;
}
}
Deserializing is now as easy as writing:
MyType obj1 = aStream.CreateFromJsonStream<MyType>();
MyType obj2 = "{\"key\":\"value\"}".CreateFromJsonString<MyType>();
MyType obj3 = "data.json".CreateFromJsonFile<MyType>();
Hope it will help someone else.
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
Be aware that the Path
is case sensitive. I tried setx PATH
and it didn't work. In my case it was setx Path
. Make sure your CMD run as Administrator.
setx Path "%PATH%;C:\Program Files\nodejs"
Now just restart your command prompt (or restart the PC) and the node
command should be available.
The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.
SET out_number=SQRT(input_number);
Instead of this write:
select SQRT(input_number);
Please don't write SET out_number
and your input parameter should be:
PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT)
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* @param string $query The sql query with parameter placeholders
* @param array $params The array of substitution parameters
* @return string The interpolated query
*/
public static function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
select *
from invoice
where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));
Use string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ')
to split your code into an array with no periods, commas, question marks, or exclamation marks. You can add/remove as many replace calls as you want.
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
I've created a generic directive, able to receive any mask and also able to define the mask dynamically based on the value:
mask.directive.ts:
import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { NgControl } from '@angular/forms';
import { MaskGenerator } from '../interfaces/mask-generator.interface';
@Directive({
selector: '[spMask]'
})
export class MaskDirective {
private static readonly ALPHA = 'A';
private static readonly NUMERIC = '9';
private static readonly ALPHANUMERIC = '?';
private static readonly REGEX_MAP = new Map([
[MaskDirective.ALPHA, /\w/],
[MaskDirective.NUMERIC, /\d/],
[MaskDirective.ALPHANUMERIC, /\w|\d/],
]);
private value: string = null;
private displayValue: string = null;
@Input('spMask')
public maskGenerator: MaskGenerator;
@Input('spKeepMask')
public keepMask: boolean;
@Input('spMaskValue')
public set maskValue(value: string) {
if (value !== this.value) {
this.value = value;
this.defineValue();
}
};
@Output('spMaskValueChange')
public changeEmitter = new EventEmitter<string>();
@HostListener('input', ['$event'])
public onInput(event: { target: { value?: string }}): void {
let target = event.target;
let value = target.value;
this.onValueChange(value);
}
constructor(private ngControl: NgControl) { }
private updateValue(value: string) {
this.value = value;
this.changeEmitter.emit(value);
MaskDirective.delay().then(
() => this.ngControl.control.updateValueAndValidity()
);
}
private defineValue() {
let value: string = this.value;
let displayValue: string = null;
if (this.maskGenerator) {
let mask = this.maskGenerator.generateMask(value);
if (value != null) {
displayValue = MaskDirective.mask(value, mask);
value = MaskDirective.processValue(displayValue, mask, this.keepMask);
}
} else {
displayValue = this.value;
}
MaskDirective.delay().then(() => {
if (this.displayValue !== displayValue) {
this.displayValue = displayValue;
this.ngControl.control.setValue(displayValue);
return MaskDirective.delay();
}
}).then(() => {
if (value != this.value) {
return this.updateValue(value);
}
});
}
private onValueChange(newValue: string) {
if (newValue !== this.displayValue) {
let displayValue = newValue;
let value = newValue;
if ((newValue == null) || (newValue.trim() === '')) {
value = null;
} else if (this.maskGenerator) {
let mask = this.maskGenerator.generateMask(newValue);
displayValue = MaskDirective.mask(newValue, mask);
value = MaskDirective.processValue(displayValue, mask, this.keepMask);
}
this.displayValue = displayValue;
if (newValue !== displayValue) {
this.ngControl.control.setValue(displayValue);
}
if (value !== this.value) {
this.updateValue(value);
}
}
}
private static processValue(displayValue: string, mask: string, keepMask: boolean) {
let value = keepMask ? displayValue : MaskDirective.unmask(displayValue, mask);
return value
}
private static mask(value: string, mask: string): string {
value = value.toString();
let len = value.length;
let maskLen = mask.length;
let pos = 0;
let newValue = '';
for (let i = 0; i < Math.min(len, maskLen); i++) {
let maskChar = mask.charAt(i);
let newChar = value.charAt(pos);
let regex: RegExp = MaskDirective.REGEX_MAP.get(maskChar);
if (regex) {
pos++;
if (regex.test(newChar)) {
newValue += newChar;
} else {
i--;
len--;
}
} else {
if (maskChar === newChar) {
pos++;
} else {
len++;
}
newValue += maskChar;
}
}
return newValue;
}
private static unmask(maskedValue: string, mask: string): string {
let maskLen = (mask && mask.length) || 0;
return maskedValue.split('').filter(
(currChar, idx) => (idx < maskLen) && MaskDirective.REGEX_MAP.has(mask[idx])
).join('');
}
private static delay(ms: number = 0): Promise<void> {
return new Promise(resolve => setTimeout(() => resolve(), ms)).then(() => null);
}
}
(Remember to declare it in your NgModule)
The numeric character in the mask is 9
so your mask would be (999) 999-9999
. You can change the NUMERIC
static field if you want (if you change it to 0
, your mask should be (000) 000-0000
, for example).
The value is displayed with mask but stored in the component field without mask (this is the desirable behaviour in my case). You can make it be stored with mask using [spKeepMask]="true"
.
The directive receives an object that implements the MaskGenerator
interface.
mask-generator.interface.ts:
export interface MaskGenerator {
generateMask: (value: string) => string;
}
This way it's possible to define the mask dynamically based on the value (like credit cards).
I've created an utilitarian class to store the masks, but you can specify it directly in your component too.
my-mask.util.ts:
export class MyMaskUtil {
private static PHONE_SMALL = '(999) 999-9999';
private static PHONE_BIG = '(999) 9999-9999';
private static CPF = '999.999.999-99';
private static CNPJ = '99.999.999/9999-99';
public static PHONE_MASK_GENERATOR: MaskGenerator = {
generateMask: () => MyMaskUtil.PHONE_SMALL,
}
public static DYNAMIC_PHONE_MASK_GENERATOR: MaskGenerator = {
generateMask: (value: string) => {
return MyMaskUtil.hasMoreDigits(value, MyMaskUtil.PHONE_SMALL) ?
MyMaskUtil.PHONE_BIG :
MyMaskUtil.PHONE_SMALL;
},
}
public static CPF_MASK_GENERATOR: MaskGenerator = {
generateMask: () => MyMaskUtil.CPF,
}
public static CNPJ_MASK_GENERATOR: MaskGenerator = {
generateMask: () => MyMaskUtil.CNPJ,
}
public static PERSON_MASK_GENERATOR: MaskGenerator = {
generateMask: (value: string) => {
return MyMaskUtil.hasMoreDigits(value, MyMaskUtil.CPF) ?
MyMaskUtil.CNPJ :
MyMaskUtil.CPF;
},
}
private static hasMoreDigits(v01: string, v02: string): boolean {
let d01 = this.onlyDigits(v01);
let d02 = this.onlyDigits(v02);
let len01 = (d01 && d01.length) || 0;
let len02 = (d02 && d02.length) || 0;
let moreDigits = (len01 > len02);
return moreDigits;
}
private static onlyDigits(value: string): string {
let onlyDigits = (value != null) ? value.replace(/\D/g, '') : null;
return onlyDigits;
}
}
Then you can use it in your component (use spMaskValue
instead of ngModel
, but if is not a reactive form, use ngModel
with nothing, like in the example below, just so that you won't receive an error of no provider because of the injected NgControl
in the directive; in reactive forms you don't need to include ngModel
):
my.component.ts:
@Component({ ... })
export class MyComponent {
public phoneValue01: string = '1231234567';
public phoneValue02: string;
public phoneMask01 = MyMaskUtil.PHONE_MASK_GENERATOR;
public phoneMask02 = MyMaskUtil.DYNAMIC_PHONE_MASK_GENERATOR;
}
my.component.html:
<span>Phone 01 ({{ phoneValue01 }}):</span><br>
<input type="text" [(spMaskValue)]="phoneValue01" [spMask]="phoneMask01" ngModel>
<br><br>
<span>Phone 02 ({{ phoneValue02 }}):</span><br>
<input type="text" [(spMaskValue)]="phoneValue02" [spMask]="phoneMask02" [spKeepMask]="true" ngModel>
(Take a look at phone02
and see that when you type 1 more digit, the mask changes; also, look that the value stored of phone01
is without mask)
I've tested it with normal inputs as well as with ionic
inputs (ion-input
), with both reactive (with formControlName
, not with formControl
) and non-reactive forms.
For the following HTML document:
<html>
<body>
<a href="http://www.example.com">Example</a>
<a href="http://www.stackoverflow.com">SO</a>
</body>
</html>
The xpath query /html/body//a/@href
(or simply //a/@href
) will return:
http://www.example.com http://www.stackoverflow.com
To select a specific instance use /html/body//a[N]/@href
,
$ /html/body//a[2]/@href http://www.stackoverflow.com
To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:
$ /html/body//a[contains(@href,'example')]/@href http://www.example.com
Mixing the two:
$ /html/body//a[contains(@href,'com')][2]/@href http://www.stackoverflow.com
Yes, wireshark will work.
I don't think there is any easy way to filter out solely emulator traffic, since it is coming from the same src IP.
Perhaps the best way would be to set up a very bare VMware environment and only run the emulator in there, at least that way there wouldn't be too much background traffic.
Please note that inserted, deleted
means the same thing as inserted CROSS JOIN deleted
and gives every combination of every row. I doubt this is what you want.
Something like this may help get you started...
SELECT
CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
WHEN deleted.primaryKey IS NULL THEN 'This is an insert'
ELSE 'This is an update'
END as Action,
*
FROM
inserted
FULL OUTER JOIN
deleted
ON inserted.primaryKey = deleted.primaryKey
Depending on what you want to do, you then reference the table you are interested in with inserted.userID
or deleted.userID
, etc.
Finally, be aware that inserted
and deleted
are tables and can (and do) contain more than one record.
If you insert 10 records at once, the inserted
table will contain ALL 10 records. The same applies to deletes and the deleted
table. And both tables in the case of an update.
EDIT Examplee Trigger after OPs edit.
ALTER TRIGGER [dbo].[UpdateUserCreditsLeft]
ON [dbo].[Order]
AFTER INSERT,UPDATE,DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE
User
SET
CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a DELETE>
WHEN deleted.UserID IS NULL THEN <new value for an INSERT>
ELSE <new value for an UPDATE>
END
FROM
User
INNER JOIN
(
inserted
FULL OUTER JOIN
deleted
ON inserted.UserID = deleted.UserID -- This assumes UserID is the PK on UpdateUserCreditsLeft
)
ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)
END
If the PrimaryKey of UpdateUserCreditsLeft
is something other than UserID, use that in the FULL OUTER JOIN instead.
An important note: JavaScript Arrays are not associative arrays like those you might be used to from PHP. If your "array key" is a string, you're no longer operating on the contents of an array. Your array is an object, and you're using bracket notation to access the member named <key name>. Thus:
var myArray = []; myArray["bar"] = true; myArray["foo"] = true; alert(myArray.length); // returns 0.
because you have not added elements to the array, you have only modified myArray's bar and foo members.
If you want to remove multiple object from a list. There are various ways to delete an object from a list
Try this code. a is list with all object, b is list object you want to remove.
example :
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
the output is [1,4,5,6]
I hope, it will work for you
To remove rows based on Nan value of particular column:
d= pd.DataFrame([[2,3],[4,None]]) #creating data frame
d
Output:
0 1
0 2 3.0
1 4 NaN
d = d[np.isfinite(d[1])] #Select rows where value of 1st column is not nan
d
Output:
0 1
0 2 3.0
As already recommended, you can use tree
. But for using it together with restructured text some additional parameters were required.
The standard tree
output will not be printed if your're using pandoc
to produce pdf.
tree --dirsfirst --charset=ascii /path/to/directory
will produce a nice ASCII
tree that can be integrated into your document like this:
.. code::
.
|-- ContentStore
| |-- de-DE
| | |-- art.mshc
| | |-- artnoloc.mshc
| | |-- clientserver.mshc
| | |-- noarm.mshc
| | |-- resources.mshc
| | `-- windowsclient.mshc
| `-- en-US
| |-- art.mshc
| |-- artnoloc.mshc
| |-- clientserver.mshc
| |-- noarm.mshc
| |-- resources.mshc
| `-- windowsclient.mshc
`-- IndexStore
|-- de-DE
| |-- art.mshi
| |-- artnoloc.mshi
| |-- clientserver.mshi
| |-- noarm.mshi
| |-- resources.mshi
| `-- windowsclient.mshi
`-- en-US
|-- art.mshi
|-- artnoloc.mshi
|-- clientserver.mshi
|-- noarm.mshi
|-- resources.mshi
`-- windowsclient.mshi
std::fill(v.begin(), v.end(), 0);
I may be missing part of the question, but I believe you can simply do this:
$('.testimonial').each((index, element) => {
if (/* Condition */) {
// Do Something
}
});
This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/
Try
SELECT LTRIM(RTRIM('Amit Tech Corp '))
LTRIM
- removes any leading spaces from left side of string
RTRIM
- removes any spaces from right
Ex:
update table set CompanyName = LTRIM(RTRIM(CompanyName))
A-M's is similar to what the BrowerActivity does. for FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams (768, 512);
I think we can use
FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.FILL_PARENT)
instead.
Another issue I met is if the video is playing, and user clicks the back button, next time, you go to this activity(singleTop one) and can not play the video. to fix this, I called the
try {
mCustomVideoView.stopPlayback();
mCustomViewCallback.onCustomViewHidden();
} catch(Throwable e) { //ignore }
in the activity's onBackPressed method.
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
Since Python 3.3, you can use the class ExitStack
from the contextlib
module to safely
open an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStack
operates:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
I Had the same issue on a service running on IIS 7 the service connects to multiple suppliers servers (some SSL some not) when adding a new one of these (this new supplier was TLS 1.2) I would get the error after a few requests were made to the original servers (SSL).
To confirm this I simply logged the System.Net.ServicePointManager.SecurityProtocol
before each request to each supplier.
Low and behold after restarting the service (or restarting the application pool) I would get the output Ssl3, Tls
but after a few requests to the original supplier servers this changed to Ssl3
and requests to the TLS service gave the error.
To fix I simply did what user369142 suggested. Before each request to the new server:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
and no more errors.
You can set its before
and after
to force a constant width-to-height ratio
HTML:
<div class="squared"></div>
CSS:
.squared {
background: #333;
width: 300px;
}
.squared::before {
content: '';
padding-top: 100%;
float: left;
}
.squared::after {
content: '';
display: block;
clear: both;
}
You can't use a condition to change the structure of your query, just the data involved. You could do this:
update table set
columnx = (case when condition then 25 else columnx end),
columny = (case when condition then columny else 25 end)
This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.
The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.
Did you install the drivers? See the Arduino installation instructions under #4. I don't know that machine but I doubt it doesn't have any COM ports.
Use the range's NumberFormat
property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
This should work. You may save the following in a batch file:
TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security
pause
Post increment(a++)
If int b = a++,then this means
int b = a;
a = a+1;
Here we add 1 to the value. The value is returned before the increment is made,
For eg a = 1; b = a++;
Then b=1 and a=2
Pre-increment (++a)
If int b = ++a; then this means
a=a+1;
int b=a ;
Pre-increment: This will add 1 to the main value. The value will be returned after the increment is made, For a = 1; b = ++a; Then b=2 and a=2.
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
since "$foobar"
would instead expand the variable identified by foobar
.
Curly braces are also unconditionally required when:
${array[42]}
${filename%.*}
(remove extension)"$8 $9 ${10} ${11}"
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
You are missing vendor folder, probably its new cloned repository or new project
the vendor folder is populated by composer binary which reads composer.json file or system requirements and installs packaged under vendor folder and create an autoload script that has all classed
composer update
Seems like the simplest solution would to use ES6's .map
or lodash's _.map
:
var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
// lodash
var newArr = _.map(arr, function(a) {
return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});
// ES6
var newArr = arr.map(function(a) {
return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});
This has the nice effect of avoiding mutating the original array.
Just an FYI adding to Chris. B (best answer):
d = defaultdict(int)
Works as well; the reason is that calling int()
returns 0
which is what defaultdict
does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.
SQL Server has its own built in system for security that covers logins and roles. This is separate and parallel to Windows users and groups. You can use just SQL security and then all administration will occur within SQL server and there's no connection between those logins and the Windows users. If you use mixed mode then Windows users are treated just like SQL logins.
There are a number of features of each approach -
1) If you want to use connection pooling you have to use SQL logins, or all share the same windows user - not a good idea.
2) If you want to track what a particular user is doing, then using the windows authentication makes sense.
3) Using the windows tools to administer users is much more powerful than SQL, but the link between the two is tenuous, for instance if you remove a windows user then the related data within SQL isn't updated.
Actually the orderBy
filter can take as a parameter not only a string but also a function. From the orderBy
documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
The other thing worth noting is that orderBy
is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy
should be enough for most uses cases).
You can also do the following
string filename = Path.ChangeExtension(Path.GetTempFileName(), ".csv");
and this also works as expected
string filename = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");
For those coming here from a later day and age and one a working solution:
(Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
this will give the total sum of bytes.
$bytes = (Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
$kb = $bytes / 1024
$mb = $bytes / 1024 / 1024
$gb = $bytes / 1024 / 1024 / 1024
I tested this up to windows server 2008 (winver 6.0) even there this command seems to work
The reason is that modprobe
looks into /lib/modules/$(uname -r)
for the modules and therefore won't work with local file path. That's one of differences between modprobe
and insmod
.
It seems your hesitation is in creating your own component and then dispatching in the render method? Well you can avoid both by just using the render
method of the <Route>
component. No need to create a <AuthenticatedRoute>
component unless you really want to. It can be as simple as below. Note the {...routeProps}
spread making sure you continue to send the properties of the <Route>
component down to the child component (<MyComponent>
in this case).
<Route path='/someprivatepath' render={routeProps => {
if (!this.props.isLoggedIn) {
this.props.redirectToLogin()
return null
}
return <MyComponent {...routeProps} anotherProp={somevalue} />
} />
See the React Router V4 render documentation
If you did want to create a dedicated component, then it looks like you are on the right track. Since React Router V4 is purely declarative routing (it says so right in the description) I do not think you will get away with putting your redirect code outside of the normal component lifecycle. Looking at the code for React Router itself, they perform the redirect in either componentWillMount
or componentDidMount
depending on whether or not it is server side rendering. Here is the code below, which is pretty simple and might help you feel more comfortable with where to put your redirect logic.
import React, { PropTypes } from 'react'
/**
* The public API for updating the location programatically
* with a component.
*/
class Redirect extends React.Component {
static propTypes = {
push: PropTypes.bool,
from: PropTypes.string,
to: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
])
}
static defaultProps = {
push: false
}
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired
}).isRequired,
staticContext: PropTypes.object
}).isRequired
}
isStatic() {
return this.context.router && this.context.router.staticContext
}
componentWillMount() {
if (this.isStatic())
this.perform()
}
componentDidMount() {
if (!this.isStatic())
this.perform()
}
perform() {
const { history } = this.context.router
const { push, to } = this.props
if (push) {
history.push(to)
} else {
history.replace(to)
}
}
render() {
return null
}
}
export default Redirect
Going into my manifest and adding android:launchMode="singleTop"
to the activity did the trick for me.
This specifically solved my issue because I didn't want Android to create a new instance of the previous activity after hitting the Up
button in the toolbar - I instead wanted to use the existing instance of the prior activity when I went up the navigation hierarchy.
Reference: android:launchMode
window load will wait for all resources to be loaded.
document ready waits for the document to be initialized.
unload well, waits till the document is being unloaded.
the order is: document ready, window load, ... ... ... ... window unload.
always use document ready unless you need to wait for your images to load.
shorthand for document ready:
$(function(){
// yay!
});
Drawing an image using a QLabel
seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView
widget. In Qt Creator, drag a Graphics View
widget onto your UI and name it something (it is named mainImage
in the code below). In mainwindow.h
, add something like the following as private
variables to your MainWindow
class:
QGraphicsScene *scene;
QPixmap image;
Then just edit mainwindow.cpp
and make the constructor something like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
image.load("myimage.png");
scene = new QGraphicsScene(this);
scene->addPixmap(image);
scene->setSceneRect(image.rect());
ui->mainImage->setScene(scene);
}
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
If you're using Spring Boot, the simplest way to disable the Spring Security default headers is to use security.headers.*
properties. In particular, if you want to disable the X-Frame-Options
default header, just add the following to your application.properties
:
security.headers.frame=false
There is also security.headers.cache
, security.headers.content-type
, security.headers.hsts
and security.headers.xss
properties that you can use. For more information, take a look at SecurityProperties
.
In your case, ('AND' and 'OR' and 'NOT')
evaluates to "NOT"
, which may or may not be in your list...
while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
print 'No Boolean Operator'
These things helped me
Hope this helps someone out there.
Support for peer to peer WiFi networking is available since API level 14.
=RIGHT(A1)
is quite sufficient (where the string is contained in A1).
Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:
SYNTAX
RIGHT( text, [number_of_characters] )
Parameters or Arguments
text
The string that you wish to extract from.
number_of_characters
Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.
Applies To
Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Since number_of_characters is optional and defaults to 1
it is not required in this case.
However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):
=RIGHT(TRIM(A1))
might be preferred.
I tried replacing value
with Value
and it worked out. It has set the value
in input
tag now.
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
Recently there was a similar question on hashcode.com, and I created a jQuery plugin to deal with it. It also supports the recognition of caps lock on numbers. (On the standard German keyboard layout caps lock has effect on numbers).
You can check the latest version here: jquery.capsChecker
git stash
+ rebase
automation
For when I need to modify an old commit a lot of times for Gerrit reviews, I've been doing:
git-amend-old() (
# Stash, apply to past commit, and rebase the current branch on to of the result.
current_branch="$(git rev-parse --abbrev-ref HEAD)"
apply_to="$1"
git stash
git checkout "$apply_to"
git stash apply
git add -u
git commit --amend --no-edit
new_sha="$(git log --format="%H" -n 1)"
git checkout "$current_branch"
git rebase --onto "$new_sha" "$apply_to"
)
Usage:
git add
if already in repogit-amend-old $old_sha
I like this over --autosquash
as it does not squash other unrelated fixups.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt()
or statement.setString()
depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ?
in place of named value - :userId
..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
For me, the case was that I was searching the main bundle for a nib which wasn't in the main bundle. My nib was in an imported module so I needed to retrieve the bundle for that module and use it to init the UINib
, rather than using Bundle.main
.
You can also use a circle as a marker icon, for example:
var oMarker = new google.maps.Marker({
position: latLng,
sName: "Marker Name",
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: "#F00",
fillOpacity: 0.4,
strokeWeight: 0.4
},
});
and then, if you want to change the marker dynamically (like on mouseover), you can, for example:
oMarker.setIcon({
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: "#00F",
fillOpacity: 0.8,
strokeWeight: 1
})
select name, value
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1
i know i am late but this is what i got after 1 hour of search
<?php
$file = 'file.pdf';
if (! file) {
die('file not found'); //Or do something
} else {
if(isset($_GET['file'])){
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file); }
}
?>
and for downloadable link i did this
<a href="index.php?file=file.pdf">Download PDF</a>
You could overlay one element above the blurred element like so
div {
position: absolute;
left:0;
top: 0;
}
p {
position: absolute;
left:0;
top: 0;
}
The problem with opacity
is that it will also affect the content, when often you do not want this to happen.
If you just want your element to be transparent, it's really as easy as :
background-color: transparent;
But if you want it to be in colors, you can use:
background-color: rgba(255, 0, 0, 0.4);
Or define a background image (1px
by 1px
) saved with the right alpha
.
(To do so, use Gimp
, Paint.Net
or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)
As said by René, the best thing to do would be to mix both, with the rgba
first and the 1px
by 1px
image as a fallback if the browser doesn't support alpha :
background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);
See also : http://www.w3schools.com/cssref/css_colors_legal.asp.
Demo : My JSFiddle
Just put your projects in the same folder and simply open that folder in vscode.
Now your projects will appear like:
GROUP OF PROJECTS
PROJECT 1
PROJECT 2
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
Thanks Jason Rogers's answer first.
In Android && cpp should be this:
const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
Can fix this errors:
1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'
3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'
4.add "env->DeleteLocalRef(nativeString);" at end.
This error comes for me in windows application while calling server dll from client. After system restart it works fine
You must use the equals operator not the assignment like
if(document.form1.radio1[0].checked == true) {
alert("You have selected Option 1");
}
Note too that Hyperlink
does not have to be used for navigation. You can connect it to a command.
For example:
<TextBlock>
<Hyperlink Command="{Binding ClearCommand}">Clear</Hyperlink>
</TextBlock>
Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.
It depends on how tall you want your logo to be.
The default <a>
height in the navbar is 20px, so if you specify height: 20px
on your logo, it will allign nicely.
However that's kind of small for a logo, so what I opted for was this:
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="#" title="Brand">
<img style="height: 30px; margin-top: -5px;"
src="/img/brand.png">
</a>
</div>
This makes the image 30px tall and vertically aligns the image by adding a negative margin to the top (5px is half of the difference between the padding on a and the size of the image).
Alternately you could change the padding on the <a>
element, eg:
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="#" title="Brand" style="padding-top: 10px; padding-bottom: 10px">
<img style="height: 30px;"
src="/img/transparent-white-logo.png">
</a>
</div>
If you deal with bandwidth problems, try to compress data at the client side first, then base64-it.
Nice example of such magic is at http://jszip.stuartk.co.uk/ and more discussion to this topic is at JavaScript implementation of Gzip
I liked the idea from @Peter Lawrey, And i extended it to further limits :
/**
* Normalize string array,
* Appends zeros if string from the array
* has length smaller than the maxLen.
**/
private String normalize(String[] split, int maxLen){
StringBuilder sb = new StringBuilder("");
for(String s : split) {
for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');
sb.append(s);
}
return sb.toString();
}
/**
* Removes trailing zeros of the form '.00.0...00'
* (and does not remove zeros from, say, '4.1.100')
**/
public String removeTrailingZeros(String s){
int i = s.length()-1;
int k = s.length()-1;
while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){
if(s.charAt(i) == '.') k = i-1;
i--;
}
return s.substring(0,k+1);
}
/**
* Compares two versions(works for alphabets too),
* Returns 1 if v1 > v2, returns 0 if v1 == v2,
* and returns -1 if v1 < v2.
**/
public int compareVersion(String v1, String v2) {
// Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1
// v1 = removeTrailingZeros(v1);
// v2 = removeTrailingZeros(v2);
String[] splitv1 = v1.split("\\.");
String[] splitv2 = v2.split("\\.");
int maxLen = 0;
for(String str : splitv1) maxLen = Math.max(maxLen, str.length());
for(String str : splitv2) maxLen = Math.max(maxLen, str.length());
int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));
return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);
}
Hope it helps someone. It passed all test cases in interviewbit and leetcode (need to uncomment two lines in compareVersion function).
Easily tested !
Using Android studio 1.5.1 i got the following warnings:
Call requires API level 16 (current min is 9): android.view.View#setBackground
and the complaints about deprecation
'setBackgroundDrawable(android.graphics.drawable.Drawable)' is deprecated
Using this format, i got rid of both:
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
//noinspection deprecation
layout.setBackgroundDrawable(drawable);
} else {
layout.setBackground(drawable);
}
Real life examples of both TCP and UDP tcp -> a phone call, sms or anything specific to destination UDP -> a FM radio channel (AM), Wi-Fi.
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document
for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
While this example displays the usage of event delegation to capture events for a specific node (h1
in this case), and issue a callback for such events.
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
Anaconda is a very large installation ~ 2 GB and is most useful for those users who are not familiar with installing modules or packages with other package managers.
Anaconda seems to be promoting itself as the official package manager of Jupyter. It's not. Anaconda bundles Jupyter, R, python, and many packages with its installation.
Anaconda is not necessary for installing Jupyter Lab or the R kernel. There is plenty of information available elsewhere for installing Jupyter Lab or Notebooks. There is also plenty of information elsewhere for installing R studio. The following shows how to install the R kernel directly from R Studio:
To install the R kernel, without Anaconda, start R Studio. In the R terminal window enter these three commands:
install.packages("devtools")
devtools::install_github("IRkernel/IRkernel")
IRkernel::installspec()
Done. Next time Jupyter is opened, the R kernel will be available.
Basically if your compiler can work out what you mean or what a value is "at compile time" it can hardcode this into the runtime code. Obviously if your runtime code has to do a calculation every time it will run slower, so if you can determine something at compile time it is much better.
Eg.
Constant folding:
If I write:
int i = 2;
i += MY_CONSTANT;
The compiler can perform this calulation at compile time because it knows what 2 is, and what MY_CONSTANT is. As such it saves itself from performing a calculation every single execution.
I would suggest everytime when using global check if the variable is already define by simply check
if (!global.logger){
global.logger = require('my_logger');
}
I've found it to have better performance
this code solved problem
defaultConfig {
multiDexEnabled true
}
For easiest way to implement google sign in visit: google sign in android
Also try
dexOptions {
javaMaxHeapSize "4g"
}
Also keep same version number for different services.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns, Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
Please consider replacring the accepted solution with the following:
parse_url() will always include any sub-domain(s), so this function doesn't parse domain names very well. Here are some examples:
$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'www.google.com'
echo parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.com
echo parse_url('https://subdomain.example.co.uk/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.co.uk
Instead, you may consider this pragmatic solution. It will cover many, but not all domain names -- for instance, lower-level domains such as 'sos.state.oh.us' are not covered.
function getDomain($url) {
$host = parse_url($url, PHP_URL_HOST);
if(filter_var($host,FILTER_VALIDATE_IP)) {
// IP address returned as domain
return $host; //* or replace with null if you don't want an IP back
}
$domain_array = explode(".", str_replace('www.', '', $host));
$count = count($domain_array);
if( $count>=3 && strlen($domain_array[$count-2])==2 ) {
// SLD (example.co.uk)
return implode('.', array_splice($domain_array, $count-3,3));
} else if( $count>=2 ) {
// TLD (example.com)
return implode('.', array_splice($domain_array, $count-2,2));
}
}
// Your domains
echo getDomain('http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
echo getDomain('http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
echo getDomain('http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'); // google.co.uk
// TLD
echo getDomain('https://shop.example.com'); // example.com
echo getDomain('https://foo.bar.example.com'); // example.com
echo getDomain('https://www.example.com'); // example.com
echo getDomain('https://example.com'); // example.com
// SLD
echo getDomain('https://more.news.bbc.co.uk'); // bbc.co.uk
echo getDomain('https://www.bbc.co.uk'); // bbc.co.uk
echo getDomain('https://bbc.co.uk'); // bbc.co.uk
// IP
echo getDomain('https://1.2.3.45'); // 1.2.3.45
Finally, Jeremy Kendall's PHP Domain Parser allows you to parse the domain name from a url. League URI Hostname Parser will also do the job.
I strongly recommend that you not define your own scheme. This goes against the web standards for URI schemes, which attempts to rigidly control those names for good reason -- to avoid name conflicts between different entities. Once you put a link to your scheme on a web site, you have put that little name into entire the entire Internet's namespace, and should be following those standards.
If you just want to be able to have a link to your own app, I recommend you follow the approach I described here:
easy
batch file:
FOR %%A IN (1 2 3) DO ECHO %%A
command line:
FOR %A IN (1 2 3) DO ECHO %A
output:
1
2
3
It seems i came late to the party, but you should better check this out too.
So in system.web
for caching up exceptions within the application such as return HttpNotFound()
<system.web>
<customErrors mode="RemoteOnly">
<error statusCode="404" redirect="/page-not-found" />
<error statusCode="500" redirect="/internal-server-error" />
</customErrors>
</system.web>
and in system.webServer
for catching up errors that were caught by IIS and did not made their way to the asp.net framework
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404"/>
<error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
<remove statusCode="500"/>
<error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
</system.webServer>
In the last one if you worry about the client response then change the responseMode="Redirect"
to responseMode="File"
and serve a static html file, since this one will display a friendly page with an 200 response code.
git add --all
or git add -A
or git add -A .
Stages All
git add .
Stages New & Modified But Without Deleted
git add -u
Stages Modified & Deleted But Without New
git commit -a
Means git add -u
And git commit -m "message"
After writing this command follow these steps:-
git add <list of files>
add specific file
git add *.txt
add all the txt files in current directory
git add docs/*/txt
add all txt files in docs directory
git add docs/
add all files in docs directory
git add "*.txt"
or git add '*.txt'
add all the files in the whole project
Just use
latch = new CountDownLatch(noThreads)
In each thread
latch.countDown();
and as barrier
latch.await();
Change the return type to Nullable<T>
, and call the method with the non nullable parameter
static void Main(string[] args)
{
int? i = GetValueOrNull<int>(null, string.Empty);
}
public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
return (T)columnValue;
return null;
}
After opening local bootstrap.min.css in visual studio code, it looked unindented. Tried the commad ALT+Shift+F but in vain.
Then installed
CSS Formatter extension.
Reloaded it and ALT+Shift+F indented my CSS file with charm.
Bingo !!!
Have been struggling with this till I found out the answer:
Use GSON library:
Gson gson = Gson();
String str_json = gson.tojson(jsonArray);`
Pass the json array. This will be auto stringfied. This option worked perfectly for me.
Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:
/**
* Once this is running open your browser and hit http://localhost
* You'll see that the request hits the proxy and you get the HTML back
*/
'use strict';
const net = require('net');
const http = require('http');
const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;
let proxy = net.createServer(socket => {
socket.on('data', message => {
console.log('---PROXY- got message', message.toString());
let serviceSocket = new net.Socket();
serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
console.log('---PROXY- Sending message to server');
serviceSocket.write(message);
});
serviceSocket.on('data', data => {
console.log('---PROXY- Receiving message from server', data.toString();
socket.write(data);
});
});
});
let httpServer = http.createServer((req, res) => {
switch (req.url) {
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body><p>Ciao!</p></body></html>');
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 Not Found');
}
});
proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);
https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
Yet another way
$("#wizard li").click(function ()
{
$($(this),'#wizard"').index();
});
Often you can use Apache commons BeanUtils or PropertyUtils which introspection (basically they cache the meta data about the classes so they don't always need to use reflection).
You can also install any of the Hardware IO Tools without installing XCode itself. Simply visit Apple's Download Center and search for "Hardware IO".
Potentially, inconsistency of the node JS versions is what causes the problem. As stated in the documentation. Be sure to use one of the lts release. E.g. specify this in your Dockerfile:
# Pull lts from docker registry
FROM node:8.12.0
# ...
<html>
<input type="text" placeholder ="username" id="userinput">
<br>
<input type="password" placeholder="password">
<br>
<button type="submit" onclick="myfunc()" id="demo">click me</button>
<script type="text/javascript">
function myfunc() {
var input = document.getElementById('userinput');
alert(input.value);
}
</script>
</html>
protected void switchTabsUsingPartOfUrl(String platform) {
String currentHandle = null;
try {
final Set<String> handles = driver.getWindowHandles();
if (handles.size() > 1) {
currentHandle = driver.getWindowHandle();
}
if (currentHandle != null) {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
break;
}
}
} else {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform)) {
break;
}
}
}
} catch (Exception e) {
System.out.println("Switching tabs failed");
}
}
Call this method and pass parameter a substring of url of the tab you want to switch to
(df.groupby(['col5', 'col2']).size()
.sort_values(ascending=False)
.reset_index(name='count')
.drop_duplicates(subset='col2'))
col5 col2 count
0 3 A 3
1 1 D 3
2 5 B 2
6 3 C 1
Explanation
The result of the groupby size
method is a Series with col5
and col2
in the index. From here, you can use another groupby method to find the maximum value of each value in col2
but it is not necessary to do. You can simply sort all the values descendingly and then keep only the rows with the first occurrence of col2
with the drop_duplicates
method.
In your html file:
<a href="contact.html" class="button large hpbottom">Get Started</a>
In your css file:
.hpbottom{
text-align: center;
}
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
Anything you can do in regular old ANSI C can be done in Objective-C.
To create a vertical line centered inside a div I think you can use this code. The 'container' may well be 100% width, I guess.
div.container {_x000D_
width: 400px;_x000D_
}_x000D_
_x000D_
div.vertical-line {_x000D_
border-left: 1px solid #808080;_x000D_
height: 350px;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
width: 1px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="vertical-line"> </div>_x000D_
</div>
_x000D_
That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r
and, using c/c++ to parse text is not a good idea. try awk:
$awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
ID=0 Name=Filipe Age=19 Gender=M
ID=1 Name=Maria Age=20 Gender=F
ID=2 Name=Walter Age=60 Gender=M
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Faced same issue, Try using JPG format !!
I use Charles Web Debugging Proxy it costs but they have a trial version.
It is very simple to set up if your iPhone/iPad share the same Wifi network as your Mac.
If your Mac and iOS device are not on the same Wifi network you can set up your Mac as a Wifi router using the "Internet Sharing" option under Sharing in the System Preferences. You then connect your device to that "Wifi" network and follow the steps above.
I've used Sothink SWF decompiler a couple of times, the only problem is that as project gets more complex, the output of decompiler gets harder to compile back again. But it ensures that you can get your .as files most of the time, compilable fla is a question.
I had the same issue. Tried all the solutions mentioned here but nothing worked. So i rebooted my device and suddenly the issue solved.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
System.out.println(LocalDate.parse("08/16/2011", dateFormatter));
Output:
2011-08-16
I am contributing the modern answer. The answer by Bohemian is correct and was a good answer when it was written 6 years ago. Now the notoriously troublesome SimpleDateFormat
class is long outdated and we have so much better in java.time
, the modern Java date and time API. I warmly recommend you use this instead of the old date-time classes.
When I parse 08/16/2011
using your snippet, I get Sun Jan 16 00:08:00 CET 2011
. Since lowercase mm
is for minutes, I get 00:08:00
(8 minutes past midnight), and since uppercase DD
is for day of year, I get 16 January.
In java.time
too format pattern strings are case sensitive, and we needed to use uppercase MM
for month and lowercase dd for day of month.
Yes, java.time
works nicely on Java 6 and later and on both older and newer Android devices.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).JavaScript objects cannot be implemented purely on top of hash maps.
Try this in your browser console:
var foo = {
a: true,
b: true,
z: true,
c: true
}
for (var i in foo) {
console.log(i);
}
...and you'll recieve them back in insertion order, which is de facto standard behaviour.
Hash maps inherently do not maintain ordering, so JavaScript implementations may use hash maps somehow, but if they do, it'll require at least a separate index and some extra book-keeping for insertions.
Here's a video of Lars Bak explaining why v8 doesn't use hash maps to implement objects.
To better understand the volume
instruction in dockerfile, let us learn the typical volume usage in mysql official docker file implementation.
VOLUME /var/lib/mysql
Reference: https://github.com/docker-library/mysql/blob/3362baccb4352bcf0022014f67c1ec7e6808b8c5/8.0/Dockerfile
The /var/lib/mysql
is the default location of MySQL that store data files.
When you run test container for test purpose only, you may not specify its mounting point,e.g.
docker run mysql:8
then the mysql container instance will use the default mount path which is specified by the volume
instruction in dockerfile. the volumes is created with a very long ID-like name inside the Docker root, this is called "unnamed" or "anonymous" volume. In the folder of underlying host system /var/lib/docker/volumes.
/var/lib/docker/volumes/320752e0e70d1590e905b02d484c22689e69adcbd764a69e39b17bc330b984e4
This is very convenient for quick test purposes without the need to specify the mounting point, but still can get best performance by using Volume for data store, not the container layer.
For a formal use, you will need to specify the mount path by using named volume or bind mount, e.g.
docker run -v /my/own/datadir:/var/lib/mysql mysql:8
The command mounts the /my/own/datadir directory from the underlying host system as /var/lib/mysql inside the container.The data directory /my/own/datadir won't be automatically deleted, even the container is deleted.
Usage of the mysql official image (Please check the "Where to Store Data" section):
Reference: https://hub.docker.com/_/mysql/
Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.
> man signal
11 SIGSEGV create core image segmentation violation
Writing to a NULL pointer is probably going to cause a SIGSEGV signal
A var
cannot be set to null
since it needs to be statically typed.
var foo = null;
// compiler goes: "Huh, what's that type of foo?"
However, you can use this construct to work around the issue:
var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."
I don't know for sure, but from what I heard you can also use dynamic
instead of var
. This does not require static typing.
dynamic foo = null;
foo = "hi";
Also, since it was not clear to me from the question if you meant the var
keyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:
string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable
But you cannot do this:
int i = null; // integers cannot contain null
Here's what I've got so far (found it on the page Ben Alpert mentioned):
SELECT REPLACE(
SUBSTRING(
SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId` + 1)
, LENGTH(SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId`)
) + 1)
, ','
, ''
)
FROM `clients` c INNER JOIN `clientenrols` e USING (`clientId`)
My problem was; None admin users were getting "the http request is unauthorized with client authentication scheme 'negotiate' asmx" on my asmx services.
I gived read/execute folder permissions for the none admin users and my problem was solved.
I'm struggling with the same here. But I can show you what I've got doing some research. Basically, you first start adding the page @Output event in the foo.template.ts:
<md-paginator #paginator
[length]="length"
[pageIndex]="pageIndex"
[pageSize]="pageSize"
[pageSizeOptions]="[5, 10, 25, 100]"
(page)="pageEvent = getServerData($event)"
>
</md-paginator>
And later, you have to add the pageEvent attribute in the foo.component.ts class and the others to handle paginator requirements:
pageEvent: PageEvent;
datasource: null;
pageIndex:number;
pageSize:number;
length:number;
And add the method that will fetch the server data:
ngOnInit() {
getServerData(null) ...
}
public getServerData(event?:PageEvent){
this.fooService.getdata(event).subscribe(
response =>{
if(response.error) {
// handle error
} else {
this.datasource = response.data;
this.pageIndex = response.pageIndex;
this.pageSize = response.pageSize;
this.length = response.length;
}
},
error =>{
// handle error
}
);
return event;
}
So, basically every time you click the paginator, you'll activate getServerData(..) method that will call foo.service.ts getting all data required. In this case, you do not need to handle nextPage and nextXXX events because it will be automatically calculated upon view rendering.
Hope this can help you. Let me know if you had success. =]
You can get a request parameter id using the expression:
<h:outputText value="#{param['id']}" />
Section 5.3.1.2 of the JSF 1.0 specification defines the objects that must be resolved by the variable resolver.
Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
Try:
sudo apt-get install python-tk python3-tk tk-dev
If you're using python3, then Python3 virtual environment(venv) is also required. Use:
sudo apt install python3-venv
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
Another alternative:
head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1
One more option is WinRun4J. There is an Eclipse Plugin for WinRun4J that allows you to export your application as a single executable with necessary jars/classes embedded.
(full disclosure: I work on this project)
Add this in MainActivity.
Intent intent = new Intent(getApplicationContext(), Heightimage.class);
startActivity(intent);
Try pasting this code in CMD:
keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>Children ({this.props.children.length}):</div>_x000D_
{this.props.children}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>First <code>Example</code>:</div>_x000D_
<Example>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
</Example>_x000D_
<div>Second <code>Example</code> with different children:</div>_x000D_
<Example>_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</Example>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Widget/>,_x000D_
document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
children
is a special property of React components which contains any child elements defined within the component, e.g. the divs
inside Example
above. {this.props.children}
includes those children in the rendered result.
...what are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.
I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &
is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R
. So the acc parameter ends when it reaches the ampersand character.
That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.
The port was changed to 9001 in 5.4, just changing the port from 9000 to 9001 in the nginx conf and in php-fpm configuration worked for me.
You can use this jquery plugin:
http://digitalbush.com/projects/masked-input-plugin/
Refer to demo tab, phone option.
We are using AspectJ and Java annotations for this purpose. If we need to know to execution time for a method, we simple annotate it. A more advanced version could use an own log level that can enabled and disabled at runtime.
public @interface Trace {
boolean showParameters();
}
@Aspect
public class TraceAspect {
[...]
@Around("tracePointcut() && @annotation(trace) && !within(TraceAspect)")
public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {
Object result;
// initilize timer
try {
result = jp.procced();
} finally {
// calculate execution time
}
return result;
}
[...]
}
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
While I agree that Graeme Blackwood's should be the accepted answer, because it practically solves the issue, it should be noted that a fixed element can be positioned relatively to its container.
I noticed by accident that when applying
-webkit-transform: translateZ(0);
to the body, it made a fixed child relative to it (instead of the viewport). So my fixed elements left
and top
properties were now relative to the container.
So I did some research, and found that the issue was already been covered by Eric Meyer and even if it felt like a "trick", turns out that this is part of the specifications:
For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.
http://www.w3.org/TR/css3-transforms/
So, if you apply any transformation to a parent element, it will become the containing block.
The problem is that the implementation seems buggy/creative, because the elements also stop behaving as fixed (even if this bit doesn't seem to be part of specification).
The same behavior will be found in Safari, Chrome and Firefox, but not in IE11 (where the fixed element will still remain fixed).
Another interesting (undocumented) thing is that when a fixed element is contained inside a transformed element, while its top
and left
properties will now be related to the container, respecting the box-sizing
property, its scrolling context will extend over the border of the element, as if box-sizing was set to border-box
. For some creative out there, this could possibly become a plaything :)