I had the same issue. But in my case it was due to my branch's name. The branch's name automatically set in my GitHub repo as main instead of master.
git pull origin master (did not work).
I confirmed in GitHub if the name of the branch was actually master and found the the actual name was main. so the commands below worked for me. git pull origin main
The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,
First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.
So we use that variable to invoke the function by adding parentheses () at the end.
One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().
Hey you can do this with java/com integration. By accessing WMI features you can get all the information.
I make a sample for you , and I hope this is helpful...
static void Main(string[] args)
{
var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };
DataTable table = new DataTable();
foreach (var col in cols)
table.Columns.Add(col);
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
foreach (var col in cols)
{
var results = from p in table.AsEnumerable()
select p[col];
Console.WriteLine("*************************");
foreach (var result in results)
{
Console.WriteLine(result);
}
}
Console.ReadLine();
}
Works for me, has nothing to do with PHP 5.3. Just like many such options it cannot be overriden via ini_set()
when safe_mode is enabled. Check your updated php.ini
(and better yet: change the memory_limit there too).
As of React Native 0.4.2, View components have an onLayout
prop. Pass in a function that takes an event object. The event's nativeEvent
contains the view's layout.
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
}} />
The onLayout
handler will also be invoked whenever the view is resized.
The main caveat is that the onLayout
handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
You should only need to do a single join:
SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
this is a common question here.
Here's a link to a similar question. You can see my answer there. Why POST['submit'] is set when I reload?
The basic answer is to look into post/redirect/get, but since it is easier to see by example, just check the link above.
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
Try the :lt selector: http://docs.jquery.com/Selectors/lt#index
$('a:lt(20)');
a little late but i hope it helps to someone else.
Make sure to put the @Service on the implementation class for the service
@Service
public class ServiceNameImpl implements ServiceName {
@Override
public void method(ObjectType paramName) {
//CODE
}
}
That's how i fixed the error.
Some applications like skype uses wamp's default port:80 so you have to find out which application is accessing this port you can easily find it by using TCP View. End the service accessing this port and restart wamp server. Now it will work.
my sample code
wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen
I know that due to this ugly anonymous inner class usage of TransactionTemplate
doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.
In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional
on the test methods. Why? Because @Transactional
may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate
can be perfect for controlling transaction boundries when we want that control.
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
First make sure you have the runat="server"
attribute in your textarea
tag like this
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
Then you can access the content via:
string body = TextArea1.value;
This link shows how to list all the active properties: http://skillshared.blogspot.co.uk/2012/11/how-to-list-down-all-maven-available.html
In summary, add the following plugin definition to your POM, then run mvn install
:
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<echoproperties />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
The principle behind Data Transfer Object is to create new Data Objects that only include the necessary properties you need for a specific data transaction.
Benefits include:
Make data transfer more secure Reduce transfer size if you remove all unnecessary data.
Read More: https://www.codenerd.co.za/what-is-data-transfer-objects
Do you know sprintf
? It's basically the same thing with fprintf
. The first argument is the destination (the file in the case of fprintf
i.e. stderr
), the second argument is the format string, and the rest are the arguments as usual.
I also recommend this printf
(and family) reference.
I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.
ticks: {
callback: function(label, index, labels) {
return label/1000+'k';
}
}
More in details
var options = {
scales: {
yAxes: [
{
ticks: {
callback: function(label, index, labels) {
return label/1000+'k';
}
},
scaleLabel: {
display: true,
labelString: '1k = 1000'
}
}
]
}
}
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
How about just doing some linq queries against your dictionary, and then binding your graph to the results of those?...
var under = colStates.Where(c => (decimal)c.Value / (decimal)totalCount < .05M);
var over = colStates.Where(c => (decimal)c.Value / (decimal)totalCount >= .05M);
var newColStates = over.Union(new Dictionary<string, int>() { { "Other", under.Sum(c => c.Value) } });
foreach (var item in newColStates)
{
Console.WriteLine("{0}:{1}", item.Key, item.Value);
}
You can use GROUP BY SalesOrderID
. The difference is, with GROUP BY you can only have the aggregated values for the columns that are not included in GROUP BY.
In contrast, using windowed aggregate functions instead of GROUP BY, you can retrieve both aggregated and non-aggregated values. That is, although you are not doing that in your example query, you could retrieve both individual OrderQty
values and their sums, counts, averages etc. over groups of same SalesOrderID
s.
Here's a practical example of why windowed aggregates are great. Suppose you need to calculate what percent of a total every value is. Without windowed aggregates you'd have to first derive a list of aggregated values and then join it back to the original rowset, i.e. like this:
SELECT
orig.[Partition],
orig.Value,
orig.Value * 100.0 / agg.TotalValue AS ValuePercent
FROM OriginalRowset orig
INNER JOIN (
SELECT
[Partition],
SUM(Value) AS TotalValue
FROM OriginalRowset
GROUP BY [Partition]
) agg ON orig.[Partition] = agg.[Partition]
Now look how you can do the same with a windowed aggregate:
SELECT
[Partition],
Value,
Value * 100.0 / SUM(Value) OVER (PARTITION BY [Partition]) AS ValuePercent
FROM OriginalRowset orig
Much easier and cleaner, isn't it?
I always use Desktop first, mobile first doesn't have highest priority does it? IE< 8 will show mobile css..
normal css here:
@media screen and (max-width: 768px) {}
@media screen and (max-width: 480px) {}
sometimes some custom sizes. I don't like bootstrap etc.
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
Check this out : readdir()
This bit of code should list all entries in a certain directory:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
Edit: miah's solution is much more elegant than mine, you should use his solution instead.
As others have pointed out this is because MySQL is installed but the service isn't running. There are many ways to start the MySQL service and what worked for me is the below.
To start the service:
My env:
Mac Yosemite 10.10.3
Installed Package: /Volumes/mysql-advanced-5.6.24-osx10.8-x86_64
In your css add a class:
.fa-clickable {
cursor:pointer;
outline:none;
}
Then add the class to the clickable fontawesome icons (also an id so you can differentiate the clicks):
<i class="fa fa-dribbble fa-4x fa-clickable" id="epd-dribble"></i>
<i class="fa fa-behance-square fa-4x fa-clickable" id="epd-behance"></i>
<i class="fa fa-linkedin-square fa-4x fa-clickable" id="epd-linkedin"></i>
<i class="fa fa-twitter-square fa-4x fa-clickable" id="epd-twitter"></i>
<i class="fa fa-facebook-square fa-4x fa-clickable" id="epd-facebook"></i>
Then add a handler in your jQuery
$(document).on("click", "i", function(){
switch (this.id) {
case "epd-dribble":
// do stuff
break;
// add additional cases
}
});
At this point, why not mentioning python-audio-tools
:
It's the best solution I found.
(I needed to install libasound2-dev
, on Raspbian)
Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay
#!/usr/bin/python
import os
import re
import audiotools.player
START = 0
INDEX = 0
PATH = '/path/to/your/mp3/folder'
class TracklistPlayer:
def __init__(self,
tr_list,
audio_output=audiotools.player.open_output('ALSA'),
replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
skip=False):
if skip:
return
self.track_index = INDEX + START - 1
if self.track_index < -1:
print('--> [track index was negative]')
self.track_index = self.track_index + len(tr_list)
self.track_list = tr_list
self.player = audiotools.player.Player(
audio_output,
replay_gain,
self.play_track)
self.play_track(True, False)
def play_track(self, forward=True, not_1st_track=True):
try:
if forward:
self.track_index += 1
else:
self.track_index -= 1
current_track = self.track_list[self.track_index]
audio_file = audiotools.open(current_track)
self.player.open(audio_file)
self.player.play()
print('--> index: ' + str(self.track_index))
print('--> PLAYING: ' + audio_file.filename)
if not_1st_track:
pass # here I needed to do something :)
if forward:
pass # ... and also here
except IndexError:
print('\n--> playing finished\n')
def toggle_play_pause(self):
self.player.toggle_play_pause()
def stop(self):
self.player.stop()
def close(self):
self.player.stop()
self.player.close()
def natural_key(el):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]
def natural_cmp(a, b):
return cmp(natural_key(a), natural_key(b))
if __name__ == "__main__":
print('--> path: ' + PATH)
# remove hidden files (i.e. ".thumb")
raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))
# mp3 and wav files only list
file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)
# natural order sorting
file_list.sort(key=natural_key, reverse=False)
track_list = []
for f in file_list:
track_list.append(os.path.join(PATH, f))
TracklistPlayer(track_list)
You can use System.device.Location
:
System.device.Location.GeoCoordinate gc = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt1,
Longitude = yourLongitudePt1
};
System.device.Location.GeoCoordinate gc2 = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt2,
Longitude = yourLongitudePt2
};
Double distance = gc2.getDistanceTo(gc);
good luck
SimpleDateFormat has a constructor which takes the locale, have you tried that?
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Something like
new SimpleDateFormat("your-pattern-here", Locale.getDefault());
The NVARCHAR2 datatype was introduced by Oracle for databases that want to use Unicode for some columns while keeping another character set for the rest of the database (which uses VARCHAR2). The NVARCHAR2 is a Unicode-only datatype.
One reason you may want to use NVARCHAR2 might be that your DB uses a non-Unicode character set and you still want to be able to store Unicode data for some columns without changing the primary character set. Another reason might be that you want to use two Unicode character set (AL32UTF8 for data that comes mostly from western Europe, AL16UTF16 for data that comes mostly from Asia for example) because different character sets won't store the same data equally efficiently.
Both columns in your example (Unicode VARCHAR2(10 CHAR)
and NVARCHAR2(10)
) would be able to store the same data, however the byte storage will be different. Some strings may be stored more efficiently in one or the other.
Note also that some features won't work with NVARCHAR2, see this SO question:
For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.
Here is a simple shell script with no dependencies that will convert one or more SVN repositories to git and push them to GitHub.
https://gist.github.com/NathanSweet/7327535
In about 30 lines of script it: clones using git SVN, creates a .gitignore file from SVN::ignore properties, pushes into a bare git repository, renames SVN trunk to master, converts SVN tags to git tags, and pushes it to GitHub while preserving the tags.
I went thru a lot of pain to move a dozen SVN repositories from Google Code to GitHub. It didn't help that I used Windows. Ruby was all kinds of broken on my old Debian box and getting it working on Windows was a joke. Other solutions failed to work with Cygwin paths. Even once I got something working, I couldn't figure out how to get the tags to show up on GitHub (the secret is --follow-tags).
In the end I cobbled together two short and simple scripts, linked above, and it works great. The solution does not need to be any more complicated than that!
You need to use the Thread.sleep()
call.
More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
One aspect of the Map that is not given much press here is lookup. According to the spec:
A Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Map objects specification is only intended to describe the required observable semantics of Map objects. It is not intended to be a viable implementation model.
For collections that have a huge number of items and require item lookups, this is a huge performance boost.
TL;DR - Object lookup is not specified, so it can be on order of the number of elements in the object, i.e., O(n). Map lookup must use a hash table or similar, so Map lookup is the same regardless of Map size, i.e. O(1).
Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim()
on a not existing object would throw an exception:
function isEmpty(value) {
return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}
Usage:
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false
This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.
You will crop your images with a few lines of code.
1 - Add the dependecies into buid.gradle (Module: app)
compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
2 - Add the permissions into AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3 - Add CropImageActivity into AndroidManifest.xml
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="@style/Base.Theme.AppCompat"/>
4 - Start the activity with one of the cases below, depending on your requirements.
// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);
// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);
5 - Get the result in onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.
In Sublime Text (confirmed in both v2.x and v3.x) there is a menu command:
View -> Syntax -> Open all with current extension as ...
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.
the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".
the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!
but did anyone think to "localhost" on any apache server for example www.apachefriends.org?
you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".
<?php
for($i=1;$i<50000;$i++){
print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>
<?php
?>
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause
Now if you pay attention closely ...
the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!
here i got :
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/void.php
Document Length: 0 bytes
Concurrency Level: 1
Time taken for tests: 11.219 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 2150000 bytes
HTML transferred: 0 bytes
Requests per second: 891.34 [#/sec] (mean)
Time per request: 1.122 [ms] (mean)
Time per request: 1.122 [ms] (mean, across all concurrent requests)
Transfer rate: 187.15 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 0 1 0.9 1 17
Waiting: 0 1 0.9 1 17
Total: 0 1 0.9 1 17
Percentage of the requests served within a certain time (ms)
50% 1
66% 1
75% 1
80% 1
90% 1
95% 2
98% 2
99% 3
100% 17 (longest request)
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/bench.php
Document Length: 1799964 bytes
Concurrency Level: 1
Time taken for tests: 177.006 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 18001600000 bytes
HTML transferred: 17999640000 bytes
Requests per second: 56.50 [#/sec] (mean)
Time per request: 17.701 [ms] (mean)
Time per request: 17.701 [ms] (mean, across all concurrent requests)
Transfer rate: 99317.00 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 12 17 3.2 17 90
Waiting: 0 1 1.1 1 26
Total: 13 18 3.2 18 90
Percentage of the requests served within a certain time (ms)
50% 18
66% 19
75% 19
80% 20
90% 21
95% 22
98% 23
99% 26
100% 90 (longest request)
c:\xampp\htdocs\bench>pause
Press any key to continue . . .
90-17= 73 the result i expect !
The TextBox
control has a Text
property that you can use to get (or set) the text of the textbox.
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
unfortunately this is not supported in the builtin tools in visual studio. however, you can create your own data provider using mysql connector but still have to integrate it from code
#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}
fiddle : http://jsfiddle.net/sKqZJ/
or
#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}
fiddle : http://jsfiddle.net/sKqZJ/1/
or
#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/2/
or
#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}
fiddle : http://jsfiddle.net/sKqZJ/3/
reference : The Difference Between CSS Margins and Padding
I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.
I have a table of sensor data (1 minute data from about 30 sensors)
SensorReadings->(timestamp,value,idSensor)
and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:
Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:
SELECT idSensor,Description,tvLastUpdate,tvLastValue
FROM Sensors
I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.
I want to write a program that (...) creates the directory and a (...) file inside of it
because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.
void rek_mkdir(char *path) {
char *sep = strrchr(path, '/');
if(sep != NULL) {
*sep = 0;
rek_mkdir(path);
*sep = '/';
}
if(mkdir(path, 0777) && errno != EEXIST)
printf("error while trying to create '%s'\n%m\n", path);
}
FILE *fopen_mkdir(char *path, char *mode) {
char *sep = strrchr(path, '/');
if(sep) {
char *path0 = strdup(path);
path0[ sep - path ] = 0;
rek_mkdir(path0);
free(path0);
}
return fopen(path,mode);
}
Date().toLocaleString()
returns this: 7/31/2018, 12:58:03 PM
Pretty close - just drop the comma and the seconds:
new Date().toLocaleString().replace(",","").replace(/:.. /," ");
Results: 7/31/2018 12:58 PM
Try something like
SELECT
CASE var
WHEN xyz THEN col1
WHEN zyx THEN col2
ELSE col7
END AS col1,
...
In other words, use a conditional expression to select the value, then rename the column.
Alternately, you could build up some sort of dynamic SQL hack to share the query tail; I've done this with iBatis before.
I found a pretty well put explanation of atomic and non-atomic properties here. Here's some relevant text from the same:
'atomic' means it cannot be broken down. In OS/programming terms an atomic function call is one that cannot be interrupted - the entire function must be executed, and not swapped out of the CPU by the OS's usual context switching until it's complete. Just in case you didn't know: since the CPU can only do one thing at a time, the OS rotates access to the CPU to all running processes in little time-slices, to give the illusion of multitasking. The CPU scheduler can (and does) interrupt a process at any point in its execution - even in mid function call. So for actions like updating shared counter variables where two processes could try to update the variable at the same time, they must be executed 'atomically', i.e., each update action has to finish in its entirety before any other process can be swapped onto the CPU.
So I'd be guessing that atomic in this case means the attribute reader methods cannot be interrupted - in effect meaning that the variable(s) being read by the method cannot change their value half way through because some other thread/call/function gets swapped onto the CPU.
Because the atomic
variables can not be interrupted, the value contained by them at any point is (thread-lock) guaranteed to be uncorrupted, although, ensuring this thread lock makes access to them slower. non-atomic
variables, on the other hand, make no such guarantee but do offer the luxury of quicker access. To sum it up, go with non-atomic
when you know your variables won't be accessed by multiple threads simultaneously and speed things up.
Here is to share something I found on __import__
and importlib
while trying to solve this problem.
I am using Python 3.7.3.
When I try to get to the class d
in module a.b.c
,
mod = __import__('a.b.c')
The mod
variable refer to the top namespace a
.
So to get to the class d
, I need to
mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d
If we try to do
mod = __import__('a.b.c')
d = getattr(mod, 'd')
we are actually trying to look for a.d
.
When using importlib
, I suppose the library has done the recursive getattr
for us. So, when we use importlib.import_module
, we actually get a handle on the deepest module.
mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d
To store the password (PY3):
import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'
hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()
An expression like
dosomething1 && dosomething2 && dosomething3
will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":
cat nosuchfile && echo "done"
echo $?
1
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.
Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Have you tried using jQuery's ajax request? As of version 1.3 jQuery supports certain types of cross domain ajax requests.
Quoting from the reference above:
Note: All remote (not on the same domain) requests should be specified as GET when 'script' or 'jsonp' is the dataType (because it loads script using a DOM script tag). Ajax options that require an XMLHttpRequest object are not available for these requests. The complete and success functions are called on completion, but do not receive an XHR object; the beforeSend and dataFilter functions are not called.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.
You need to give the user table an alias the second time you join to it
e.g.
SELECT article . * , section.title, category.title, user.name, u2.name
FROM article
INNER JOIN section ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user ON article.author_id = user.id
LEFT JOIN user u2 ON article.modified_by = u2.id
WHERE article.id = '1'
Leaving aside the fact that they are private
, since a
and b
are members of A
, they are meant to be initialized by A
's constructors, not by some other class's constructors (derived or not).
Try:
class A
{
int a, b;
protected: // or public:
A(int a, int b): a(a), b(b) {}
};
class B : public A
{
B() : A(0, 0) {}
};
when you set the density to 96, doesn't it look good?
when i tried it i saw that saving as jpg resulted with better quality, but larger file size
The following points help you in deciding in which situations one should use Comparable and in which Comparator:
1) Code Availabilty
2) Single Versus Multiple Sorting Criteria
3) Arays.sort() and Collection.sort()
4) As keys in SortedMap and SortedSet
5) More Number of classes Versus flexibility
6) Interclass comparisions
7) Natural Order
For more detailed article you can refer When to use comparable and when to use comparator
Type
git push
from the command line inside the repository directory
I say almost the same as ratkok but if you have a embedded twist to the unit tests then...
Unity - Highly recommended framework for unit testing C code.
#include <unity.h>
void test_true_should_be_true(void)
{
TEST_ASSERT_TRUE(true);
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(test_true_should_be_true);
return UNITY_END();
}
The examples in the book that is mentioned in this thread TDD for embedded C are written using Unity (and CppUTest).
While the answers explaining the exact differences are fine, I want to show how the relational algebra is transformed to SQL and what the actual value of the 3 concepts is.
The key concept in your question is the idea of a join. To understand a join you need to understand a Cartesian Product (the example is based on SQL where the equivalent is called a cross join as onedaywhen points out);
This isn't very useful in practice. Consider this example.
Product(PName, Price)
====================
Laptop, 1500
Car, 20000
Airplane, 3000000
Component(PName, CName, Cost)
=============================
Laptop, CPU, 500
Laptop, hdd, 300
Laptop, case, 700
Car, wheels, 1000
The Cartesian product Product x Component will be - bellow or sql fiddle. You can see there are 12 rows = 3 x 4. Obviously, rows like "Laptop" with "wheels" have no meaning, this is why in practice the Cartesian product is rarely used.
| PNAME | PRICE | CNAME | COST |
--------------------------------------
| Laptop | 1500 | CPU | 500 |
| Laptop | 1500 | hdd | 300 |
| Laptop | 1500 | case | 700 |
| Laptop | 1500 | wheels | 1000 |
| Car | 20000 | CPU | 500 |
| Car | 20000 | hdd | 300 |
| Car | 20000 | case | 700 |
| Car | 20000 | wheels | 1000 |
| Airplane | 3000000 | CPU | 500 |
| Airplane | 3000000 | hdd | 300 |
| Airplane | 3000000 | case | 700 |
| Airplane | 3000000 | wheels | 1000 |
JOINs are here to add more value to these products. What we really want is to "join" the product with its associated components, because each component belongs to a product. The way to do this is with a join:
Product JOIN Component ON Pname
The associated SQL query would be like this (you can play with all the examples here)
SELECT *
FROM Product
JOIN Component
ON Product.Pname = Component.Pname
and the result:
| PNAME | PRICE | CNAME | COST |
----------------------------------
| Laptop | 1500 | CPU | 500 |
| Laptop | 1500 | hdd | 300 |
| Laptop | 1500 | case | 700 |
| Car | 20000 | wheels | 1000 |
Notice that the result has only 4 rows, because the Laptop has 3 components, the Car has 1 and the Airplane none. This is much more useful.
Getting back to your questions, all the joins you ask about are variations of the JOIN I just showed:
Natural Join = the join (the ON clause) is made on all columns with the same name; it removes duplicate columns from the result, as opposed to all other joins; most DBMS (database systems created by various vendors such as Microsoft's SQL Server, Oracle's MySQL etc. ) don't even bother supporting this, it is just bad practice (or purposely chose not to implement it). Imagine that a developer comes and changes the name of the second column in Product from Price to Cost. Then all the natural joins would be done on PName AND on Cost, resulting in 0 rows since no numbers match.
Theta Join = this is the general join everybody uses because it allows you to specify the condition (the ON clause in SQL). You can join on pretty much any condition you like, for example on Products that have the first 2 letters similar, or that have a different price. In practice, this is rarely the case - in 95% of the cases you will join on an equality condition, which leads us to:
Equi Join = the most common one used in practice. The example above is an equi join. Databases are optimized for this type of joins! The oposite of an equi join is a non-equi join, i.e. when you join on a condition other than "=". Databases are not optimized for this! Both of them are subsets of the general theta join. The natural join is also a theta join but the condition (the theta) is implicit.
Source of information: university + certified SQL Server developer + recently completed the MOO "Introduction to databases" from Stanford so I dare say I have relational algebra fresh in mind.
There is also one more solution for that kind of problem, which is rather rare, I think, and you may experience it, if you are using vim on OS X Sierra. Actually, it's a problem with Esc button — not with vim. For example, I wasnt able to exit fullscreen video on youtube using Esc, but I lived with that for a few months until I had experienced the same problem with vim.
I found this solution. If you are lazy enough to follow external link, switching off Siri and killing the process in Activity Monitor helped.
If you are using forms authentication you could try the code below:
<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/">
</forms>
</authentication>
A very good reason for using IDEs is that they are the accepted way of producing modern software. If you do not use one, then you likely use "old fashioned" stuff like vi and emacs. This can lead people to conclude - possibly wrongly - that you are stuck in your ways and unable to adapt to new ways of working. In an industry such as software development - where ideas can be out of date in mere months - this is a dangerous state to get into. It could seriously damage your future job prospects...
I guess you could try
table tr td { color: red; }
table tr td table tr td { color: black; }
Or
body table tr td { color: red; }
where 'body' is a selector for your table's parent
But classes are most likely the right way to go here.
Incrementing / Decrementing Operators
++
increment operator
--
decrement operator
Example Name Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
These can go before or after the variable.
If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.
For example:
$apples = 10;
for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}
In the case above ++$i
is used, since it is faster. $i++
would have the same results.
Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.
However, you must use $apples--
, since first, you want to display the current number of apples, and then you want to subtract one from it.
You can also increment letters in PHP:
$i = "a";
while ($i < "c") {
echo $i++;
}
Once z
is reached aa
is next, and so on.
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Stack Overflow Posts:
Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.
I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug
error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...
Union Operation is combined result of the Vertical Aggregate of the rows, Union Operation is combined result of the Horizontal Aggregate of the Columns.
Considering it hasn't been released yet, I'm assuming this is a question for ahead-of-time or you have a developer's build. As Benjamin mentioned, MAMP is the easiest way. However, if you want a native install, the process should be like 10.5. PHP comes installed on OS X by default (not always activated for some), just download the 32-bit version of MySQL, start Apache, and you should be good to go. You may have to tweak Apache for PHP or MySQL, depending on what builds are present. I didn't have to tweak anything to have it working.
First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"
{{ word|striptags('<b>,<a>,<pre>')|raw }}
if you want to allow multiple tags
There are basically 4 techniques for this task, all of them standard SQL.
NOT EXISTS
Often fastest in Postgres.
SELECT ip
FROM login_log l
WHERE NOT EXISTS (
SELECT -- SELECT list mostly irrelevant; can just be empty in Postgres
FROM ip_location
WHERE ip = l.ip
);
Also consider:
LEFT JOIN / IS NULL
Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS
.
SELECT l.ip
FROM login_log l
LEFT JOIN ip_location i USING (ip) -- short for: ON i.ip = l.ip
WHERE i.ip IS NULL;
EXCEPT
Short. Not as easily integrated in more complex queries.
SELECT ip
FROM login_log
EXCEPT ALL -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM ip_location;
Note that (per documentation):
duplicates are eliminated unless
EXCEPT ALL
is used.
Typically, you'll want the ALL
keyword. If you don't care, still use it because it makes the query faster.
NOT IN
Only good without NULL
values or if you know to handle NULL
properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.
SELECT ip
FROM login_log
WHERE ip NOT IN (
SELECT DISTINCT ip -- DISTINCT is optional
FROM ip_location
);
NOT IN
carries a "trap" for NULL
values on either side:
Similar question on dba.SE targeted at MySQL:
$( this ).find( 'li.target' ).css("border", "3px double red");
or
$( this ).children( 'li.target' ).css("border", "3px double red");
Use children
for immediate descendants, or find
for deeper elements.
I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach
xAxes = {
type: "time",
time: {
displayFormats: {
hour: "hA"
}
},
display: true,
ticks: {
reverse: true
},
gridLines: {display: false}
}
// if more than two days between start and end of data, set format to show date, not hrs
if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000*60*60*24*2)) {
xAxes.time.displayFormats.hour = "MMM D";
}
FireFox + FireBug is very good for this purpose. For IE there's a developer toolbar which I've never used and intend to use so I cannot provide much feedback.
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction
python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py
, then following way you can do it:
Define import statement in Example3.py
- file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py
you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
You can do this in one line
let arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" },_x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
const mergeById = (a1, a2) =>_x000D_
a1.map(itm => ({_x000D_
...a2.find((item) => (item.id === itm.id) && item),_x000D_
...itm_x000D_
}));_x000D_
_x000D_
console.log(mergeById(arr1, arr2));
_x000D_
The final array will only contain id's that match from both arrays
I had this error when running an old python script developped with Python 2.6.4
When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.
I don't have enough reputation to comment answer of @user1615903, so add this as answer: "git remote remove" does not exist, should use "rm" instead of "remove". So the correct way is:
git remote rm origin
As a quick and dirty solution leveraging existing infrastructure, you can wrap your uglyPrintedMap
into a java.util.HashMap
, then use toString()
.
uglyPrintedMap.toString(); // ugly
System.out.println( uglyPrintedMap ); // prints in an ugly manner
new HashMap<Object, Object>(jobDataMap).toString(); // pretty
System.out.println( new HashMap<Object, Object>(uglyPrintedMap) ); // prints in a pretty manner
As with @kidbrax's answer, you can use the +
to add days. To get this to work I had to explicitly declare my cell data as being a date:
A1: =DATE(2014, 03, 28)
A2: =A1+1
Value of A2 is now 29th March 2014
I think you are looking for std::any_of
, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)
int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
return i == val;
});
If you want to know where the element is, std::find
will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}
The problem lies in https.conf file!
# Virtual hosts
# Include conf/extra/httpd-vhosts.conf
The error occurs when hash(#) is removed or messed around with. These two lines should appear as shown above.
Had to put the url in quotes for it work
npm install "https://github.com/shakacode/bootstrap-loader.git#v1" --save
You can get the first column as a Series by following code:
x[x.columns[0]]
If you use the command
time /T
that will print the time. (without the /T, it will try to set the time)
date /T
is similar for the date.
If cmd's Command Extensions are enabled (they are enabled by default, but in this question they appear to be disabled), then the environment variables %DATE%
and %TIME%
will expand to the current date and time each time they are expanded. The format used is the same as the DATE
and TIME
commands.
To see the other dynamic environment variables that exist when Command Extensions are enabled, run set /?
.
@user3168844: try the below code:
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
Inverse of a matrix using python and numpy:
>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5, 1.5],
[ 2. , -1. ]])
Not all matrices can be inverted. For example singular matrices are not Invertable:
>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)
LinAlgError: Singular matrix
Solution to singular matrix problem:
try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.
Intuition for why matrix inversion can't always be done; like in singular matrices:
Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.
If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.
Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."
A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.
If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.
Source:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv
The data URI format is:
data:<headers>;<encoding>,<data>
So, you need only append your data to the "data:image/jpeg;," string:
var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format
window.open('data:image/jpeg;,'+your_binary_data);
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
FYI
If you are using hbm files to define the O/R mapping.
Notice that:
In Hibernate 5, the param name for the sequence name has been changed.
The following setting worked fine in Hibernate 4:
<generator class="sequence">
<param name="sequence">xxxxxx_seq</param>
</generator>
But in Hibernate 5, the same mapping setting file will cause a "hibernate_sequence doesn't exist" error.
To fix this error, the param name must change to:
<generator class="sequence">
<param name="sequence_name">xxxxxx_seq</param>
</generator>
This problem wasted me 2, 3 hours.
And somehow, it looks like there are no document about it.
I have to read the source code of org.hibernate.id.enhanced.SequenceStyleGenerator to figure it out
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.
You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.
I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.
If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.
update(
{_id: 1, 'items.id': 2},
{'$set': {'items.$[]': update}},
{new: true})
Here is the doc about $[]
: https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[]
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {_x000D_
totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly()
in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.
Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.
Yes. It is done with a filter on the appender.
Here is the appender configuration I normally use, limited to only INFO level.
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="${HOMEDRIVE}\\PI.Logging\\PI.ECSignage.${COMPUTERNAME}.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="5MB" />
<rollingStyle value="Size" /> <!--A maximum number of backup files when rolling on date/time boundaries is not supported. -->
<staticLogFileName value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.
Just make sure you set cors values in elasticsearch.yml appropiate.
List<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList();
This one works.
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
If you have IIS Express (with Visual Studio):
To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.
See the steps and pictures at this code project.
IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.
From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.
You can use some functional programming approach, transforming data:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
Try this query:
SELECT cast(column_name as type) as col_identifier FROM tableName WHERE 1=1
Before comparing, the cast
function will convert varchar
type value to integer
type.
m1 = (y2 - y1) / (x2 - x1)
if perpendicular two lines:
m1*m2 = -1
then
m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)
y = m2*x + b //b is offset of new perpendicular line..
b is something if you want to pass it from a point you defined
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
Look in the Android SDK samples. There are several examples in the ApiDemos project:
/ApiDemos/res/drawable/
It will look something like this for a circle with a gradient fill:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF" android:angle="270"/> </shape>
The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.
Use
Z=XY[0]+XY[1]
Instead of
Z=XY(i,0)+XY(i,1)
This code simply worked for me
System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
This works in SQL Server:
SELECT * INTO tmpFerdeen FROM (
SELECT top 100 *
FROM Customers
UNION All
SELECT top 100 *
FROM CustomerEurope
UNION All
SELECT top 100 *
FROM CustomerAsia
UNION All
SELECT top 100 *
FROM CustomerAmericas
) as tmp
If the number is stored in a string (which it would be if typed by a user), you can use atoi()
to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}
Using unless
is fine for statements with single include?
clauses but, for example, when you need to check the inclusion of something in one Array
but not in another, the use of include?
with exclude?
is much friendlier.
if @players.include? && @spectators.exclude? do
....
end
But as dizzy42 says above, the use of exclude?
requires ActiveSupport
Stephen's answer is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:
decorated = [(tup[1], tup) for tup in data]
decorated.sort()
undecorated = [tup for second, tup in decorated]
Or, more tersely:
[b for a,b in sorted((tup[1], tup) for tup in data)]
As noted in the Python Sorting HowTo, this has been unnecessary since Python 2.4, when key functions became available.
date.setTime( date.getTime() + days * 86400000 );
First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...
Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)
This answer is not working since the urllib2
module has been split across several modules in Python 3.
You need to do
from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")
I personally use Cygwin, which puts the entire smörgåsbord of Linux utilities at my fingertip --- there's md5sum
and all the cryptographic digests supported by OpenSSL. Alternatively, you can also use a Windows distribution of OpenSSL (the "light" version is only a 1 MB installer).
You need to qualify the a
part of the selector too:
.button input, .button a {
//css stuff here
}
Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.
Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".
There is also list.append
from the rlist
(link to the documentation)
require(rlist)
LL <- list(a="Tom", b="Dick")
list.append(LL,d="Pam",f=c("Joe","Ann"))
It's very simple and efficient.
The image should be embedded in the message as an attachment like this:
--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png
base64 data
--boundary
And, the HTML part would reference the image like this:
<img src="cid:0123456789">
In some clients, src="sig.png" will work too.
You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.
Clients shouldn't block this image either as it isn't remote.
Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):
From
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"
This is a message with multiple parts in MIME format.
--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
test
--
[Picture of a Christmas Tree]
--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"
--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>test</p>
<p class="sig">-- <br><img src="cid:0123456789"></p>
</body>
</html>
--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64
R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7
--related_boundary--
--alternative_boundary--
You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.
Try this,
/**
* Draw the view into a bitmap.
*/
public static Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
... right now it happens only to the website I'm testing. I can't post it here because it's confidential.
Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use
--secure-protocol=TLSv1
. If this does not help check if you can access the site with openssl s_client -connect ...
(probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ...
.
Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.
The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.
Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?
The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.
There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.
I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.
Edit:
After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.
GMTL -
Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.
Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.
Eigen -
Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.
Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).
IMSL -
Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.
Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.
NT2 -
Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.
Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.
LAPACK -
Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.
Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.
Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
In LINUX
1.Single line commenting. Ctrl + /
2.For block comment Ctrl + Shift + /
You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.
$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c
[..]
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/lib/gcc/i686-apple-darwin9/4.0.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
[..]
t.c:1:32: error: bogus.h: No such file or directory
Some time ago i created an excel file with supported dimensions
Hope this will be helpful for somebody
To be honest i lost the idea, but it refers another screen feature as size (not only density)
https://developer.android.com/guide/practices/screens_support.html
Please inform me if there are some mistakes
cd /Library/Ruby/Gems/2.0.0
open .
right click get info
click lock
place password
make everything read and write.
ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.
The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:
<a href="#examples">Skip to examples</a>
There has to be an element in the page with that id, example:
<div id="examples">Here are the examples</div>
So make sure that each one of the links are matched inside the page with it's corresponding anchor.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__
is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype
and all other objects are descendants of this one. The __proto__
property of the root object is null
, which represents the end of inheritance chain.
You'll notice that prototype
is a property of functions. Cat
is a function, but also Function
and Object
are (native) functions. tom
is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new
operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor
which points back to the respective function object. For brevity reasons this was not depicted.
Indeed, when we create the tom
object with new Cat()
, the created object will have the __proto__
property set to the prototype
object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__
property points to the same object as Cat.prototype
.
Cat.__proto__
points to the Function.prototype
object, just like Function.__proto__
and Object.__proto__
do.
Cat.prototype.__proto__
and tom.__proto__.__proto__
point to the same object and that is Object.prototype
.
Cheers!
You have to define a path in the "Project compiler output" field in
File
>Project Structure...
>Project
>Project compiler output
This path will be used to store all project compilation results.
Don't re-sort after every item, its overkill..
If there is only one item to insert, you can find the location to insert using binary search. Then use memcpy or similar to bulk copy the remaining items to make space for the inserted one. The binary search is O(log n), and the copy is O(n), giving O(n + log n) total. Using the methods above, you are doing a re-sort after every insertion, which is O(n log n).
Does it matter? Lets say you are randomly inserting k elements, where k = 1000. The sorted list is 5000 items.
Binary search + Move = k*(n + log n) = 1000*(5000 + 12) = 5,000,012 = ~5 million ops
Re-sort on each = k*(n log n) = ~60 million ops
If the k items to insert arrive whenever, then you must do search+move. However, if you are given a list of k items to insert into a sorted array - ahead of time - then you can do even better. Sort the k items, separately from the already sorted n array. Then do a scan sort, in which you move down both sorted arrays simultaneously, merging one into the other. - One-step Merge sort = k log k + n = 9965 + 5000 = ~15,000 ops
Update: Regarding your question.
First method = binary search+move = O(n + log n)
. Second method = re-sort = O(n log n)
Exactly explains the timings you're getting.
You just need to use Arrow function to pass value.
<button onClick={() => this.props.onClickHandle("StackOverFlow")}>
Make sure to use () = >, Otherwise click method will be called without click event.
Note : Crash checks default methods
Please find below running code in codesandbox for the same.
Follow these steps:
Microsoft Access Database Engine 2016 Redistributable
and installI had some problems with this topic too. You have to make sure you define the packages in Spring boot runner class like this example below:
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
I hope this helps!
Firefox 71+ (2019-12-03) and Chrome 79+ (2019-12-10) support internal mapping of the width
and height
HTML attributes of the IMG
element to the new aspect-ratio
CSS property (the property itself is not yet available for direct use).
The calculated aspect ratio is used to reserve space for the image until it is loaded, and as long as the calculated aspect ratio is equal to the actual aspect ratio of the image, page “jump” is prevented after loading the image.
For this to work, one of the two image dimensions must be overridden via CSS to the auto
value:
IMG {max-width: 100%; height: auto; }
<img src="example.png" width="1280" height="720" alt="Example" />
In the example, the aspect ratio of 16:9 (1280:720) is maintained even if the image is not yet loaded and the effective image width is less than 1280 as a result of max-width: 100%
.
See also the related Firefox bug 392261.
That works:
DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:]
before being able to schedule and present UILocalNotifications, do not forget this.
If you want to go beyond binary evaluation and keep your CSS out of your controller you can implement a simple filter that evaluates the input against a map object:
angular.module('myApp.filters, [])
.filter('switch', function () {
return function (input, map) {
return map[input] || '';
};
});
This allows you to write your markup like this:
<div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
...
</div>
Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
Directive using formaters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var moment = $window.moment;
var dateFormat = attrs.moDateInput;
attrs.$observe('moDateInput', function (newValue) {
if (dateFormat == newValue || !ctrl.$modelValue) return;
dateFormat = newValue;
ctrl.$modelValue = new Date(ctrl.$setViewValue);
});
ctrl.$formatters.unshift(function (modelValue) {
if (!dateFormat || !modelValue) return "";
var retVal = moment(modelValue).format(dateFormat);
return retVal;
});
ctrl.$parsers.unshift(function (viewValue) {
var date = moment(viewValue, dateFormat);
return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
});
}
};
});
Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:
body {
-webkit-font-smoothing: antialiased;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
background: url('./images/background.png');
text-align: left;
margin: auto;
}
HTML:
<i class="icon-cog blackiconcolor">
css :
.blackiconcolor {color:black;}
you can also add extra class to the button icon...
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
Use : db.Set<tale>.AddRange(list);
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> {
new Person{Name="p1",Place="palce"},
new Person{Name="p2",Place="palce"},
new Person{Name="p3",Place="palce"},
new Person{Name="p4",Place="palce"},
new Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
This worked for me:
p { margin-left: -2em;
text-indent: 2em
}
Where
returns a new sequence of items matching the predicate.
Any
returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).
I'm not sure about Exists
- it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any
? (There's an Exists
method in List<T>
which is similar to Any(predicate)
but that predates LINQ.)
Even though it does not exactly fit to your problem, I'll drop this here. My requirements were:
Let's talk about (3) first: Just having the jars in a folder and somehow merging them into the final jar will not work for here, since the IDE will not understand this. This means all libraries have to be installed properly. However, I dont want to have everyone installing it using "mvn install-file".
In my project I needed metawidget. Here we go:
Every time you have a new library, just add a new execution and tell everyone to build the project again (you can improve this process with project hierachies).
I have used sequelize.js, node.js and transaction in belowcode and added proper error handling if it doesn't find data it will throw error that no data found with that id
deleteMyModel: async (req, res) => {
sequelize.sequelize.transaction(async (t1) => {
if (!req.body.id) {
return res.status(500).send(error.MANDATORY_FIELDS);
}
let feature = await sequelize.MyModel.findOne({
where: {
id: req.body.id
}
})
if (feature) {
let feature = await sequelize.MyModel.destroy({
where: {
id: req.body.id
}
});
let result = error.OK;
result.data = MyModel;
return res.status(200).send(result);
} else {
return res.status(404).send(error.DATA_NOT_FOUND);
}
}).catch(function (err) {
return res.status(500).send(error.SERVER_ERROR);
});
}
function bot_detected() {
if(preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']){
return true;
}
else{
return false;
}
}
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
There seems to be a much cleaner solution if you only want to reduce the spacing between the bullet point and the text:
li:before {
content: "";
margin-left: -0.5rem;
}
Yes.you have to loop it
public int getIndex(String itemName)
{
for (int i = 0; i < arraylist.size(); i++)
{
AuctionItem auction = arraylist.get(i);
if (itemName.equals(auction.getname()))
{
return i;
}
}
return -1;
}
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.com/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
Try like below:
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
I use Bitbucket with the Eclipse IDE with the Eclipse EGit plugin installed.
I compare a file from any version of its history (like SVN).
Menu Project Explorer → File → right click → Team → Show in history.
This will bring the history of all changes on that file. Now Ctrl click and select any two versions→ "Compare with each other".
Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS.
Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.
In jupyter notebook run:
!echo y | jupyter kernelspec uninstall unwanted-kernel
In anaconda prompt run:
jupyter kernelspec uninstall unwanted-kernel
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
An IntPtr is an integer which is the same size as a pointer.
You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.
The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.
The name "IntPtr" is confusing -- something like Handle
might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.
An IntPtr
is a pointer with two limitations:
In other words, an IntPtr
is just like a void*
-- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.
In order to dereference an IntPtr
, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal
class. Using the Marshal
class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.
The accepted/high-voted answers are great, but they are lacking a few nitty-gritty details. This post covers the cases on how to better handle when the shell path-name expansion (glob) fails, when filenames contain embedded newlines/dash symbols and moving the command output re-direction out of the for-loop when writing the results to a file.
When running the shell glob expansion using *
there is a possibility for the expansion to fail if there are no files present in the directory and an un-expanded glob string will be passed to the command to be run, which could have undesirable results. The bash
shell provides an extended shell option for this using nullglob
. So the loop basically becomes as follows inside the directory containing your files
shopt -s nullglob
for file in ./*; do
cmdToRun [option] -- "$file"
done
This lets you safely exit the for loop when the expression ./*
doesn't return any files (if the directory is empty)
or in a POSIX compliant way (nullglob
is bash
specific)
for file in ./*; do
[ -f "$file" ] || continue
cmdToRun [option] -- "$file"
done
This lets you go inside the loop when the expression fails for once and the condition [ -f "$file" ]
check if the un-expanded string ./*
is a valid filename in that directory, which wouldn't be. So on this condition failure, using continue
we resume back to the for
loop which won't run subsequently.
Also note the usage of --
just before passing the file name argument. This is needed because as noted previously, the shell filenames can contain dashes anywhere in the filename. Some of the shell commands interpret that and treat them as a command option when the name are not quoted properly and executes the command thinking if the flag is provided.
The --
signals the end of command line options in that case which means, the command shouldn't parse any strings beyond this point as command flags but only as filenames.
Double-quoting the filenames properly solves the cases when the names contain glob characters or white-spaces. But *nix filenames can also contain newlines in them. So we de-limit filenames with the only character that cannot be part of a valid filename - the null byte (\0
). Since bash
internally uses C
style strings in which the null bytes are used to indicate the end of string, it is the right candidate for this.
So using the printf
option of shell to delimit files with this NULL byte using the -d
option of read
command, we can do below
( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
cmdToRun [option] -- "$file"
done
The nullglob
and the printf
are wrapped around (..)
which means they are basically run in a sub-shell (child shell), because to avoid the nullglob
option to reflect on the parent shell, once the command exits. The -d ''
option of read
command is not POSIX compliant, so needs a bash
shell for this to be done. Using find
command this can be done as
while IFS= read -r -d '' file; do
cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0)
For find
implementations that don't support -print0
(other than the GNU and the FreeBSD implementations), this can be emulated using printf
find . -maxdepth 1 -type f -exec printf '%s\0' {} \; | xargs -0 cmdToRun [option] --
Another important fix is to move the re-direction out of the for-loop to reduce a high number of file I/O. When used inside the loop, the shell has to execute system-calls twice for each iteration of the for-loop, once for opening and once for closing the file descriptor associated with the file. This will become a bottle-neck on your performance for running large iterations. Recommended suggestion would be to move it outside the loop.
Extending the above code with this fixes, you could do
( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
cmdToRun [option] -- "$file"
done > results.out
which will basically put the contents of your command for each iteration of your file input to stdout and when the loop ends, open the target file once for writing the contents of the stdout and saving it. The equivalent find
version of the same would be
while IFS= read -r -d '' file; do
cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0) > results.out
there is a problem in best answer given by ScottKoon
here is it
} else if(el.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
Should be
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
Due to this it didn't work in IE. Hoping that ScottKoon will update code
You can use the append function. For rows:
>>> from numpy import *
>>> a = array([10,20,30])
>>> append(a, [[1,2,3]], axis=0)
array([[10, 20, 30],
[1, 2, 3]])
For columns:
>>> append(a, [[15],[15]], axis=1)
array([[10, 20, 30, 15],
[1, 2, 3, 15]])
EDIT
Of course, as mentioned in other answers, unless you're doing some processing (ex. inversion) on the matrix/array EVERY time you append something to it, I would just create a list, append to it then convert it to an array.
Swift 2.0 solution is here:
let urlStr = “http://url_to_manage_post_requests”
let url = NSURL(string: urlStr)
let request: NSMutableURLRequest =
NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
request.timeoutInterval = 60.0
//additional headers
request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)
let bodyStr = “string or data to add to body of request”
let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPBody = bodyData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
print("responseCode \(httpResponse.statusCode)")
}
if error != nil {
// You can handle error response here
print("\(error)")
}else {
//Converting response to collection formate (array or dictionary)
do{
let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:
NSJSONReadingOptions.MutableContainers))
//success code
}catch{
//failure code
}
}
}
task.resume()
It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.
To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.
(Updated version with updated screen shots Here)
Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.
Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.
Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.
Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.
To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:
Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.
Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.
Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.
Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:
Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.
Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.
Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:
Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.
Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts
Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
rm pushcert.p12
Step 11 - NEW AWS UPDATE: Create new pushcert.p12
to submit to AWS SNS. Double click on the new pushcert.pem
, then export the one highlighed on the green only.
Credit: AWS new update
Now you have successfully created an Apple Push Notification Certificate (.p12 file)! You will need to upload this file to our Build Your Own area later on. :)
Updated for Bootstrap 4.1+
Bootstrap 4 the navbar now uses flexbox so the Website Name
can be centered using mx-auto
. The left and right side menus don't require floats.
<nav class="navbar navbar-expand-md navbar-fixed-top navbar-dark bg-dark main-nav">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>
<ul class="nav navbar-nav mx-auto">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Rates</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with mx-auto
Demo
If the Navbar only has a single navbar-nav
, then justify-content-center
can also be used to center.
In the solution above, the Website Name
is centered relative to the left and right navbar-nav
so if the width of these adjacent navs are different the Website Name
is no longer centered.
To resolve this, one of the flexbox workarounds for absolute centering can be used...
Option 1 - Use position:absolute;
Since it's ok to use absolute positioning in flexbox, one option is to use this on the item to be centered.
.abs-center-x {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Navbar center with absolute position Demo
Option 2 - Use flexbox nesting
Finally, another option is to make the centered item also display:flexbox
(using d-flex
) and center justified. In this case each navbar component must have flex-grow:1
As of Bootstrap 4 Beta, the Navbar is now display:flex
. Bootstrap 4.1.0 includes a new flex-fill
class to make each nav section fill the width:
<nav class="navbar navbar-expand-sm navbar-dark bg-dark main-nav">
<div class="container justify-content-center">
<ul class="nav navbar-nav flex-fill w-100 flex-nowrap">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">More</a>
</li>
</ul>
<ul class="nav navbar-nav flex-fill justify-content-center">
<li class="nav-item"><a class="nav-link" href="#">Center</a></li>
</ul>
<ul class="nav navbar-nav flex-fill w-100 justify-content-end">
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with flexbox nesting Demo
Prior to Bootstrap 4.1.0 you can add the flex-fill class like this...
.flex-fill {
flex:1
}
As of 4.1 flex-fill
is included in Bootstrap.
Bootstrap 4 Navbar center demos
More centering demos
Center links on desktop, left align on mobile
Related:
How to center nav-items in Bootstrap?
Bootstrap NavBar with left, center or right aligned items
How move 'nav' element under 'navbar-brand' in my Navbar
A good choice is to use 'sed as grep' (as explained in this classical sed tutorial).
sed -n 's/pattern/&/p' file
Examples (works in bash, sh, ksh, csh,..):
[~]$ cat testfile
12 3
1 4 abc
xa c
a c\2
1 23
[~]$ sed -n 's/\t/&/p' testfile
xa c
a c\2
[~]$ sed -n 's/\ta\t/&/p' testfile
a c\2
If you are making the fetch call to your localhost which I'm guessing is run by node.js in the same directory as your backbone code, than it will most likely be on http://localhost:3000
or something like that. Than this should be your model:
var model = Backbone.Model.extend({
url: '/item'
});
And in your node.js you now have to accept that call like this:
app.get('/item', function(req, res){
res.send('some info here');
});
If you are also interested in the case where the user closes the date selection dialog without selecting a date (in my case choosing no date also has meaning) you can bind to the onClose
event:
$('#datePickerElement').datepicker({
onClose: function (dateText, inst) {
//you will get here once the user is done "choosing" - in the dateText you will have
//the new date or "" if no date has been selected
});
Following should work. I have verified. May be your problem is somewhere else.
Receiver:
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
Log.d("TAG", "MyReceiver");
Intent serviceIntent = new Intent(context, Test1Service.class);
context.startService(serviceIntent);
}
}
}
Service:
public class Test1Service extends Service {
/** Called when the activity is first created. */
@Override
public void onCreate() {
super.onCreate();
Log.d("TAG", "Service created.");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Service started.");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TAG", "Service started.");
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS"
/>
<!-- <activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity> -->
<service android:name=".Test1Service"
android:label="@string/app_name"
>
</service>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Open a phpsh terminal:
php> $myhashmap = array();
php> $myhashmap['mykey1'] = 'myvalue1';
php> $myhashmap['mykey2'] = 'myvalue2';
php> echo $myhashmap['mykey2'];
myvalue2
The complexity of the $myhashmap['mykey2']
in this case appears to be constant time O(1), meaning that as the size of $myhasmap approaches infinity, the amount of time it takes to retrieve a value given a key stays the same.
Evidence the php array read is constant time:
Run this through the PHP interpreter:
php> for($x = 0; $x < 1000000000; $x++){
... $myhashmap[$x] = $x . " derp";
... }
The loop adds 1 billion key/values, it takes about 2 minutes to add them all to the hashmap which may exhaust your memory.
Then see how long it takes to do a lookup:
php> system('date +%N');echo " " . $myhashmap[10333] . " ";system('date +%N');
786946389 10333 derp 789008364
So how fast is the PHP array map lookup?
The 10333
is the key we looked up. 1 million nanoseconds == 1 millisecond. The amount of time it takes to get a value from a key is 2.06 million nanoseconds or about 2 milliseconds. About the same amount of time if the array were empty. This looks like constant time to me.
When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR
keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
complete example here: How to create CSR with SANs using keytool
git diff HEAD file
will show you changes you added to your worktree from the last commit. All the changes (staged or not staged) will be shown.
I tried pasting Endoro's command (Thanks Endoro) directly into the command prompt to add a prefix to files but encountered an error. Solution was to reduce %% to %, so:
for /f "delims=" %i in ('dir /b /a-d *.*') do ren "%~i" "Service.Enviro.%~ni%~xi"
The short answer for lazy people like me:
type Overrided = Omit<YourInterface, 'overrideField'> & { overrideField: <type> };
If you want a REAL cloned object/array in JS with cloned references of all attributes and sub-objects:
export function clone(arr) {
return JSON.parse(JSON.stringify(arr))
}
ALL other operations do not create clones, because they just change the base address of the root element, not of the included objects.
Except you traverse recursive through the object-tree.
For a simple copy, these are OK. For storage address relevant operations I suggest (and in most all other cases, because this is fast!) to type convert into string and back in a complete new object.
Assuming you're talking about a static library, DUMPBIN /SYMBOLS
shows the functions and data objects in the library. If you're talking about an import library (a .lib
used to refer to symbols exported from a DLL), then you want DUMPBIN /EXPORTS
.
Note that for functions linked with the "C" binary interface, this still won't get you return values, parameters, or calling convention. That information isn't encoded in the .lib
at all; you have to know that ahead of time (via prototypes in header files, for example) in order to call them correctly.
For functions linked with the C++ binary interface, the calling convention and arguments are encoded in the exported name of the function (also called "name mangling"). DUMPBIN /SYMBOLS
will show you both the "mangled" function name as well as the decoded set of parameters.
$(this).parent()
Tree traversal is fun
$(this).parent().siblings(".something1");
$(this).parent().prev(); // if you always want the parent's previous sibling
$(this).parents(".box").children(".something1");
And much more ways, you might find these docs helpful.
I've come up with a solution to this that doesn't require you to know the number of row returned.
For example, if you want to get all the locations logged in a table, except the latest 1 (or 2, or 5, or 34)
SELECT *
FROM
(SELECT ROW_NUMBER() OVER (ORDER BY CreatedDate) AS Row, *
FROM Locations
WHERE UserId = 12345) AS SubQuery
WHERE Row > 1 -- or 2, or 5, or 34
First, have to check
SELECT * FROM university
WHERE course_name LIKE '%&%'
Next, have to update
UPDATE university SET course_name = REPLACE(course_name, '&', '&') WHERE id = 1
Results: Engineering & Technology => Engineering & Technology
The help for %in%, help("%in%")
, includes, in the Examples section, this definition of not in,
"%w/o%" <- function(x, y) x[!x %in% y] #-- x without y
Lets try it:
c(2,3,4) %w/o% c(2,8,9)
[1] 3 4
Alternatively
"%w/o%" <- function(x, y) !x %in% y #-- x without y
c(2,3,4) %w/o% c(2,8,9)
# [1] FALSE TRUE TRUE
You can memcpy
structs, or you can just assign them like any other value.
struct {int a, b;} c, d;
c.a = c.b = 10;
d = c;
<asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
</ItemTemplate>
</asp:TemplateField>
This is the traditional way and latest version of asp.net framework having strongly typed data and you don't need to use as string like "EMPID"
Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:
var rows = $('table.someclass tr');
$('#showBlackButton').click(function() {
var black = rows.filter('.black').show();
rows.not( black ).hide();
});
$('#showWhiteButton').click(function() {
var white = rows.filter('.white').show();
rows.not( white ).hide();
});
$('#showAll').click(function() {
rows.show();
});
<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr class="black">
...
</tr>
</thead>
<tbody>
<tr class="white">
...
</tr>
<tr class="black">
...
</tr>
</tbody>
</table>
It uses the filter()
[docs] method to filter the rows with the black
or white
class (depending on the button).
Then it uses the not()
[docs] method to do the opposite filter, excluding the black
or white
rows that were previously found.
EDIT: You could also pass a selector to .not()
instead of the previously found set. It may perform better that way:
rows.not( `.black` ).hide();
// ...
rows.not( `.white` ).hide();
...or better yet, just keep a cached set of both right from the start:
var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
My program does exactly what you are after, no prompts or anything, please see the following code.
This code will create all of the necessary directories if they don't already exist:
Directory.CreateDirectory(C:\dir\dira\dirb); // This code will create all of these directories
This code will download the given file to the given directory (after it has been created by the previous snippet:
private void install()
{
WebClient webClient = new WebClient(); // Creates a webclient
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); // Uses the Event Handler to check whether the download is complete
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); // Uses the Event Handler to check for progress made
webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip"); // Defines the URL and destination directory for the downloaded file
}
So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.
You need a pointer to the first char to have an ANSI string.
printf("%s", source + i);
will do the job
Plus, of course you should have meant strlen(source)
, not sizeof(source)
.