I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value
to set associations.
I solved this by setting a coffeescript var of @valueAttr
to the id
of each object and a var of @dataAttr
to the name
of the record. Then I went through each option and set:
opts.labelField = @dataAttr
opts.valueField = @valueAttr
It helps to see the full diff: https://github.com/18F/C2/pull/912/files
From Java:
public static String GetSubscriptionTenantId (String subscriptionId) throws ClientProtocolException, IOException
{
String tenantId = null;
String url = "https://management.azure.com/subscriptions/" + subscriptionId + "?api-version=2016-01-01";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header[] headers = response.getAllHeaders();
for (Header header : headers)
{
if (header.getName().equals("WWW-Authenticate"))
{
// split by '"' to get the URL, split the URL by '/' to get the ID
tenantId = header.getValue().split("\"")[1].split("/")[3];
}
}
return tenantId;
}
The add
method that takes a String
and a Person
is calling a different add
method that takes a Position
. The one that takes Position
is inherited from the ArrayList
class.
Since your class Staff
extends ArrayList<Position>
, it automatically has the add(Position)
method. The new add(String, Person)
method is one that was written particularly for the Staff class.
You can use the following code to do custom ORDERED serialization and deserialization of JSON Array (This example assumes you are ordering Strings but can be applied to all types):
Serialization
JSONArray params = new JSONArray();
int paramIndex = 0;
for (String currParam : mParams)
{
JSONObject paramObject = new JSONObject();
paramObject.put("index", paramIndex);
paramObject.put("value", currParam);
params.put(paramObject);
++paramIndex;
}
json.put("orderedArray", params);
Deserialization
JSONArray paramsJsonArray = json.optJSONArray("orderedArray");
if (null != paramsJsonArray)
{
ArrayList<String> paramsArr = new ArrayList<>();
for (int i = 0; i < paramsJsonArray.length(); i++)
{
JSONObject param = paramsJsonArray.optJSONObject(i);
if (null != param)
{
int paramIndex = param.optInt("index", -1);
String paramValue = param.optString("value", null);
if (paramIndex > -1 && null != paramValue)
{
paramsArr.add(paramIndex, paramValue);
}
}
}
}
The reason your functor example does not work is that you need an instance to invoke the operator()
.
Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.
Root could not erase a file.
I did my research. Turns out there's something called an immutable bit.
# lsattr /path/file
----i-------- /path/file
#
This bit being configured prevents even root from modifying/removing it.
To remove this I did:
# chattr -i /path/file
After that I could rm the file.
In reverse, it's a neat trick to know if you have something you want to keep from being gone.
:)
If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.
Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true
.
You can't set it when code running, as the java.net just read it when jvm starting.
And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.
There are a few different ways of doing this. I prefer using apply
, since it's easily extendable:
##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)
##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
Both commands are working like charm :)
I tried this tool and it gave me good results.
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
template <typename ...A>
constexpr auto assign(A& ...a) noexcept
{
return [&](auto&& ...v) noexcept(noexcept(
((a = std::forward<decltype(v)>(v)), ...)))
{
((a = std::forward<decltype(v)>(v)), ...);
};
}
int column, row, index;
assign(column, row, index)(0, 0, 0);
The action
attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
There is no reason to use $_SERVER['PHP_SELF']
, and #
doesn't submit the form at all (unless there is a submit
event handler attached that handles the submission).
You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator
public class FooImpl implements Foo {
private static final Logger LOGGER = Logger.getLogger(FooBar.class);
public Object createObject() {
BasicConfigurator.configure();
LOGGER.info("something");
return new Object();
}
}
So under the table, configure do:
configure() {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}
For VS 2019, this should work without installing anything:
//#region MyRegion1
foo() {
}
//#endregion
//#region MyRegion2
bar() {
}
//#endregion
To store actual Unicode codepoints, you have to first decode the String's UTF-16 codeunits to UTF-32 codeunits (which are currently the same as the Unicode codepoints). Use System.Text.Encoding.UTF32.GetBytes()
for that, and then write the resulting bytes to the StringBuilder
as needed,i.e.
static void Main(string[] args)
{
String originalString = "This string contains the unicode character Pi(p)";
Byte[] bytes = Encoding.UTF32.GetBytes(originalString);
StringBuilder asAscii = new StringBuilder();
for (int idx = 0; idx < bytes.Length; idx += 4)
{
uint codepoint = BitConverter.ToUInt32(bytes, idx);
if (codepoint <= 127)
asAscii.Append(Convert.ToChar(codepoint));
else
asAscii.AppendFormat("\\u{0:x4}", codepoint);
}
Console.WriteLine("Final string: {0}", asAscii);
Console.ReadKey();
}
For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.
Required here
<div class="outer">Outer Text
<div class="inner"> Inner Text</div>
</div>
added by
$(document).ready(function(){
$('.inner').prepend('<div class="middle">New Text Middle</div>');
});
In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"
I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)
If you are using RC5 then import this:
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
and be sure to import CommonModule
from the module that is providing your component.
@NgModule({
imports: [CommonModule],
declarations: [MyComponent]
...
})
class MyComponentModule {}
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
If you just want to have your header font a little bit bigger then the rest, you can use ScaleTransform. so you do not depend on the real fontsize.
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor">
<TextBlock.LayoutTransform>
<ScaleTransform ScaleX="1.1" ScaleY="1.1" />
</TextBlock.LayoutTransform>
</TextBlock>
You can access the fields by indexing the object array:
foreach (object[] item in selectedValues)
{
idTextBox.Text = item[0];
titleTextBox.Text = item[1];
contentTextBox.Text = item[2];
}
That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:
public class MyObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Then you can do:
foreach (MyObject item in selectedValues)
{
idTextBox.Text = item.Id;
titleTextBox.Text = item.Title;
contentTextBox.Text = item.Content;
}
I had this problem (colons in the target name) because I had -n
in my GREP_OPTIONS
environment variable. Apparently, this caused configure
to generate the Makefile
incorrectly.
Use String.Format()
or TextWriter.Format()
(depending on how you actually write to the file) and specify the width of a field.
String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");
You can specify the width of a field within interpolated strings as well:
$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"
And just so you know, you can create a string of repeated characters using the appropriate string contructor.
new String(' ', 20); // string of 20 spaces
I was looking for a similar problem and found a better approach of doing this. So here it goes.
You can simply put the following line on the redirection page (say page1.php).
header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php
I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.
Here is the reference link.
I liked the plugin that Vinny's written and have been using. But in case of tables inside sliding row (tr/td), the rows of nested table are always hidden even after slid up. So I did a quick and simple hack in the plugin not to hide the rows of nested table. Just change the following line
var $cells = $(this).find('td');
to
var $cells = $(this).find('> td');
which finds only immediate tds not nested ones. Hope this helps someone using the plugin and have nested tables.
If you have nodemon
installed globally, simply running nodemon
in your project will automatically run the start
script from package.json
.
For example:
"scripts": {
"start": "node src/server.js"
},
From the nodemon documentation:
nodemon will also search for the scripts.start property in package.json (as of nodemon 1.1.x).
both <button>
tag and <input type="button">
accept a title attribute..
Two differences:
Equals
is polymorphic (i.e. it can be overridden, and the implementation used will depend on the execution-time type of the target object), whereas the implementation of ==
used is determined based on the compile-time types of the objects:
// Avoid getting confused by interning
object x = new StringBuilder("hello").ToString();
object y = new StringBuilder("hello").ToString();
if (x.Equals(y)) // Yes
// The compiler doesn't know to call ==(string, string) so it generates
// a reference comparision instead
if (x == y) // No
string xs = (string) x;
string ys = (string) y;
// Now *this* will call ==(string, string), comparing values appropriately
if (xs == ys) // Yes
Equals
will go bang if you call it on null, == won't
string x = null;
string y = null;
if (x.Equals(y)) // Bang
if (x == y) // Yes
Note that you can avoid the latter being a problem using object.Equals
:
if (object.Equals(x, y)) // Fine even if x or y is null
The best cross-browser solution is
background: #fff;
background: -moz-linear-gradient(#fff, #000);
background: -webkit-linear-gradient(#fff, #000);
background: -o-linear-gradient(#fff, #000);
background: -ms-linear-gradient(#fff, #000);/*For IE10*/
background: linear-gradient(#fff, #000);
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ffffff', endColorstr='#000000');/*For IE7-8-9*/
height: 1%;/*For IE7*/
Here I am posting you the some code example which record good quality of sound using AudioRecord API.
Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.
public class Audio_Record extends Activity {
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord recorder = null;
private Thread recordingThread = null;
private boolean isRecording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
}
private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}
private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnStop, isRecording);
}
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
private void startRecording() {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//convert short to byte
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short writing to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
enableButtons(false);
stopRecording();
break;
}
}
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
}
For more detail try this AUDIORECORD BLOG.
Happy Coding !!
Select date1 - (date2 - 1) * 24 * 60 *60 * 1000 from Table;
You can do this with GNU grep's perl mode:
echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o
-P
means Perl-style, and -o
means match only.
In order for z-index to work, you'll need to give the element a position:absolute
or a position:relative
property. Once you do that, your links will function properly, though you may have to tweak your CSS a bit afterwards.
Simply convert int
to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:@"%d",x];
This will work as long as your number is a whole number:
double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
If the double variable has precision after the decimal point it will truncate it.
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
You need the :not()
selector:
$('div[class^="first-"]:not(.first-bar)')
or, alternatively, the .not()
method:
$('div[class^="first-"]').not('.first-bar');
You can view the source of the file up to a particular commit by appending
?until=<sha-of-commit>
in the URL (after the file name).
On the MacOS, with pip
installed via MacPorts into the MacPorts python2.7, I had to use @Dunes solution:
sudo python -m pip install some-package.whl
Where python
was replaced by the MacPorts python in my case, which is python2.7
or python3.5
for me.
The -m
option is "Run library module as script" according to the manpage.
(I had previously run sudo port install py27-pip py27-wheel
to install pip
and wheel
into my python 2.7 installation first.)
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
compaudit | xargs chmod g-w
will do the trick, see http://www.wezm.net/technical/2008/09/zsh-cygwin-and-insecure-directories/
One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)
The correct solution is
Dim copyToRow: copyToRow = 5
Rows(copyToRow & ":" & copyToRow).Select
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
http://code.google.com/apis/gdata/articles/dotnet_client_lib.html
This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!
You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.
You can access the data-type of a column with dtype
:
for y in agg.columns:
if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
treat_numeric(agg[y])
else:
treat_str(agg[y])
I believe telnet 74.255.12.25 8089
. Why don't u try both
I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.
If you simply want to know if the sets are equal, the equals
method on AbstractSet
is implemented roughly as below:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection c = (Collection) o;
if (c.size() != size())
return false;
return containsAll(c);
}
Note how it optimizes the common cases where:
After that, containsAll(...)
will return false
as soon as it finds an element in the other set that is not also in this set. But if all elements are present in both sets, it will need to test all of them.
The worst case performance therefore occurs when the two sets are equal but not the same objects. That cost is typically O(N)
or O(NlogN)
depending on the implementation of this.containsAll(c)
.
And you get close-to-worst case performance if the sets are large and only differ in a tiny percentage of the elements.
UPDATE
If you are willing to invest time in a custom set implementation, there is an approach that can improve the "almost the same" case.
The idea is that you need to pre-calculate and cache a hash for the entire set so that you could get the set's current hashcode value in O(1)
. Then you can compare the hashcode for the two sets as an acceleration.
How could you implement a hashcode like that? Well if the set hashcode was:
then you could cheaply update the set's cached hashcode each time you added or removed an element. In both cases, you simply XOR the element's hashcode with the current set hashcode.
Of course, this assumes that element hashcodes are stable while the elements are members of sets. It also assumes that the element classes hashcode function gives a good spread. That is because when the two set hashcodes are the same you still have to fall back to the O(N)
comparison of all elements.
You could take this idea a bit further ... at least in theory.
WARNING - This is highly speculative. A "thought experiment" if you like.
Suppose that your set element class has a method to return a crypto checksums for the element. Now implement the set's checksums by XORing the checksums returned for the elements.
What does this buy us?
Well, if we assume that nothing underhand is going on, the probability that any two unequal set elements have the same N-bit checksums is 2-N. And the probability 2 unequal sets have the same N-bit checksums is also 2-N. So my idea is that you can implement equals
as:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection c = (Collection) o;
if (c.size() != size())
return false;
return checksums.equals(c.checksums);
}
Under the assumptions above, this will only give you the wrong answer once in 2-N time. If you make N large enough (e.g. 512 bits) the probability of a wrong answer becomes negligible (e.g. roughly 10-150).
The downside is that computing the crypto checksums for elements is very expensive, especially as the number of bits increases. So you really need an effective mechanism for memoizing the checksums. And that could be problematic.
And the other downside is that a non-zero probability of error may be unacceptable no matter how small the probability is. (But if that is the case ... how do you deal with the case where a cosmic ray flips a critical bit? Or if it simultaneously flips the same bit in two instances of a redundant system?)
Partial Class _Default
Inherits System.Web.UI.Page
Dim str As String
Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed
str += "PAGE DISPOSED" & "<br />"
End Sub
Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
str += "PAGE ERROR " & "<br />"
End Sub
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
str += "PAGE INIT " & "<br />"
End Sub
Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
str += "INIT Complte " & "<br />"
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
str += "PAGE LOAD " & "<br />"
End Sub
Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
str += "PAGE LOAD Complete " & "<br />"
End Sub
Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
str = ""
str += "PAGE PRE INIT" & "<br />"
End Sub
Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
str += "PAGE PRE LOAD " & "<br />"
End Sub
Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
str += "PAGE PRE RENDER " & "<br />"
End Sub
Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
str += "PAGE PRE RENDER COMPLETE " & "<br />"
End Sub
Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
str += "PAGE SAVE STATE COMPLTE " & "<br />"
lbl.Text = str
End Sub
Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
'Response.Write("PAGE UN LOAD\n")
End Sub
End Class
Now that the question is clearer, you can just do this in one grep
grep -R --include "*bills*" "put" .
With relevant flags
-R, -r, --recursive
Read all files under each directory, recursively; this is
equivalent to the -d recurse option.
--include=GLOB
Search only files whose base name matches GLOB (using wildcard
matching as described under --exclude).
I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.
if column.class < Numeric
number_to_currency(column)
else
column.html_safe
end
In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex
df.astype(str).apply(lambda x: ' is '.join(x), axis=1)
0 1 is a
1 2 is b
2 3 is c
dtype: object
Take a peek at the ng-click
directive source:
...
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
It shows how the event
object is being passed on to the ng-click
expression, using $event
as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event
object any other way but through the callback parameter.
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
Regarding your code: It's slightly hard to read... If you want to try to view it all in a php array format, just print_r it. This might help:
<?php
$a =
array(
'languages' =>
array (
76 =>
array ( 'id' => '76', 'tag' => 'Deutsch', ), ), 'targets' =>
array ( 81 =>
array ( 'id' => '81', 'tag' => 'Deutschland', ), ), 'tags' =>
array ( 7866 =>
array ( 'id' => '7866', 'tag' => 'automobile', ), 17800 =>
array ( 'id' => '17800', 'tag' => 'seat leon', ), 17801 =>
array ( 'id' => '17801', 'tag' => 'seat leon cupra', ), ),
'inactiveTags' =>
array ( 195 =>
array ( 'id' => '195', 'tag' => 'auto', ), 17804 =>
array ( 'id' => '17804', 'tag' => 'coupès', ), 17805 =>
array ( 'id' => '17805', 'tag' => 'fahrdynamik', ), 901 =>
array ( 'id' => '901', 'tag' => 'fahrzeuge', ), 17802 =>
array ( 'id' => '17802', 'tag' => 'günstige neuwagen', ), 1991 =>
array ( 'id' => '1991', 'tag' => 'motorsport', ), 2154 =>
array ( 'id' => '2154', 'tag' => 'neuwagen', ), 10660 =>
array ( 'id' => '10660', 'tag' => 'seat', ), 17803 =>
array ( 'id' => '17803', 'tag' => 'sportliche ausstrahlung', ), 74 =>
array ( 'id' => '74', 'tag' => 'web 2.0', ), ), 'categories' =>
array ( 16082 =>
array ( 'id' => '16082', 'tag' => 'Auto & Motorrad', ), 51 =>
array ( 'id' => '51', 'tag' => 'Blogosphäre', ), 66 =>
array ( 'id' => '66', 'tag' => 'Neues & Trends', ), 68 =>
array ( 'id' => '68', 'tag' => 'Privat', ), ), );
printarr($a);
printarr($a['languages'][76]['tag']);
parintarr($a['targets'][81]['id']);
function printarr($in){
echo "\n";
print_r($in);
echo "\n";
}
//run in php command line php path/to/file.php to test, switching otu the print_r.
Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.
I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.
Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":
if (allDay)
{
$( "#even_allday_yn").prop('checked', true);
}
else
{
$( "#even_allday_yn").prop('checked', false);
}
I did it like this:
li {
list-style: none;
background-image: url("./assets/img/control.svg");
background-repeat: no-repeat;
background-position: left center;
}
Or you can try this if you want to change the color:
li::before {
content: "";
display: inline-block;
height: 10px;
width: 10px;
margin-right: 7px;
background-color: orange;
-webkit-mask-image: url("./assets/img/control.svg");
-webkit-mask-size: cover;
}
When you change files or add a new ones in repository you first must stage them.
git add <file>
or if you want to stage all
git add .
By doing this you are telling to git what files you want in your next commit. Then you do:
git commit -m 'your message here'
You use
git push origin master
where origin is the remote repository branch and master is your local repository branch.
Try this
SELECT Count(*) AS N
FROM
(SELECT DISTINCT Name FROM table1) AS T;
Read this for more info.
You can quit, either by pressing the Back button or by calling finish()
in your Activity
. Just call finish()
from a MenuItem
if you want to explicitly kill it off.
Romain isn't saying it can't be done, just that it's pointless — users don't need to care about quitting or saving their work or whatever, as the way the application lifecycle works encourages you to write smart software that automatically saves and restores its state no matter what happens.
Given a file application.yaml
in test/resources
ll src/test/resources/
total 6
drwxrwx--- 1 root vboxsf 4096 Oct 6 12:23 ./
drwxrwx--- 1 root vboxsf 0 Sep 29 17:05 ../
-rwxrwx--- 1 root vboxsf 142 Sep 22 23:59 application.properties*
-rwxrwx--- 1 root vboxsf 78 Oct 6 12:23 application.yaml*
-rwxrwx--- 1 root vboxsf 0 Sep 22 17:31 db.properties*
-rwxrwx--- 1 root vboxsf 618 Sep 22 23:54 log4j2.json*
From the test context, I can get the file with
String file = getClass().getClassLoader().getResource("application.yaml").getPath();
which will actually point to the file in test-classes
ll target/test-classes/
total 10
drwxrwx--- 1 root vboxsf 4096 Oct 6 18:49 ./
drwxrwx--- 1 root vboxsf 4096 Oct 6 18:32 ../
-rwxrwx--- 1 root vboxsf 142 Oct 6 17:35 application.properties*
-rwxrwx--- 1 root vboxsf 78 Oct 6 17:35 application.yaml*
drwxrwx--- 1 root vboxsf 0 Oct 6 18:50 com/
-rwxrwx--- 1 root vboxsf 0 Oct 6 17:35 db.properties*
-rwxrwx--- 1 root vboxsf 618 Oct 6 17:35 log4j2.json*
Other options, not based on NOPASSWD:
Lombok is great, but...
Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.
Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.
I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.
All radio buttons inside of a share container are in the same group by default.
Means, if you check one of them - others will be unchecked.
If you want to create independent groups of radio buttons, you must situate them into different containers such as Group Box
, or control their Checked state through code behind.
Quirk single-line solutions on every day.
Values in arrays is total random, so when you will be use this snippets, it will different.
An array (length 10) with random chars in lowercase
Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })
[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]
An array (length 10) with random integer numbers from 0 to 99
Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })
[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]
An array random dates (from 10 years to ago to now)
Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})
[ 2008-08-22T21:00:00.000Z, 2007-07-17T21:00:00.000Z,
2015-05-05T21:00:00.000Z, 2011-06-14T21:00:00.000Z,
2009-07-23T21:00:00.000Z, 2009-11-13T22:00:00.000Z,
2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
2016-05-06T21:00:00.000Z, 2014-08-06T21:00:00.000Z ]
An array (length 10) random strings
Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10 + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });
[ 'cubjjhaph', 'bmwy', 'alhobd', 'ceud', 'tnyullyn', 'vpkdflarhnf', 'hvg', 'arazuln', 'jzz', 'cyx' ]
Other useful things you may found here https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js
The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden;
on the containing element. For example
.parent {_x000D_
background: red;_x000D_
overflow: hidden;_x000D_
}_x000D_
.segment-a {_x000D_
float: left;_x000D_
}_x000D_
.segment-b {_x000D_
float: right;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="segment-a">_x000D_
Float left_x000D_
</div>_x000D_
<div class="segment-b">_x000D_
Float right_x000D_
</div>_x000D_
</div>
_x000D_
Of course this can only be used in instances where you never wish the content to overflow.
As for "pure python" solutions: the package index lists:
The sed command allows you to use other characters instead of /
as separator:
sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'
The double quotes are not a problem.
If you want to see the changes introduced with each commit, try "git log -p"
This is the function that I use for this calculation:
public static int binlog( int bits ) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
It is slightly faster than Integer.numberOfLeadingZeros() (20-30%) and almost 10 times faster (jdk 1.6 x64) than a Math.log() based implementation like this one:
private static final double log2div = 1.000000000001 / Math.log( 2 );
public static int log2fp0( int bits )
{
if( bits == 0 )
return 0; // or throw exception
return (int) ( Math.log( bits & 0xffffffffL ) * log2div );
}
Both functions return the same results for all possible input values.
Update:
The Java 1.7 server JIT is able to replace a few static math functions with alternative implementations based on CPU intrinsics. One of those functions is Integer.numberOfLeadingZeros(). So with a 1.7 or newer server VM, a implementation like the one in the question is actually slightly faster than the binlog
above. Unfortunatly the client JIT doesn't seem to have this optimization.
public static int log2nlz( int bits )
{
if( bits == 0 )
return 0; // or throw exception
return 31 - Integer.numberOfLeadingZeros( bits );
}
This implementation also returns the same results for all 2^32 possible input values as the the other two implementations I posted above.
Here are the actual runtimes on my PC (Sandy Bridge i7):
JDK 1.7 32 Bits client VM:
binlog: 11.5s
log2nlz: 16.5s
log2fp: 118.1s
log(x)/log(2): 165.0s
JDK 1.7 x64 server VM:
binlog: 5.8s
log2nlz: 5.1s
log2fp: 89.5s
log(x)/log(2): 108.1s
This is the test code:
int sum = 0, x = 0;
long time = System.nanoTime();
do sum += log2nlz( x ); while( ++x != 0 );
time = System.nanoTime() - time;
System.out.println( "time=" + time / 1000000L / 1000.0 + "s -> " + sum );
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.
>> signal
signal =
sin: {{1x1x25 cell} {1x1x25 cell}}
cos: {{1x1x25 cell} {1x1x25 cell}}
>> each(fieldnames(signal))
ans =
CellIterator with properties:
NumberOfIterations: 2.0000e+000
Usage:
for bridge = each(fieldnames(signal))
signal.(bridge) = rand(10);
end
I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
queryForList returns a List of LinkedHashMap objects.
You need to cast it first like this:
List list = jdbcTemplate.queryForList(...); for (Object o : list) { Map m = (Map) o; ... }
It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.
To answer your question:
typedef void (*foobar)() fubarfn;
void Fun(fubarfn& baz){
fubarfn = baz;
baz();
}
Edit:
&
means the reference address*
means the value of what's contained at the reference address, called de-referencingSo using the reference, example below, shows that we are passing in a parameter, and directly modify it.
void FunByRef(int& iPtr){
iPtr = 2;
}
int main(void){
// ...
int n;
FunByRef(n);
cout << n << endl; // n will have value of 2
}
This worked for me in Laravel 5.8
return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');
Or instead of / you can use
use Redirect;
If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:
Behavior of this function, and therefore the results it returns, can change from release to release. ...
Declare a public string in form1
public string getdata;
In button of form1
form2 frm= new form2();
this.hide();
form2.show();
To send data to form1
you can try any event and code following in that event
form1 frm= new form1();
form1.getdata="some string to be sent to form1";
Now after closing of form2
and opening of form1
, you can use returned data in getdata
string.
If you just need to convert timezones I have uploaded a stripped-down version of moment-timezone with just the bare minimum functionallity. Its ~1KB + data:
S.loadData({
"zones": [
"Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
"Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
],
"links": [
"Europe/Paris|Europe/Madrid",
]
});
let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());
The answer is Yes if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.
Yes. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction.
Be careful to only use WITH (NOLOCK)
in SELECT statements on tables that have a clustered index.
WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.
The result set can contain rows that have not yet been committed, that are often later rolled back.
If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times.
READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.
The MACAddress property of the Win32_NetworkAdapterConfiguration WMI class can provide you with an adapter's MAC address. (System.Management Namespace)
MACAddress
Data type: string
Access type: Read-only
Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter.
Example: "00:80:C7:8F:6C:96"
If you're not familiar with the WMI API (Windows Management Instrumentation), there's a good overview here for .NET apps.
WMI is available across all version of windows with the .Net runtime.
Here's a code example:
System.Management.ManagementClass mc = default(System.Management.ManagementClass);
ManagementObject mo = default(ManagementObject);
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (var mo in moc) {
if (mo.Item("IPEnabled") == true) {
Adapter.Items.Add("MAC " + mo.Item("MacAddress").ToString());
}
}
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
Andy's response worked for me by escaping $path:
git submodule foreach "(git checkout master; git pull; cd ..; git add \$path; git commit -m 'Submodule Sync')"
Unexpected 'O' error is thrown when JSON data or String happens to get parsed.
If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.
I faced similar( although in different context), I solved the following error by removing JSON Producer.
@POST
@Produces({ **MediaType.APPLICATION_JSON**})
public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
return Response.status(200).entity("OK").build();
}
The response contains "OK" string return. The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.
Removing @Produces({ MediaType.APPLICATION_JSON}) works fine. Output : OK
Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'
O is the first letter of the string
JSON.parse(object) compares with jQuery.parseJSON(object);
JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine
As other answers have noted, assert
is similar to throwing an exception if a given condition isn't true. An important difference is that assert statements get ignored if you compile your code with the optimization option -O
. The documentation says that assert expression
can better be described as being equivalent to
if __debug__:
if not expression: raise AssertionError
This can be useful if you want to thoroughly test your code, then release an optimized version when you're happy that none of your assertion cases fail - when optimization is on, the __debug__
variable becomes False and the conditions will stop getting evaluated. This feature can also catch you out if you're relying on the asserts and don't realize they've disappeared.
You tagged the question with both sql-server and plsql so I will provide answers for both SQL Server and Oracle.
In SQL Server you can use FOR XML PATH
to concatenate multiple rows together:
select distinct t.[user],
STUFF((SELECT distinct ', ' + t1.department
from yourtable t1
where t.[user] = t1.[user]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') department
from yourtable t;
See SQL Fiddle with Demo.
In Oracle 11g+ you can use LISTAGG
:
select "User",
listagg(department, ',') within group (order by "User") as departments
from yourtable
group by "User"
Prior to Oracle 11g, you could use the wm_concat
function:
select "User",
wm_concat(department) departments
from yourtable
group by "User"
It seems like a Android Runtime bug. There seems to be finalizer that runs in its separate thread and calls finalize() method on objects if they are not in the current frame of the stacktrace. For example following code(created to verify this issue) ended with the crash.
Let's have some cursor that do something in finalize method(e.g. SqlCipher ones, do close() which locks to the database that is currently in use)
private static class MyCur extends MatrixCursor {
public MyCur(String[] columnNames) {
super(columnNames);
}
@Override
protected void finalize() {
super.finalize();
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And we do some long running stuff having opened cursor:
for (int i = 0; i < 7; i++) {
new Thread(new Runnable() {
@Override
public void run() {
MyCur cur = null;
try {
cur = new MyCur(new String[]{});
longRun();
} finally {
cur.close();
}
}
private void longRun() {
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
This causes following error:
FATAL EXCEPTION: FinalizerWatchdogDaemon
Process: la.la.land, PID: 29206
java.util.concurrent.TimeoutException: MyCur.finalize() timed out after 10 seconds
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:371)
at java.lang.Thread.sleep(Thread.java:313)
at MyCur.finalize(MessageList.java:1791)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)
at java.lang.Thread.run(Thread.java:762)
The production variant with SqlCipher is very similiar:
12-21 15:40:31.668: E/EH(32131): android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): java.util.concurrent.TimeoutException: android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Object.wait(Native Method)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.parkFor$(Thread.java:2128)_x000D_
12-21 15:40:31.668: E/EH(32131): at sun.misc.Unsafe.park(Unsafe.java:325)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.LockSupport.park(LockSupport.java:161)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:840)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:873)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1197)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock$FairSync.lock(ReentrantLock.java:200)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteDatabase.lock(SourceFile:518)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteProgram.close(SourceFile:294)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteQuery.close(SourceFile:136)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteCursor.close(SourceFile:510)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.close(ContentResolver.java:2746)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.finalize(ContentResolver.java:2757)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.run(Thread.java:762)
_x000D_
Resume: Close cursors ASAP. At least on Samsung S8 with Android 7 where the issue have been seen.
If you are using the standard eclipse IDE provided by google for Android development, you can check the "Launcher Activity" check-box while creating a new Activity. Please find below:
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
Also see:
http://www.techonthenet.com/sql/order_by.php
For a description of order by. I learned something! :)
I've also used this in the past when I wanted to add an indeterminate number of filters to a sql statement. Sloppy I know, but it worked. :P
I had a similar issue but the cause was because I had 40px of margin at the bottom of the page, so the very last row would always wrap even if there were room for it on the last page. Not because of any kind of page-break-*
css command. I fixed by removing the margin on print and it worked fine. Just wanted to add my solution in case someone else has something similar!
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
Me help next:
git stash
git pull origin master
git apply
git commit -m "some comment"
git push
Regarding this topic the specification (ecma-262) is quite clear
I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm
I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.
I hope you find it useful.
If I got you correctly, it is as easy as
cartDiv.id = "someID";
No need for jQuery.
Have a look at the properties of a DOM Element.
For classes it is the same:
cartDiv.className = "classes here";
But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
plt.errorbar
can be used to plot x, y, error data (as opposed to the usual plt.plot
)
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])
plt.errorbar(x, y, e, linestyle='None', marker='^')
plt.show()
plt.errorbar
accepts the same arguments as plt.plot
with additional yerr
and xerr
which default to None (i.e. if you leave them blank it will act as plt.plot
).
#! /bin/bash
if [ $# != "1" ];then
echo "Not enough arguments.";
echo "Usage: killQueryByDB.sh <db_name>";
exit;
fi;
DB=${1};
for i in `mysql -u <user> -h localhost ${DB} -p<password> -e "show processlist" | sed 's/\(^[0-9]*\).*/\1/'`; do
echo "Killing query ${i}";
mysql -u <user> -h localhost ${DB} -p<password> -e "kill query ${i}";
done;
int a = fork();
Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.
The child getting 0 returned, and the parent getting the new pid.
Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.
At each fork
, only one value is modified - the return value from fork
.
you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
to
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*"));
and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)
Also check it
jQuery: Customizable layout using drag and drop (examples)
Easiest way with 1.7+ is:
$("#myDropDown option:text=" + myText +"").attr("selected", "selected");
1.9+
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Tested and works.
IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.
.container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
width: 400px;_x000D_
height: 100px;_x000D_
background: #000000;_x000D_
padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #000000;_x000D_
border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="inner"></div>_x000D_
</div>
_x000D_
The following ways to fetch local JSON file-
ES6 version:
import customData from './customData.json';
or import customData from './customData';
If it's inside .js
file instead of .json
then import like -
import { customData } from './customData';
for more clarification/understanding refer example - Live working demo
Originally from a Codepen pen by Chris Coyier of Codepen/CSS-Tricks
.auto { cursor: auto; }
.default { cursor: default; }
.none { cursor: none; }
.context-menu { cursor: context-menu; }
.help { cursor: help; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.wait { cursor: wait; }
.cell { cursor: cell; }
.crosshair { cursor: crosshair; }
.text { cursor: text; }
.vertical-text { cursor: vertical-text; }
.alias { cursor: alias; }
.copy { cursor: copy; }
.move { cursor: move; }
.no-drop { cursor: no-drop; }
.not-allowed { cursor: not-allowed; }
.all-scroll { cursor: all-scroll; }
.col-resize { cursor: col-resize; }
.row-resize { cursor: row-resize; }
.n-resize { cursor: n-resize; }
.e-resize { cursor: e-resize; }
.s-resize { cursor: s-resize; }
.w-resize { cursor: w-resize; }
.ns-resize { cursor: ns-resize; }
.ew-resize { cursor: ew-resize; }
.ne-resize { cursor: ne-resize; }
.nw-resize { cursor: nw-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.nesw-resize { cursor: nesw-resize; }
.nwse-resize { cursor: nwse-resize; }
body {
text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
.cursors {
display: flex;
flex-wrap: wrap;
}
.cursors > div {
flex: 150px;
padding: 10px 2px;
white-space: nowrap;
border: 1px solid #eee;
border-radius: 5px;
margin: 0 5px 5px 0;
}
.cursors > div:hover {
background: #eee;
}
HTML CSSResult
EDIT ON
.svg {
cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.svg), auto;
}
.svg-base64 {
cursor: url(data:text/html;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSItMjQxIDI0MyAxNiAxNiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojRkYwMDAwO30NCjwvc3R5bGU+DQo8cGF0aCBjbGFzcz0ic3QwIiBkPSJNLTIyOS4yLDI0NGMtMS43LDAtMy4xLDEuNC0zLjgsMi44Yy0wLjctMS40LTIuMS0yLjgtMy44LTIuOGMtMi4zLDAtNC4yLDEuOS00LjIsNC4yYzAsNC43LDQuOCw2LDgsMTAuNg0KCWMzLjEtNC42LDgtNi4xLDgtMTAuNkMtMjI1LDI0NS45LTIyNi45LDI0NC0yMjkuMiwyNDRMLTIyOS4yLDI0NHoiLz4NCjwvc3ZnPg0K), auto;
}
.png-base64 {
cursor: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6M0EwMEYyRjlDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6M0EwMEYyRkFDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozQTAwRjJGN0MyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozQTAwRjJGOEMyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pi/X/ugAAAY6SURBVHja7J1bbBVFHMZ3pVajTQoxCCgaNECqJiJV41NFCdF6CRKrvrRcXkyMD6gQE16MMSbESx9INCYkeHkywRhNiJFUoK3EqDVoRVQIiBpoQDFKC4jYtK7fZP+L0+2e6V7ncvx/ydc953S7Z+b7dWbP7O6Z9YMg8Fj26AKOgIGwGAgDYTEQBsKqQA3yE9/3C28wCLd5C3wnfCPcAl8NN8GNtNrv8M/wN/BuuAfvfNxkECj3HCzuhm+ncs+DL6Nfj8Jn4CPwASp3H7wH5R4r/N7y0EM8iVygMj7cBm+BhwOx2Wweh3fCDwYaW614L3rPnVSGrOUepjqLuvtFgJxnUAQIgVgBD+aoTC0fhDuKVDBluTvovcoq9yBl4RsBgrUXwZ+VWKG4xX/ttRXAuIa2XVW5RSaLtAHBWtPgZ+GxCisV+QzcVSKMLtpm1eUeo4ymVQoEa8yEd2moUNyb0lZO8U+0yUC5RVYzKwGC386F9xuoVOT3g/8+pWWB0Uh/a6rcIrO5pQIhGEMGKxV5WxYoBGObBeUeUkHJBASvzoC/s6BSkd9J031RN7XVonKLDGcUAkIfD3ssqlTkF1MAecHCcvckfSzOAmSDhZWK/IgCxkMWl3tDLiB41gKPWlyxkSA8vBEv97ycRwt0WWTakgfIDosrFblP7gKoi93lQLl3ZAKCR+0OVCryGqncaxwqd3sSEF8GER3txSv9WCxx5Ij1r/ACenwInuVIuT9G2nfEj/Y2JPTBrQ7B8AjAeumxK1oisgaUr2qeDyGtdPC8zpOOno8SWU8AMqHLoj7rGDybz91p0S/wFXKfFT8ZdAPD0KrZlHnNc+pLOSPtWqoCspjz0a7FKiALOR/tWqgCMp/z0a75KiBNnI92Nak+9vJ3E0woCPxaLYRlWAzEvP5RARnhfLRrRAXkBOejXScYiF0aUgE5zPlo10EVkP2cj3Z9qwKyl/PRri9VA8Nm/DzpVfhVANYE/QlPx8BwLLGF+OFHMG4l+tQb/wZW0sDwA85Jm96LvzDpqhM8uxkP93BWlUt8b3EOWsgfMoNJLcQPdzIHOK/K9a6AEX+x1rGsLZxX5Xot6cVaF8pNpxHkpZxbJfoESbdFT5RdFnVbw1hs5twq0/O1fpHYQqiViKsAD3MrKV0f+eEEBV7qFkKtRFwz2835lSox5livWmGqE1QveeEUGKxy1O3Hjl2l7rKkruseLD7kLAtLHLgVF1efm5Rxmi5L6rq2Y/EG51l4ENiZBCNrlxXpKfhHzjW3ngaMwTQrTtllSV3XTVh8Dl/E+WbS20i1U7VCpi5L6rq+xuIxzjeTxDHBR7P8QabLgADlLSxe5pxT6Si8HJmdzZRx2i5L6rrELApb4Q7OvKbEjHltfspT4rm6LKmVjHthn9jPuSfqNHyfn/P6hFxXLuLN/sZiBfwF5z9Bf4lckM9A3g3kvpSUTve2e3wyS4ZxP3LpLbKRQtf2+uEFEcu4pXin4HuLwji/QylhVtJmeMChWRTKnnPlttIYlAGEoFwC9/7PYPwG31pqoygLCEG52PB0ejp9ND6rj3VAonEK/Hqdw/h+qnkUrQFCUMR34zbWKYyBNDONWgVEAvNEzim8bfV2sa8sPSddQAiKmG7vXB3AeDNInqzHLSAERUxWf9JhGBsrnYteNxCCcj18xDEQortdW/Wo0ggQgnIlvNcRGKOqmU/rAog0qu9zYPS9TNdxF6NACEqjZbNOx0ffrToPhBkHQlDE3W1etQyGmKN9ge4jk1YAkcA8ZwmMH+CrjGRgExCCstYwjH3w5cbqbxsQgtJlaFQ/QF+/8BjIZCidmqEIGM3G620rEILygKabAFgBw3ogBGV5xVCsgeEEkIqh7DO9z3ASCEF5uOR9ivhoa91E0c4AISirS4JxXNxU0so6ugSEoKwrCONUYPEk0c4BISjdBe66eZfVdXMUiE+3zMsK5HHPcjkJhKCIy4w+zQDjFc8BOQuEoMxKeeZxN3whA9EDpRU+q4BxLHDoPijOAyEoqxTnwducqks9ACEomxOAPONcPeoIiNjJD0ow+ovcd52BlAPlOtqfnLZ1JJ4FSIPnuPzwBvLr8HAcj39yvj6utox6Fd+ugoGwGAgDYeXVvwIMAGCAb3XkplDRAAAAAElFTkSuQmCC"), auto;
}
.png {
cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.png"), auto;
}
.gif {
cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/tina.gif"), auto;
}
.cursors {
display: flex;
justify-content: flex-start;
align-items: stretch;
height: 100vh;
}
.cursors > div {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
box-sizing: border-box;
padding: 10px 2px;
text-align: center;
}
_x000D_
<h1>The Cursors of CSS</h1>
<div class="cursors">
<div class="auto">auto</div>
<div class="default">default</div>
<div class="none">none</div>
<div class="context-menu">context-menu</div>
<div class="help">help</div>
<div class="pointer">pointer</div>
<div class="progress">progress</div>
<div class="wait">wait</div>
<div class="cell">cell</div>
<div class="crosshair">crosshair</div>
<div class="text">text</div>
<div class="vertical-text">vertical-text</div>
<div class="alias">alias</div>
<div class="copy">copy</div>
<div class="move">move</div>
<div class="no-drop">no-drop</div>
<div class="not-allowed">not-allowed</div>
<div class="all-scroll">all-scroll</div>
<div class="col-resize">col-resize</div>
<div class="row-resize">row-resize</div>
<div class="n-resize">n-resize</div>
<div class="s-resize">s-resize</div>
<div class="e-resize">e-resize</div>
<div class="w-resize">w-resize</div>
<div class="ns-resize">ns-resize</div>
<div class="ew-resize">ew-resize</div>
<div class="ne-resize">ne-resize</div>
<div class="nw-resize">nw-resize</div>
<div class="se-resize">se-resize</div>
<div class="sw-resize">sw-resize</div>
<div class="nesw-resize">nesw-resize</div>
<div class="nwse-resize">nwse-resize</div>
</div>
<br><br><br><br><br><br><br><br><br>
<h1>Custom Image</h1>
<div class="cursors">
<div class="svg"><p>SVG</p></div>
<div class="svg-base64">Base 64 SVG</div>
<div class="png-base64">Base 64 PNG</div>
<div class="png">PNG</div>
<div class="gif">GIF</div>
</div>
_x000D_
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
#testdiv {
border-left: 1px solid;
}
a.button a:hover
means "a link that's being hovered over that is a child of a link with the class button
".
Go instead for a.button:hover
.
UNION ALL
once, aggregate once:
SELECT sum(hours) AS total_hours
FROM (
SELECT hours FROM resource
UNION ALL
SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
) x
For the Platform Independent Users or Windows users, what you can do is:
import runtime:
import (
"runtime"
"strings"
)
and then trim the string like this:
if runtime.GOOS == "windows" {
input = strings.TrimRight(input, "\r\n")
} else {
input = strings.TrimRight(input, "\n")
}
now you can compare it like that:
if strings.Compare(input, "a") == 0 {
//....yourCode
}
This is a better approach when you're making use of STDIN on multiple platforms.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
I think Manoj Gupta had the best answer from what I'm seeing. However, the remove command doesn't get rid of any configuration folders or files that may be leftover. Use:
sudo apt-get purge --auto-remove nodejs
The purge command should remove the package and then clean up any configuration files. (see this question for more info on the difference between purge and remove). The auto-remove flag will do the same for packages that were installed by NodeJS.
See the accepted answer on this question for a better explanation.
Although don't forget to handle NPM! Josh's answer covers that.
I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...
app.run(['$templateCache', function($templateCache) {
var url = "survey-input.html";
content = angular.element(document.getElementById(url)).html()
$templateCache.put(url, content);
}]);
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
You can create several divs and do that:
<div style="width:100px; height:100px;">
<div style="position:relative; top:0px; left:0px; width:100px; height:100px; opacity:0.3;"><img src="urltoimage" alt=" " /></div>
<div style="position:relative; top:0px; left:0px; width:100px; height:100px;"> DIV with no opacity </div>
</div>
I did that couple times... Simple, yet effective...
Concerning whether to raise an exception or return None
: it depends on the use case. Either can be Pythonic.
Look at Python's dict
class for example. x[y]
hooks into dict.__getitem__
, and it raises a KeyError
if key is not present. But the dict.get
method returns the second argument (which is defaulted to None
) if key is not present. They are both useful.
The most important thing to consider is to document that behaviour in the docstring, and make sure that your get_attr()
method does what it says it does.
To address your other questions, use these conventions:
if foo:
# For testing truthiness
if not foo:
# For testing falsiness
if foo is None:
# Testing .. Noneliness ?
if foo is not None:
# Check explicitly avoids common bugs caused by empty sequences being false
Functions that return True
or False
should probably have a name that makes this obvious to improve code readability:
def is_running_on_windows():
return os.name == 'nt'
In Python 3 you can "type-hint" that:
>>> def is_running_on_windows() -> bool:
... return os.name == 'nt'
...
>>> is_running_on_windows.__annotations__
{'return': bool}
And ofcourse you can do:
# a.py
MY_CONSTANT = ...
# b.py
from a import *
print MY_CONSTANT
df = df.replace({np.nan: None})
Credit goes to this guy here on this Github issue.
You have to do something like:
case 1:
case 2:
case 3:
//do stuff
break;
TFS users: If you are using source control that requires you to warn it before your rename files/folders then look at this answer instead which covers the extra steps required.
To rename a project's folder, file (.*proj
) and display name in Visual Studio:
.sln
file directly in another editor such as Notepad++ and update the paths there instead. (You may need to check-out the solution first in TFS, etc.)Note: Other suggested solutions that involve removing and then re-adding the project to the solution will break project references.
If you perform these steps then you might also consider renaming the following to match:
Also consider modifying the values of the following assembly attributes:
AssemblyProductAttribute
AssemblyDescriptionAttribute
AssemblyTitleAttribute
ps -elf doesn't seem to show the PID. I recommend using instead:
ps -ld | grep foo
gdb -p PID
Same thing, with jQuery:
$('#links a').each(function(){
var me = $(this);
me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
});
or
$('#links a').each(function(){
var me = $(this)
, t = me.text().split(' ');
me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
});
(Via 'Wizzud' on the jQuery Mailing List)
Over this summer I've enjoyed:
I echo the sentiment about the difference between tech gossip (TWiT, Diggnation, etc) and software development podcasts; while the former can sometimes be entertaining, I've found they tend towards the audio equivalent of Digg rather than Hacker News, programming.reddit, or, hopefully, StackOverflow.
I'll be checking out the other suggestions people gave.
Uncheck
"Work Offline"
in Settings -> Maven ! It worked for me ! :D
Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.
max-width:something px;
max-height:something px;
The other option would be to use the devlopr tools and see if you can remove the natural padding.
padding: 0;
with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#
but it still limited on so many aspect. And browser support is also not so ready.
your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:
This worked for me:
mysql> FLUSH PRIVILEGES
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES
no, you need to do something like:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
You can also get more specific, such as:
$('input[type=text].sitebg').val('000000');
EDIT:
do this to find your input based on the name attribute:
$('input[name=sitebg]').val('000000');
Try in html:
style="display: inline-block; margin-top: 50px;"
or in css:
display: inline-block;
margin-top: 50px;
Make sure you have package.json
inside root of your project.
Happy coding :)
This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
strings.Find(s => s == "hello");
This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
private static bool FindHello(String s)
{
return s == "hello";
}
strings.Find(FindHello);
EDIT:
In C# 2.0, this could be done using the anonymous delegate syntax:
strings.Find(delegate(String s) { return s == "hello"; });
Lambda's significantly cleaned up that syntax.
If you really want to cover the case that a script is called via execfile(...)
, you can use the inspect
module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
There is already a Twig extension that lets you call PHP functions form your Twig templates like:
Hi, I am unique: {{ uniqid() }}.
And {{ floor(7.7) }} is floor of 7.7.
See official extension repository.
This error can surface because of following two reasons:
There is no room in the memory to accommodate new threads.
The number of threads exceeds the Operating System limit.
I doubt that number of thread have exceeded the limit for the java process
So possibly chances are the issue is because of memory One point to consider is
threads are not created within the JVM heap. They are created outside the JVM heap. So if there is less room left in the RAM, after the JVM heap allocation, application will run into “java.lang.OutOfMemoryError: unable to create new native thread”.
Possible Solution is to reduce the heap memory or increase the overall ram size
db.users.count()
db.users.remove({})
db.users.count()
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
You can also use Postman App for Windows, Linux or OSX. It is a complete web app & service test environment that involve all the request methods. You can find the latest version here.
The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.
Need some adjusts but should work for Express v4. Including those routes added with .use()
.
function listRoutes(routes, stack, parent){
parent = parent || '';
if(stack){
stack.forEach(function(r){
if (r.route && r.route.path){
var method = '';
for(method in r.route.methods){
if(r.route.methods[method]){
routes.push({method: method.toUpperCase(), path: parent + r.route.path});
}
}
} else if (r.handle && r.handle.name == 'router') {
const routerName = r.regexp.source.replace("^\\","").replace("\\/?(?=\\/|$)","");
return listRoutes(routes, r.handle.stack, parent + routerName);
}
});
return routes;
} else {
return listRoutes([], app._router.stack);
}
}
//Usage on app.js
const routes = listRoutes(); //array: ["method: path", "..."]
edit: code improvements
-> is for pointers to a class instance
. is for class instances
:: is for classnames - for example when using a static member
To do it by using f-string and with control of the number of trailing digits:
print(f'A number -> {my_number:>20.5f}')
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
I take it you are creating the TextBox in XAML?
In that case, you need to give the text box a name. Then in the code-behind you can then set the Background property using a variety of brushes. The simplest of which is the SolidColorBrush:
myTextBox.Background = new SolidColorBrush(Colors.White);
Your way can't work for two reasons.
You need to use set /p text=
for setting the variable with user input.
The other problem is the pipe.
A pipe starts two asynchronous cmd.exe instances and after finishing the job both instances are closed.
That's the cause why it seems that the variables are not set, but a small example shows that they are set but the result is lost later.
set myVar=origin
echo Hello | (set /p myVar= & set myVar)
set myVar
Outputs
Hello
origin
Alternatives: You can use the FOR loop to get values into variables or also temp files.
for /f "delims=" %%A in ('echo hello') do set "var=%%A"
echo %var%
or
>output.tmp echo Hello
>>output.tmp echo world
<output.tmp (
set /p line1=
set /p line2=
)
echo %line1%
echo %line2%
Alternative with a macro:
You can use a batch macro, this is a bit like the bash equivalent
@echo off
REM *** Get version string
%$set% versionString="ver"
echo The version is %versionString[0]%
REM *** Get all drive letters
`%$set% driveLetters="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveLetters
The definition of the macro can be found at
SO:Assign output of a program to a variable using a MS batch file
If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient
and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.
Post as JSON:
var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);
or URL-encoded:
var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);
Both examples above return an HttpResponseMessage
, but Flurl includes extension methods for returning other things if you just want to cut to the chase:
T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();
Flurl is available on NuGet:
PM> Install-Package Flurl.Http
If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:
'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
'***App Window Constants***
Public Const WIN_NORMAL = 1 'Open Normal
Public Const WIN_MAX = 3 'Open Maximized
Public Const WIN_MIN = 2 'Open Minimized
'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&
'***************Usage Examples***********************
'Open a folder: ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app: ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL: ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
' ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
' ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************
Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
'First try ShellExecute
lRet = apiShellExecute(hWndAccessApp, vbNullString, _
stFile, vbNullString, vbNullString, lShowHow)
If lRet > ERROR_SUCCESS Then
stRet = vbNullString
lRet = -1
Else
Select Case lRet
Case ERROR_NO_ASSOC:
'Try the OpenWith dialog
varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
& stFile, WIN_NORMAL)
lRet = (varTaskID <> 0)
Case ERROR_OUT_OF_MEM:
stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
Case ERROR_FILE_NOT_FOUND:
stRet = "Error: File not found. Couldn't Execute!"
Case ERROR_PATH_NOT_FOUND:
stRet = "Error: Path not found. Couldn't Execute!"
Case ERROR_BAD_FORMAT:
stRet = "Error: Bad File Format. Couldn't Execute!"
Case Else:
End Select
End If
fHandleFile = lRet & _
IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********
Just put this into a separate module and call fHandleFile() with the right parameters.
Testers need to focus on the testing pyramid. You will want to understand unit tests, integration tests, and end to end tests. Each of these can be performed both with black box and white box testing. Start small and work your way up learning the different types and when to use each. remember you cant always test everything.
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
System.out.println(Name + " " + Income);
Is that what you mean? That will put a space between the name and the income?
I faced same issue and I resolved this by
changing gradle version of project-label .gradle file to Latest
classpath 'com.android.tools.build:gradle:3.2.1'
and add these checks on app label .gradle file
packagingOptions{
doNotStrip '*/mips/*.so'
doNotStrip '*/mips64/*.so'
}
Hope This will help.
The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,
Open with
HTML (web forms) editor
Set as default
OK
buttonOnce you have done that, all you need to do is click on design
or split
view as shown below:
For example, here's a table that has a primary key but is not AUTO_INCREMENT
:
mysql> CREATE TABLE foo (
id INT NOT NULL,
PRIMARY KEY (id)
);
mysql> INSERT INTO foo VALUES (1), (2), (5);
You can MODIFY
the column to redefine it with the AUTO_INCREMENT
option:
mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;
Verify this has taken effect:
mysql> SHOW CREATE TABLE foo;
Outputs:
CREATE TABLE foo (
`id` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The PRIMARY KEY
constraint is unaffected, and you don't need to mention in in the ALTER TABLE
statement.
Next you can test that an insert generates a new value:
mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax
mysql> SELECT * FROM foo;
Outputs:
+----+
| id |
+----+
| 1 |
| 2 |
| 5 |
| 6 |
+----+
4 rows in set (0.00 sec)
I tested this on MySQL 5.0.51 on Mac OS X.
I also tested with ENGINE=InnoDB
and a dependent table. Modifying the id
column definition does not interrupt referential integrity.
To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
Create a class which extends HttpServlet
and put @WebServlet
annotation on it containing the desired URL the servlet should listen on.
@WebServlet("/yourServletURL")
public class YourServlet extends HttpServlet {}
And just let <form action>
point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified the name
attribute of the HTML form input fields (<input>
, <select>
, <textarea>
and <button>
). This represents the HTTP request parameter name. Finally, you also need to make sure that the input fields of interest are enclosed inside the desired form and thus not outside.
Here are some examples of various HTML form input fields:
<form action="${pageContext.request.contextPath}/yourServletURL" method="post">
<p>Normal text field.
<input type="text" name="name" /></p>
<p>Secret text field.
<input type="password" name="pass" /></p>
<p>Single-selection radiobuttons.
<input type="radio" name="gender" value="M" /> Male
<input type="radio" name="gender" value="F" /> Female</p>
<p>Single-selection checkbox.
<input type="checkbox" name="agree" /> Agree?</p>
<p>Multi-selection checkboxes.
<input type="checkbox" name="role" value="USER" /> User
<input type="checkbox" name="role" value="ADMIN" /> Admin</p>
<p>Single-selection dropdown.
<select name="countryCode">
<option value="NL">Netherlands</option>
<option value="US">United States</option>
</select></p>
<p>Multi-selection listbox.
<select name="animalId" multiple="true" size="2">
<option value="1">Cat</option>
<option value="2">Dog</option>
</select></p>
<p>Text area.
<textarea name="message"></textarea></p>
<p>Submit button.
<input type="submit" name="submit" value="submit" /></p>
</form>
Create a doPost()
method in your servlet which grabs the submitted input values as request parameters keyed by the input field's name
(not id
!). You can use request.getParameter()
to get submitted value from single-value fields and request.getParameterValues()
to get submitted values from multi-value fields.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String gender = request.getParameter("gender");
boolean agree = request.getParameter("agree") != null;
String[] roles = request.getParameterValues("role");
String countryCode = request.getParameter("countryCode");
String[] animalIds = request.getParameterValues("animalId");
String message = request.getParameter("message");
boolean submitButtonPressed = request.getParameter("submit") != null;
// ...
}
Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.
User user = new User(name, pass, roles);
userDAO.save(user);
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,''
Notice the column Running, obviously 1 means that it is currently running, and [Current Step]. This returns job_id to you, so you'll need to look these up, e.g.:
SELECT top 100 *
FROM msdb..sysjobs
WHERE job_id IN (0x9DAD1B38EB345D449EAFA5C5BFDC0E45, 0xC00A0A67D109B14897DD3DFD25A50B80, 0xC92C66C66E391345AE7E731BFA68C668)
I think to work with all systems use "ntpath" instead of "os.path". Today, it works well with Windows, Linux and Mac OSX.
import ntpath
import os
dirname = ntpath.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')
On the solution explorer, right click on the project title and select the 'Properties' on the context menu to open the 'Project Property' form. In the 'Application' tab, on the 'Resources' group box there is a entry field where you can select the icon file you want for your application.
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
Well, your solution almost works. There are a few things to take into account to keep it simple:
Cancel the default navigation only for specific URLs you know a download will occur, or the user won't be able to navigate anywhere. This means you musn't change your website download URLs.
DownloadFileAsync
doesn't know the name reported by the server in the Content-Disposition
header so you have to specify one, or compute one from the original URL if that's possible. You cannot just specify the folder and expect the file name to be retrieved automatically.
You have to handle download server errors from the DownloadCompleted
callback because the web browser control won't do it for you anymore.
Sample piece of code, that will download into the directory specified in textBox1
, but with a random file name, and without any additional error handling:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
/* change this to match your URL. For example, if the URL always is something like "getfile.php?file=xxx", try e.Url.ToString().Contains("getfile.php?") */
if (e.Url.ToString().EndsWith(".zip")) {
e.Cancel = true;
string filePath = Path.Combine(textBox1.Text, Path.GetRandomFileName());
var client = new WebClient();
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadFileAsync(e.Url, filePath);
}
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
MessageBox.Show("File downloaded");
}
This solution should work but can be broken very easily. Try to consider some web service listing the available files for download and make a custom UI for it. It'll be simpler and you will control the whole process.
I found possible answer. You have core-js version 3.0, and this version doesn't have separate folders for ES6 and ES7; that's why the application cannot find correct paths.
To resolve this error, you can downgrade the core-js version to 2.5.7. This version produces correct catalogs structure, with separate ES6 and ES7 folders.
To downgrade the version, simply run:
npm i -S [email protected]
In my case, with Angular, this works ok.
With the newer Web Api 2 it has become easier to have multiple get methods.
If the parameter passed to the GET
methods are different enough for the attribute routing system to distinguish their types as is the case with int
s and Guid
s you can specify the expected type in the [Route...]
attribute
For example -
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
// GET api/values/7
[Route("{id:int}")]
public string Get(int id)
{
return $"You entered an int - {id}";
}
// GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
[Route("{id:Guid}")]
public string Get(Guid id)
{
return $"You entered a GUID - {id}";
}
}
For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/
Another options is to give the GET
methods different routes.
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
public string Get()
{
return "simple get";
}
[Route("geta")]
public string GetA()
{
return "A";
}
[Route("getb")]
public string GetB()
{
return "B";
}
}
See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/
This is an improved function:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
You can do it with AJAX !
For PUT
method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE
method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/
files.
To answer this myself I just thought of a component react uses that has the children
prop. The first thing that came to mind? How about a <div />
?
All you need to do is open vscode and create a new .tsx
file in a react project with @types/react
.
import React from 'react';
export default () => (
<div children={'test'} />
);
Hovering over the children
prop shows you the type. And what do you know -- Its type is ReactNode
(no need for ReactNode[]
).
Then if you click into the type definition it brings you straight to the definition of children
coming from DOMAttributes
interface.
// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
children?: ReactNode;
...
}
Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)
Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch
Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:
...
'elasticsearch': {
'handlers': ['console'],
'level': logging.WARNING,
},
...
Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.
GDB Dashboard
https://github.com/cyrus-and/gdb-dashboard
This GDB configuration uses the official GDB Python API to show us whatever we want whenever GDB stops after for example next
, much like TUI.
However I have found that this implementation is a more robust and configurable alternative to the built-in GDB TUI mode as explained at: gdb split view with code
For example, we can configure GDB Dashboard to show disassembly, source, registers and stack with:
dashboard -layout source assembly registers stack
Here is what it looks like if you enable all available views instead:
Related questions:
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start()
function as well; you can exit the loop with either break
, or use return
to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
Consider the limitations of the different Load*
methods. From the MSDN docs...
LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.
More information on Load Contexts can be found in the LoadFrom
docs.
For those of you developing on localhost follow these steps:
Information Property List
and add App Transport Security Settings
and assign it a Dictionary
TypeApp Transport Security Settings
entry and add NSExceptionAllowsInsecureHTTPLoads
of type Boolean
and set its value to YES
. NSExceptionAllowsInsecureHTTPLoads
entry and click the "Shift Row Right" option to make it a child of the above entry. NSExceptionAllowsInsecureHTTPLoads
entry and add Allow Arbitrary Loads
of type Boolean
and set its value to YES
Note: It should in the end look something like presented in the following picture
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
create a view for each subquery is the way to go. Got it working like a charm.
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
I couldn't figure why yet, but the createReadStream
/pipe
approach didn't work for me. I was trying to download a large CSV file (300MB+) and I got duplicated lines. It seemed a random issue. The final file size varied in each attempt to download it.
I ended up using another way, based on AWS JS SDK examples:
var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.getObject(params).
on('httpData', function(chunk) { file.write(chunk); }).
on('httpDone', function() { file.end(); }).
send();
This way, it worked like a charm.
something like:
DELIMITER //
CREATE PROCEDURE alluser()
BEGIN
SELECT *
FROM users;
END //
DELIMITER ;
than:
SHOW CREATE PROCEDURE alluser
gives result:
'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
SELECT *
FROM users;
END'
Extend Code for Show Selected Sheet(s) [ one or more sheets].
Sub Show_SelectSheet()
For Each xSheet In ThisWorkbook.Worksheets
For Each xSelectSheet In ActiveWindow.SelectedSheets
If xSheet.Name = xSelectSheet.Name Then
'=== Show Selected Sheet ===
GoTo xNext_SelectSheet
End If
Next xSelectSheet
xSheet.Visible = False
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub
Simple explanation about what a Index out of bound exception is:
Just think one train is there its compartments are D1,D2,D3. One passenger came to enter the train and he have the ticket for D4. now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.
Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0]
and array[1]
are existing. If we try to access array[3]
, it's not there actually, so an index out of bound exception will arise.
I want to add something on @Michael Laffargue's post:
jqXHR.done()
is faster!
jqXHR.success()
have some load time in callback and sometimes can overkill script. I find that on hard way before.
UPDATE:
Using jqXHR.done()
, jqXHR.fail()
and jqXHR.always()
you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:
/* Initialize some your AJAX function */
function call_ajax(attr){
var settings=$.extend({
call : 'users',
option : 'list'
}, attr );
return $.ajax({
type: "POST",
url: "//exapmple.com//ajax.php",
data: settings,
cache : false
});
}
/* .... Somewhere in your code ..... */
call_ajax({
/* ... */
id : 10,
option : 'edit_user'
change : {
name : 'John Doe'
}
/* ... */
}).done(function(data){
/* DO SOMETHING AWESOME */
});
preg_replace("/[[:blank:]]+/"," ",$input)
In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:
For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom"
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"
To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.
*Note that the bottom tag of the three is the same as the first tag in the first link path.
A full working example, could be :
<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">
In the above example, the image is centered by using the Bootstrap auto margin on left and right.
Add position: relative
to .outside
. (https://developer.mozilla.org/en-US/docs/CSS/position)
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.
The "initial container" would be <body>
, but adding the above makes .outside
positioned.
Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml
file.
For PostgreSQL 9.1 this would be:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<name>Your project name.</name>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
</dependencies>
</project>
You can get the code for the dependency (as well as any other dependency) from maven's central repository
If you are using postgresql 9.2+:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<name>Your project name.</name>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.1</version>
</dependency>
</dependencies>
</project>
You can check the latest versions and dependency snippets from:
Install firebug and use console.log
instead of alert
. Then you will see the exact element your accessing.
Error from Git:
error: src refspec master does not match any.
Fixed with this step:
git commit -m "first commit"
Before I ran:
git add <files>
And after I ran:
git push -u origin master
For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...
Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).
When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.
At that point you'll get a tiny dialog to confirm with:
Java SDK: 1.7 (e.g.)
Build target: Android 6.0 (e.g.)
You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:
Android API 23 Platform (java version "1.7.0_67")
Alex made a great point on readability. Equivalently, a function is also interface enough to define the type(s) being returned and you also get meaningful variable names.
delegate void OpDelegate(int op);
Task<bool> GetDataTaskAsync(OpDelegate callback)
{
bool canGetData = true;
if (canGetData) callback(5);
return Task.FromResult(canGetData);
}
Callers provide a lambda (or a named function) and intellisense helps by copying the variable name(s) from the delegate.
int myOp;
bool result = await GetDataTaskAsync(op => myOp = op);
This particular approach is like a "Try" method where myOp
is set if the method result is true
. Otherwise, you don't care about myOp
.
You don't need CSS for this.
<img src="abc"/>
now with link:
<a href="#myLink"><img src="abc"/></a>
Or with jquery, later on, you can use the wrap property, see these questions answer:
Mature, simple to use and has lots of features if simple isn't enought: Nodemailer: https://github.com/andris9/nodemailer (note correct url!)
What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.
When should you use :
It depends on the situation.
Note : please do not use on db connection, for a detailed answer please refer to the answer of @Chad Grant
Here is a simple example of a Singleton
:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
You can also use Lazy<T>
to create your Singleton
.
See here for a more detailed example using Lazy<T>
If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));
Hexadecimal to decimal. Don't run it on online compilers, because it won't work.
#include<stdio.h>
void main()
{
unsigned int i;
scanf("%x",&i);
printf("%d",i);
}
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
To completely remove the style attribute of the voltaic_holder
span, do this:
$("#voltaic_holder").removeAttr("style");
To add an attribute, do this:
$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");
To remove only the top style, do this:
$("#voltaic_holder").css("top", "");