You could use the object data type:
>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
This question came first on Google although an old one so I'm posting the working answer I found, which can be of use to someone else.
This requires 3 divs including the fixed div.
HTML
<div class="wrapper">
<div class="parent">
<div class="child"></div>
</div>
</div>
CSS
.wrapper { position:relative; width:1280px; }
.parent { position:absolute; }
.child { position:fixed; width:960px; }
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* @link https://stackoverflow.com/a/16069817/603003
* @license MIT 2013-2015 ComFreek
* @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
defaultText
is displayed initiallyemptyText
is displayed when the input is empty (was cleared)invalidText
is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Tested in:
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:
def find_sum(arr,sum)
result ={}
h = Hash[arr.map {|i| [i,i]}]
arr.each { |l| result[l] = sum-l if h[sum-l] && !result[sum-l] }
result
end
To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l]
instruction
If whitespace becomes that important, it may be better to use preformatted text and the <pre> tag.
I ran into this problem, and my solution was moreso that www-data didn't own the proper folders, and instead I set it for one of the users to own it. (I was trying to do a bit of fancy, but erroneous trickery to get ftp to play nicely.)
After running:
chown -R www-data:www-data /var/www/html
The machine started serving data again. You can see who currently owns the folder by means of
ls -l /var/www/html
This assumes Eclipse and an appropriate JDK are installed on your system
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
You might be after something that the scrollTo plugin from Ariel Flesler does really well.
I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following: * Set the label AutoSize to true and TextAlign to MiddleCenter
Then, each time the text changed (mine was done using a timer) I called the following method:
private Point GetPosition()
{
int y = (this.Height / 2) - (label1.Height / 2);
int x = (this.Width / 2) - (label1.Width / 2);
return new Point(x, y);
}
And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.
There 2 way to resolve this issues
1. use chmod 777 path-to-your-directory
.
if it does not work then
2. simply provide the complete path of your file query.txt
.
SELECT CONVERT( VARCHAR(24), GETDATE(), 113)
UPDATE
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
// Example: Adding a converter to a column (C#)
Style styleReading = new Style(typeof(TextBlock));
Setter s = new Setter();
s.Property = TextBlock.ForegroundProperty;
Binding b = new Binding();
b.RelativeSource = RelativeSource.Self;
b.Path = new PropertyPath(TextBlock.TextProperty);
b.Converter = new ReadingForegroundSetter();
s.Value = b;
styleReading.Setters.Add(s);
col.ElementStyle = styleReading;
Lazy loading will produce several SQL calls while Eager loading may load data with one "more heavy" call (with joins/subqueries).
For example, If there is a high ping between your web and sql servers you would go with Eager loading instead of loading related items 1-by-1 with lazy Loading.
There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.
For example,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
Other way to solve the problem of space reclaiming is, Create multiple partitions within table - Range based, Value based partitions and just drop/truncate the partition to reclaim the space, which will release the space used by whole data stored in the particular partition.
There will be some changes needed in table schema when you introduce the partitioning for your table like - Unique Keys, Indexes to include partition column etc.
The sizzle selector engine (what powers JQuery) is perfectly geared up for this:
var elements = $('input[type=text]');
Or
var elements = $('input:text');
Assuming you mean "client side JavaScript" - then you can't, at least not directly.
The session data is stored on the server, so client side code can't see it without communicating with the server.
To access it you must make an HTTP request and have a server side program modify / read & return the data.
Gray your solution was strange but you seem like a nice guy.
AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials( ....
ObjectListing images = s3Client.listObjects(bucketName);
List<S3ObjectSummary> list = images.getObjectSummaries();
for(S3ObjectSummary image: list) {
S3Object obj = s3Client.getObject(bucketName, image.getKey());
writeToFile(obj.getObjectContent());
}
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
This will not expand the last column of the xaml grid to take the remaining space if
AutoGeneratedColumns="True"
.
The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:
Google Calendar Link
<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>
the parameters being:
Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:
https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134
New base url: https://calendar.google.com/calendar/r/eventedit
New parameters:
Notes:
+
for space in addition to %20
(urlencode
vs rawurlencode
in php - both work)To enable this behavior on a header or footer, add the
data-position="fixed"
attribute to a jQuery Mobile header or footer element.
<div data-role="footer" data-position="fixed">
<h1>Fixed Footer!</h1>
</div>
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = {_x000D_
key1: "it ",_x000D_
key2: function() {_x000D_
return this.key1 + " works!";_x000D_
}_x000D_
};_x000D_
_x000D_
alert(obj.key2());
_x000D_
#!/bin/bash
echo "Please Enter a file name :"
read filename
if test -f $filename
then
echo "this is a file"
else
echo "this is not a file"
fi
Did you try with strip() :
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]
>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
In this particular case, due to the dangers cited in other answers, I would
Edit in e.g. Vim and :%s/\s/\\\0/g
, escaping all space characters with a backslash.
Then :%s/^/rm -rf /
, prepending the command. With -r
you don't have to worry to have directories listed after the files contained therein, and with -f
it won't complain due to missing files or duplicate entries.
Run all the commands: $ source 1.txt
The problem is with Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
this line. The Class qualified name is wrong
It is sqlserver.jdbc
not jdbc.sqlserver
Use OnItemClickListener
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
When you click on a row a listener is fired. So you setOnClickListener
on the listview and use the annonymous inner class OnItemClickListener
.
You also override onItemClick
. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).
Using the position you get the item .
Edit : From your comments i assume you need to set the adapter o listview
So assuming your activity extends ListActivtiy
setListAdapter(adapter);
Or if your activity class extends Activity
ListView lv = (ListView) findViewById(R.id.listview1);
//initialize adapter
lv.setAdapter(adapter);
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
Create a dynamic view and get result from it.......
CREATE PROCEDURE dbo.usp_userwise_columns_value
(
@userid BIGINT
)
AS
BEGIN
DECLARE @maincmd NVARCHAR(max);
DECLARE @columnlist NVARCHAR(max);
DECLARE @columnname VARCHAR(150);
DECLARE @nickname VARCHAR(50);
SET @maincmd = '';
SET @columnname = '';
SET @columnlist = '';
SET @nickname = '';
DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
FOR
SELECT columnname , nickname
FROM dbo.v_userwise_columns
WHERE userid = @userid
OPEN CUR_COLUMNLIST
IF @@ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @columnlist = @columnlist + @columnname + ','
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
END
CLOSE CUR_COLUMNLIST
DEALLOCATE CUR_COLUMNLIST
IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
BEGIN
SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
ELSE
BEGIN
SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
EXECUTE sp_executesql @maincmd
END
-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
Would something like this work:
In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]:
func2 func1
dummy
1 -4.263768e-16 -0.188565
You may try to write app
in use
uppercase, so App
. Worked for me.
in spring boot :
1) if your file is ouside jar you can use :
@Autowired
private ResourceLoader resourceLoader;
**.resource(resourceLoader.getResource("file:/path_to_your_file"))**
2) if your file is inside resources of jar you can `enter code here`use :
**.resource(new ClassPathResource("file_name"))**
Using regex:
var str = "my car is red";
var stringArray = str.split(/(\s+)/);
console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"]
\s
matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.
To print to the real
console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE
. The extra console window is annoying, but for debugging purposes it's very valuable.
OutputDebugString
prints to the debugger output when running inside the debugger.
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
Fun! There are a few things to tease out here:
$leadID
seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework."
or '
characters. Since you’re already inside both "
and '
, you’ll want to escape whichever you choose. \'
to escape the PHP quotes, or '
to escape the HTML quotes.<a />
elements are commonly used for “hyper”links, and almost always with a href
attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>
.return false;
to a Javascript event to suppress default behavior.onclick
doesn’t mean anything on its own. That’s because onclick
is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick
we’re talking about! One such object is window
. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>
.onclick
can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">
. I bet you had this in mind.=
assignments. The Javascript =
expects something that hasn’t been run yet. You can wrap things in a function
block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload
): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ...
.<a href="http://www.google.com" target="_blank">Google homepage</a>
.Hope those are useful.
The offending lines are the following:
MaxConnections=90
InitialConnections=80
You can increase the values to allow more connections.
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
You can use forEach method to iterate over array of objects.
data.messages.forEach(function(message){
console.log(message)
});
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.
// Support for string arguments
getClassNames('class1', 'class2');
// support for Object
getClassNames({class1: true, class2 : false});
// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
class5 : function() { return false; },
class6 : function() { return true; }
});
<div className={getClassNames({class1: true, class2 : false})} />
When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.
Which OS?
Everything you download should be placed in the android-sdk folder (in my case: j:\android-sdk-windows).
You can execute "SDK Setup.exe" (or the mac/linux command for this) and download everything and just copy your complete android-sdk folder to another computer. I have the complete SDK + Eclipse + Workspace on an external HDD that I can just plug in to another Computer and it works (except for JDK which should be installed and the AVD's which are located in the user directory). Don't forget to set the ANDROID_HOME environment var to point to your install dir.
Update: In the SDK Downloader you have a "force https:// sources to be fetched using http://" checkbox under the settings menu. Maybe check (or if checked) uncheck this may help you to download everthing from your firewalled computer.
To further work with array of maps, the followings could help:
@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {
List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
maps.addAll(payload);
}
Set is the good approach here, because it orders the variables, what seems to be your goal here. {z,y,x}
is {0,1,3}
whatever the order of the parameters.
>>> ["cdef"[i] for i in {z,x,y}]
['c', 'd', 'f']
This way, the whole solution is O(n).
Take a look at UIScreen.
eg.
CGFloat width = [UIScreen mainScreen].bounds.size.width;
Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).
UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat width = CGRectGetWidth(self.view.bounds);
}
If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.
You need to use Store.getState()
to get current state of your Store.
For more information about getState()
watch this short video.
Same issue.
I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:
1.- Activate (Network Connections) by right click
2.- netsh wlan set hostednetwork mode=allow
3.- netsh wlan start hosted network
Good luck mate !!!
Sometimes this issue occurs, If you are creating a java file for the first time in your system. The Extension of your Java file gets saved as the text file.
e.g Example.java.txt (wrong extension)
You need to change the text file extension to java file.
It should be like:
Example.java (right extension)
Try creating a new PrintReportController object in SubmitPerformanceController and calling getPrintReport method directly.
For example lets say I have a function called "Test" in SubmitPerformanceController then I can do something like this:
public function test() {
$prc = new PrintReportController();
$prc->getPrintReport();
}
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));
if($url_in_array) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
Within a ServiceWorker
or Worker
, replace window
with self
:
self[method_prefix + method_name](arg1, arg2);
Workers have no access to the DOM, therefore window
is an invalid reference. The equivalent global scope identifier for this purpose is self
.
Old question, but I found this useful. Turns out, there's also a specialized class for a Dictionary using a string for both the key and the value:
private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary
{
{ "1", "Unrecognized segment ID" },
{ "2", "Unexpected segment" }
};
Edit: Per Chris's comment below, using Dictionary<string, string>
over StringDictionary
is generally preferred but will depend on your situation. If you're dealing with an older code base, you might be limited to the StringDictionary
. Also, note that the following line:
myDict["foo"]
will return null if myDict
is a StringDictionary
, but an exception will be thrown in case of Dictionary<string, string>
. See the SO post he mentioned for more information, which is the source of this edit.
CryptoJS is a crypto library which can generate md5 hash among others:
Usage with Script tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
var hash = CryptoJS.MD5("Message");
alert(hash);
</script>
Alternatively with ES6:
npm install crypto-js
import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());
You can also use modular imports:
var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());
Github: https://github.com/brix/crypto-js
CDN: https://cdnjs.com/libraries/crypto-js
Alt + Shift + F10 will show the menu associated with the smart tag.
If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
and client side JavaScript/jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.
In HTML5, the
<hr>
tag defines a thematic break. In HTML 4.01, the<hr>
tag represents a horizontal rule.
http://www.w3schools.com/tags/tag_hr.asp
So after definition, I would prefer <hr>
I have created a jQuery plugin to add css-pseudo rules like using .css()
for specific elements.
usage:
$('body')
.css({
backgroundColor: 'white'
})
.cssPseudo('after', {
content: 'attr(title) ", you should try to hover the picture, then click it."',
position: 'absolute',
top: 20, left: 20
})
.cssPseudo('hover:after', {
content: '"Now hover the picture, then click it!"'
});
Here's a chart that may be helpful deciding which to use: http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/
Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);
public class User : List<UserData>
{
public int id { get; set; }
public string screen_name { get; set; }
}
string json = client.DownloadString(url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
var Data = serializer.Deserialize<List<UserData>>(json);
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
In my case getters and setter names were different from Variable name.
private Long stockId;
public Long getStockID() {
return stockId;
}
public void setStockID(Long stockID) {
this.stockId = stockID;
}
where it should be
public Long getStockId() {
return stockId;
}
public void setStockId(Long stockID) {
this.stockId = stockID;
}
To add on others' answers - there is one useful that will help you when coding (for example when solving project Euler problems): Hoogle. You can use either the command line interface or the web interface.
After you installed the Haskell platform be sure to cabal install hoogle
Hoogle usage example:
You have a function f x = 3 * x + 1
and you want to apply it on (5 :: Int)
, then apply it on the result and on that result and so on and get an infinite list of those values. You suspect there might already exist a function to assist you (not specifically for your f
though).
That function would be of type (a -> a) -> a -> [a]
if it takes f 5
or a -> (a -> a) -> [a]
if it takes 5 f
(we assume the function is for general types and not just Int
s)
$ hoogle "a -> (a -> a) -> [a]"
Prelude iterate :: (a -> a) -> a -> [a]
yep, the function you need already exists and it's called iterate
. you use it by iterate func 5
!
The result for the same example can be found here.
Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:
pd.read_csv('../../../data_folder/data.csv')
Will go 3 levels up and then into a data_folder (assuming it's there) Or
pd.read_csv('data_folder/data.csv')
assuming your data_folder is in the same directory as your .py file.
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
m = [1:numel(list)]';
elm = list.*m;
vectorized algorithms in matlab are in general much faster.
Settings -> Workbench -> Editor Management -> Enable Preview
This worked perfectly for me (simple text replace):
Go to search -> file
Containing text: old pakage name
File name pattern: *
Scope: workspace
Press Replace
Replace: new package name
Now your project is full of errors.
Click your package in project explorer and press F2 (rename).
Fill in the new package name and check all checkmarks.
Press Preview.
Click OK.
Wait for Eclipse to refresh. If there are still errors, clean all projects in the workspace:
Project -> Clean
Highlighting an entity in a query and pressing ALT + F1 will run sp_help for it, giving you a breakdown of any columns, indexes, parameters etc.
As per my understanding, this can be done in two ways :
1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.
Directory.GetFiles("your_folder_path)[i].Contains("*.txt")
2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.
Path.GetExtension(your_file_path).Equals(".json")
Note : Both the logic has to be inside a looping condition.
You can do this in a slightly hack-y way by:
I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).
I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:
find /etc -type f -exec grep -nHi -e "widehat" {} \;
Instead of:
grep -nRHi -e "widehat" /etc
!important
word is prior to first two rules.for example:
.divclass .spanclass
is more specific than .spanclass
.divclass.divclass
is more specific than .divclass
#divId .spanclass
has ID that's why it is more specific than .divClass .spanClass
<div id="someDiv" style="color:red;">
has attribute and beats #someDiv{color:blue}
#someDiv{color:blue!important}
will be applied over attribute style="color:red"
Just export the environment variables you want above the check for a non-interactive shell in ~/.bashrc.
If you are using MinGW toolchain for CDT, make.exe is found at C:\MinGW\msys\1.0\bin
(or search the make.exe in MinGW folder.)
Add this path in eclipse window->preferences->environment
In addition to the angular json
filter already mentioned, there is also the angular toJson()
function.
angular.toJson(obj, pretty);
The second param of this function lets you switch on pretty printing and set the number of spaces to use.
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.
(default: 2)
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
You should look into DependencyObjects as used by WPF these follow a similar pattern whereby properties can be assigned at runtime. As mentioned above this ultimately points towards using a hash table.
One other useful thing to have a look at is CSLA.Net. The code is freely available and uses some of the principles\patterns it appears you are after.
Also if you are looking at sorting and filtering I'm guessing you're going to be using some kind of grid. A useful interface to implement is ICustomTypeDescriptor, this lets you effectively override what happens when your object gets reflected on so you can point the reflector to your object's own internal hash table.
You can do this in the storyboard / xib editor as well. Just set Seperator to none.
It the element has two xpath. Then you can write two xpaths like below:
xpath1
| xpath2
Eg:
//input[@name="username"] | //input[@id="wm_login-username"]
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
In my view, "Explicit is always better than implicit." Because at some point, you may got confused with this increments statement y+ = x++ + ++y
. A good programmer always makes his or her code more readable.
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static
keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
There is only one correct answer to this and most systems get it wrong. Number of milliseconds since epoch, aka a 64 bit integer. Time Zone is a UI concern and has no business in the app layer or db layer. Why does your db care what time zone something is, when you know it's going to store it as a 64 bit integer then do the transformation calculations.
Strip out the extraneous bits and just treat dates as numbers up to the UI. You can use simple arithmetic operators to do queries and logic.
You just use jquery each() function ;
$(function() {
$( ".selector_class_name" ).each(function(){
$( this ).accordion({
collapsible: true,
active:false,
heightStyle: "content"
});
});
});
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.
HTML
<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
Nothing here
</div>
You can use CSS to style the main section of the dialog but not the title
.custom-ui-widget-header-warning {
background: #EBCCCC;
font-size: 1em;
}
You need some JS to style the title
$(function() {
$("#nonmodal1").dialog({
minWidth: 400,
minHeight: 'auto',
autoOpen: false,
dialogClass: 'custom-ui-widget-header-warning',
position: {
my: 'center',
at: 'left'
}
});
$("#dialog1").click(function() {
if ($("#nonmodal1").dialog("isOpen") === true) {
$("#nonmodal1").dialog("close");
} else {
$("#nonmodal1").dialog("open").prev().css('background','#D9534F');
}
});
});
The example only shows simple styling (background) but you can make it as complex as you wish.
You can see it in action here:
Then NumPy sum
function takes an optional axis argument that specifies along which axis you would like the sum performed:
>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])
Or, equivalently:
>>> numpy.sum(a, 0)
array([18, 22, 26])
Select the Object -> Format -> Selection Pane -> Double click to change the name
Believe it or not, renaming LinqPad.exe.config to LinqPad.config solved this problem.
Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
There is no direct option to export a single request from Postman.
You can create and export collections. Here is a link to help with that.
Regarding the single request thing, you can try a workaround. I tried with the RAW body parameters and it worked.
What you can do is,
Suppose you have many selects. This can do it:
$('.selectClass').change(function(){
var optionSelected = $(this).find('option:selected').attr('optionAtribute');
alert(optionSelected);//this will show the value of the atribute of that option.
});
public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
if (endDate < startDate)
throw new ArgumentException("endDate must be greater than or equal to startDate");
while (startDate <= endDate)
{
yield return startDate;
startDate = startDate.AddDays(1);
}
}
You may use the typescript getter method for this scenario. Like this
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
You won't need any event handler to check for resizing/ of window, this method will check for size every time automatically.
try: ctrl + P
type: @
followed by the name of the class,method or variable name you search for.
Use simple CSS3 (not supported in IE<9)
img
{
box-shadow: 0px 0px 5px #fff;
}
This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)
If you're worried about the users that don't have the latest versions of their browsers, use this:
img
{
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;
}
For IE you can use a glow filter (not sure which browsers support it)
img
{
filter:progid:DXImageTransform.Microsoft.Glow(Color=white,Strength=5);
}
Play with the settings to see what suits you :)
Reload the datasource of your grid after the update
myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;
Here's the solution I used in Kotlin
private fun startTimer()
{
Log.d(TAG, ":startTimer: timeString = '$timeString'")
object : CountDownTimer(TASK_SWITCH_TIMER, 250)
{
override fun onTick(millisUntilFinished: Long)
{
val secondsUntilFinished : Long =
Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
"%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
}
@SuppressLint("SetTextI18n")
override fun onFinish()
{
timerTxtVw.text = "0:00"
gameStartEndVisibility(true)
}
}.start()
}
I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.
Are you running PHP or ASP.NET?
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
I had to complete the same task and I used a "for" loop and a "del" command as follows:
@ECHO OFF
set dir=%cd%
FOR /d /r %dir% %%x in (archive\) do (
if exist "%%x" del %%x\*.txt /f /q
)
You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.
These are the options for "for" command:
These are the options for "del" command:
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Swift 4.2 version of SwiftArchitect's solution above (works great):
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Invocation:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.
Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.
A good seed initialisation can be done like this
Random rnd = new Random((int)DateTime.Now.Ticks);
The ticks will be unique and the cast into a int with probably a loose of value will be OK.
In your css file add following.
ul{
list-style-type: none;
}
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
Bill's answer is very good, but you may want to do some things with the request like compression or user-agents. The following code shows how you can various types of compression to your requests.
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;
// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
} else {
inStr = conn.getInputStream();
}
To also set the user-agent add the following code:
conn.setRequestProperty ( "User-agent", "my agent name");
I'd recommend you to create a shortcut to eclipse.exe with the -data
command line option. This way you can create a separate shortcut to each workspace you use, and avoid unnecessary dialogs and mouse clicks.
Windows: Just create an Eclipse shortcut on your desktop, then right-click to open Properties
and under Shortcut
set something like this as Target
: C:\eclipse\eclipse.exe -data C:\Path\to\your\workspace1
. This will launch Eclipse and automatically open workspace1
.
Repeat the steps for all the workspaces you use often.
curl
's -w
option and the sub variable url_effective
is what you are
looking for.
Something like
curl -Ls -o /dev/null -w %{url_effective} http://google.com
More info
-L Follow redirects -s Silent mode. Don't output anything -o FILE Write output to <file> instead of stdout -w FORMAT What to output after completion
More
You might want to add -I
(that is an uppercase i
) as well, which will make the command not download any "body", but it then also uses the HEAD method, which is not what the question included and risk changing what the server does. Sometimes servers don't respond well to HEAD even when they respond fine to GET.
This appears to be a limitation in git-bash. The recommendation to use winpty python.exe
worked for me. See Python not working in the command line of git bash for additional information.
The problem could be on this line:
var selectedText2 = $("#SelectedCountryId:selected").text();
It's looking for the item with id of SelectedCountryId
that is selected, where you really want the option that's selected under SelectedCountryId
, so try:
$('#SelectedCountryId option:selected').text()
Use selectionStart
, it is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
Update: This works only when no type is defined or type="text"
or type="textarea"
on the input.
Easiest way is to select it from xml as follows,
<menu>
<group android:checkableBehavior="single">
<item
android:checked="true"
android:id="@+id/nav_home"
android:icon="@drawable/nav_home"
android:title="@string/main_screen_title_home" />
Note the line android:checked="true"
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.
using System;
using System.Security.Cryptography;
using System.Text;
namespace PortalAplicaciones.Shared.Models
{
public class Encriptar
{
public static string EncriptaPassWord(string Password)
{
try
{
SHA256Managed hasher = new SHA256Managed();
byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
byte[] keyBytes = hasher.ComputeHash(pwdBytes);
hasher.Dispose();
return Convert.ToBase64String(keyBytes);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
Instead of taking the HttpServletRequest
object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.
public class OAuth2ClientController {
@Autowired
private OAuth2ClientService oAuth2ClientService;
private HttpServletRequest request;
@Autowired
public OAuth2ClientController(HttpServletRequest request) {
this.request = request;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
System.out.println(request.getRequestURI());
System.out.println(request.getHeader("Content-Type"));
return ResponseEntity.ok();
}
}
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
I've posted an step by step guide (here) to convert svn in to git including converting svn tags in to git tags and svn branches in to git branches.
Short version:
1) clone svn from an specific revision number. (the revision number must be the oldest you want to migrate)
git svn clone --username=yourSvnUsername -T trunk_subdir -t tags_subdir -b branches_subdir -r aRevisionNumber svn_url gitreponame
2) fetch svn data. This step it's the one it takes most time.
cd gitreponame
git svn fetch
repeat git svn fetch until finishes without error
3) get master branch updated
git svn rebase
4) Create local branches from svn branches by copying references
cp .git/refs/remotes/origin/* .git/refs/heads/
5) convert svn tags into git tags
git for-each-ref refs/remotes/origin/tags | sed 's#^.*\([[:xdigit:]]\{40\}\).*refs/remotes/origin/tags/\(.*\)$#\2 \1#g' | while read p; do git tag -m "tag from svn" $p; done
6) Put a repository at a better place like github
git remotes add newrepo [email protected]:aUser/aProjectName.git
git push newrepo refs/heads/*
git push --tags newrepo
If you want more details, read my post or ask me.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Wrapper class is a class that wrap the another class and provide the abstraction between client and the original class being wrapped.
The first thing that comes to mind for me is:
verts = [None]*1000
But do you really need to preinitialize it?
I'm going to improve the answer by supporting partitioned tables:
find partition scheme and partition key using below scritps:
declare @partition_scheme varchar(100) = (
select distinct ps.Name AS PartitionScheme
from sys.indexes i
join sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id
join sys.partition_schemes ps on ps.data_space_id = i.data_space_id
where i.object_id = object_id('your table name')
)
print @partition_scheme
declare @partition_column varchar(100) = (
select c.name
from sys.tables t
join sys.indexes i
on(i.object_id = t.object_id
and i.index_id < 2)
join sys.index_columns ic
on(ic.partition_ordinal > 0
and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c
on(c.object_id = ic.object_id
and c.column_id = ic.column_id)
where t.object_id = object_id('your table name')
)
print @partition_column
then change the generation query by adding below line at the right place:
+ IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')
//a[contains(@prop,'Foo')]
Works if I use this XML to get results back.
<bla>
<a prop="Foo1">a</a>
<a prop="Foo2">b</a>
<a prop="3Foo">c</a>
<a prop="Bar">a</a>
</bla>
Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use
/bla/a[contains(@prop,'Foo')]
This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element
//a[contains(@prop,'Foo')]
I added this for the sake of thoroughness and in the spirit of stackoverflow. :)
While using innerHTML.replace will work and is pretty fast, this will break the DOM state. You can replicate this by setting "autofocus" on an input field and then changing innerHTML on body, it will loose focus.
A less destructive approach is:
// retrives all childNodes of body
var childNodes = document.body.childNodes;
// start replacing
replaceInNodes(childNodes,"search","replace");
function replaceInNodes(nodes,search,replace){
// iterate through all nodes
for (var i = 0; i < nodes.length; i++) {
var curNode = nodes[i];
// if the node has attributes, let us look at those
// i.E. we want to change "John" in the input placeholder to "Peter" - <input type="text" value="John">
if(curNode.attributes !== undefined){
var curNodeAttributes = curNode.attributes;
for (var ii = 0; ii < curNodeAttributes.length; ii++) {
// replace attribute values
curNodeAttributes[ii].nodeValue = curNodeAttributes[ii].nodeValue.replace(search, replace);
}
}
// It is a "TEXT_NODE"
// i.E. <span>John</span>
if(curNode.nodeType == 3){
curNode.data = this.injectIntoString(curNode.data);
}
// It is a "ELEMENT_NODE", meaning we need to go deeper
if(curNode.nodeType == 1){
this.replaceInNodes(curNode.childNodes);
}
}
}
More info can be found here: https://zgheb.com/i?v=blog&pl=71#12.11.2020_-_Unobstrusively_replace_text_with_JavaScript Note: I am the author of said link
This will need new var ttfixed
Then this under the tt
value slot and replace all pointers down below that are tt
to ttfixed
ttfixed = (tt.replace(",", "."));
It's time to use jupyterlab
Finally, a much-needed upgrade has come to notebooks. By default, it uses the full width of your window like any other full-fledged native IDE.
All you have to do is:
pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run
jupyter lab # instead of jupyter notebook
Maybe this might help you. I added Shell32.lib to my Linker --> Input --> Additional Dependencies and it stopped this error. I found out about it from this post: https://discourse.libsdl.org/t/windows-build-fails-with-missing-symbol-imp-commandlinetoargvw/27256/3
for example
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ComboboxExample {
private JFrame frame = new JFrame("Test");
private JComboBox comboBox = new JComboBox();
public ComboboxExample() {
createGui();
}
private void createGui() {
comboBox.addItem("One");
comboBox.addItem("Two");
comboBox.addItem("Three");
JButton button = new JButton("Show Selected");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
});
JButton button1 = new JButton("Append Items");
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendCbItem();
}
});
JButton button2 = new JButton("Reduce Items");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
reduceCbItem();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4, 1));
frame.add(comboBox);
frame.add(button);
frame.add(button1);
frame.add(button2);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
selectFirstItem();
}
public void appendCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.addItem("Four");
comboBox.addItem("Five");
comboBox.addItem("Six");
comboBox.setSelectedItem("Six");
requestCbFocus();
}
});
}
public void reduceCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.removeItem("Four");
comboBox.removeItem("Five");
comboBox.removeItem("Six");
selectFirstItem();
}
});
}
public void selectFirstItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.setSelectedIndex(0);
requestCbFocus();
}
});
}
public void requestCbFocus() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ComboboxExample comboboxExample = new ComboboxExample();
}
});
}
}
The answer to your original question
How to read a string one char at the time, and stop when you reach end of line?
is, in C++, very simply, namely: use getline. The link shows a simple example:
#include <iostream>
#include <string>
int main () {
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.
C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.
Your later questions regarding "\0"
and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.
Python trim
method is called strip
:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
What's about Java code wrapped by a procedure? Simple and works fine.
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED SNOOZE AS
public final class Snooze {
private Snooze() {
}
public static void snooze(Long milliseconds) throws InterruptedException {
Thread.sleep(milliseconds);
}
}
CREATE OR REPLACE PROCEDURE SNOOZE(p_Milliseconds IN NUMBER) AS
LANGUAGE JAVA NAME 'Snooze.snooze(java.lang.Long)';
In this example I do other things that are also necessary when wanting to use a Singleton. For instance:
Like this:
class MySingleton {
static final MySingleton _singleton = MySingleton._internal();
String _valueToBeSet;
String _valueAlreadyInSingleton;
String _passedValueInContructor;
get getValueToBeSet => _valueToBeSet;
get getValueAlreadyInSingleton => _valueAlreadyInSingleton;
get getPassedValueInConstructor => _passedValueInContructor;
void setValue(newValue) {
_valueToBeSet = newValue;
}
factory MySingleton(String passedString) {
_singleton._valueAlreadyInSingleton = "foo";
_singleton._passedValueInContructor = passedString;
return _singleton;
}
MySingleton._internal();
}
Usage of MySingleton:
void main() {
MySingleton mySingleton = MySingleton("passedString");
mySingleton.setValue("setValue");
print(mySingleton.getPassedValueInConstructor);
print(mySingleton.getValueToBeSet);
print(mySingleton.getValueAlreadyInSingleton);
}
The code runs much faster without using modulo:
public boolean isEven(int a){
return ( (a & 1) == 0 );
}
public boolean isOdd(int a){
return ( (a & 1) == 1 );
}
Does this work for you:
You find this dialog on the Home
ribbon, under the Styles
group, the Conditional Formatting
menu, New rule...
.
You should use the StringFormat
on the Binding
. You can use either standard string formats, or custom string formats:
<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />
Note that the StringFormat
only works when the target property is of type string. If you are trying to set something like a Content
property (typeof(object)
), you will need to use a custom StringFormatConverter
(like here), and pass your format string as the ConverterParameter
.
Edit for updated question
So, if your ViewModel
defines the precision, I'd recommend doing this as a MultiBinding
, and creating your own IMultiValueConverter
. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding
, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter
would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format
.
However, for things like a ContentControl
, you can much more easily do this with a Style
:
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentStringFormat"
Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>
Any control that exposes a ContentStringFormat
can be used like this. Unfortunately, TextBox
doesn't have anything like that.
Use px-0
on the container
and no-gutters
on the row
to remove the paddings.
Quoting from Bootstrap 4 - Grid system:
Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.
Columns have horizontal padding to create the gutters between individual columns, however, you can remove the margin from rows and padding from columns with
.no-gutters
on the.row
.
Following is a live demo:
h1 {
background-color: tomato;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<div class="container-fluid" id="div1">
<div class="row">
<div class="col">
<h1>With padding : (</h1>
</div>
</div>
</div>
<div class="container-fluid px-0" id="div1">
<div class="row no-gutters">
<div class="col">
<h1>No padding : > </h1>
</div>
</div>
</div>
_x000D_
The reason this works is that container-fluid
and col
both have following padding:
padding-right: 15px;
padding-left: 15px;
px-0
can remove the horizontal padding from container-fluid
and no-gutters
can remove the padding from col
.
Just restart
your AS, then Rebuild
your app!
Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.
MySQL does however:
ALTER TABLE mytable
ADD COLUMN new_column <type>
AFTER existing_column
Copy your source folder to somedir
:
cp -r srcdir
somedir
Remove all unneeded files:
find somedir -name '.svn' -exec rm -rf {} \+
launch scp from somedir
Lets say I'm trying to render the below HTML.
let myHTML = "<p>Go to this <a href='https://google.com'>website </b></p>";
JSON.parse(JSON.stringify(myHTML))
This would give you a HTML element which you can set using innerHTML.
Like this
document.getElementById("demo").innerHTML = JSON.parse(JSON.stringify(myHTML));
People are storing their HTML as an object here. However the method I suggested does the same without having to use an Object.
i have been working on a dropdown replacement jquery plugin to combat this problem. As of this post, it is almost indistinguishable from a native dropdown in terms of look and functionality.
here is a demo (also a link to downloads): http://programmingdrunk.com/current-projects/dropdownReplacement/
here is the project page of the plugin:
http://plugins.jquery.com/project/dropdownreplacement
(update:) the jquery plugin page seems to no longer work. I will probably not put my plugin on their new site when they get it working, so feel free to use the programmingdrunk.com link for demo/download
I have created a small utility function, this works well for me
def display_text_max_col_width(df, width):
with pd.option_context('display.max_colwidth', width):
print(df)
display_text_max_col_width(train_df["Description"], 800)
I can change length of the width as per my requirement, without setting any option permanently.
I got stumped here a bit. Wanted to package some resource files into a wheel file and access them. Did the packaging using manifest file, but pip install was not installing it unless it was a sub directory. Hoping these sceen shots will help
+-- cnn_client
¦ +-- image_preprocessor.py
¦ +-- __init__.py
¦ +-- resources
¦ ¦ +-- mscoco_complete_label_map.pbtxt
¦ ¦ +-- retinanet_complete_label_map.pbtxt
¦ ¦ +-- retinanet_label_map.py
¦ +-- tf_client.py
MANIFEST.in
recursive-include cnn_client/resources *
Created a weel using standard setup.py . pip installed the wheel file. After installation checked if resources are installed. They are
ls /usr/local/lib/python2.7/dist-packages/cnn_client/resources
mscoco_complete_label_map.pbtxt
retinanet_complete_label_map.pbtxt
retinanet_label_map.py
In tfclient.py to access these files. from
templates_dir = os.path.join(os.path.dirname(__file__), 'resources')
file_path = os.path.join(templates_dir, \
'mscoco_complete_label_map.pbtxt')
s = open(file_path, 'r').read()
And it works.
Usually I go about parsing instead of sourcing, to avoid complexities of certain artifacts in my file. It also offers me ways to specially handle quotes and other things. My main aim is to keep whatever comes after the '=' as a literal, even the double quotes and spaces.
#!/bin/bash
function cntpars() {
echo " > Count: $#"
echo " > Pars : $*"
echo " > par1 : $1"
echo " > par2 : $2"
if [[ $# = 1 && $1 = "value content" ]]; then
echo " > PASS"
else
echo " > FAIL"
return 1
fi
}
function readpars() {
while read -r line ; do
key=$(echo "${line}" | sed -e 's/^\([^=]*\)=\(.*\)$/\1/')
val=$(echo "${line}" | sed -e 's/^\([^=]*\)=\(.*\)$/\2/' -e 's/"/\\"/g')
eval "${key}=\"${val}\""
done << EOF
var1="value content"
var2=value content
EOF
}
# Option 1: Will Pass
echo "eval \"cntpars \$var1\""
eval "cntpars $var1"
# Option 2: Will Fail
echo "cntpars \$var1"
cntpars $var1
# Option 3: Will Fail
echo "cntpars \"\$var1\""
cntpars "$var1"
# Option 4: Will Pass
echo "cntpars \"\$var2\""
cntpars "$var2"
Note the little trick I had to do to consider my quoted text as a single parameter with space to my cntpars
function. There was one extra level of evaluation required. If I wouldn't do this, as in Option 2, I would have passed 2 parameters as follows:
"value
content"
Double quoting during command execution causes the double quotes from the parameter file to be kept. Hence the 3rd Option also fails.
The other option would be of course to just simply not provide variables in double quotes, as in Option 4, and then just to make sure that you quote them when needed.
Just something to keep in mind.
Another thing I like to do is to do a real-time lookup, avoiding the use of environment variables:
lookup() {
if [[ -z "$1" ]] ; then
echo ""
else
${AWK} -v "id=$1" 'BEGIN { FS = "=" } $1 == id { print $2 ; exit }' $2
fi
}
MY_LOCAL_VAR=$(lookup CONFIG_VAR filename.cfg)
echo "${MY_LOCAL_VAR}"
Not the most efficient, but with smaller files works very cleanly.
Select the code you want to comment, then use Ctr + / to comment and Ctrl + / also to uncomment. It may not work for all types of source files, but it works great for Java code.
synchronized
is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized
block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.
volatile
is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile
variables. All threads can access volatile variable value at same time.
A good example to use volatile variable : Date
variable.
Assume that you have made Date variable volatile
. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.
Have a look at this article for better understanding of volatile
concept.
Lawrence Dol cleary explained your read-write-update query
.
Regarding your other queries
When is it more suitable to declare variables volatile than access them through synchronized?
You have to use volatile
if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.
Is it a good idea to use volatile for variables that depend on input?
Answer will be same as in first query.
Refer to this article for better understanding.
First, one of Perlis's epigrams:
"If you have a procedure with 10 parameters, you probably missed some."
Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.
Making an example up, because there's not enough information in the question to answer directly:
class PersonInfo(object):
def __init__(self, name, age, iq):
self.name = name
self.age = age
self.iq = iq
Then your 10 argument function:
def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
...
becomes:
def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
...
and the caller changes to:
personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
I don't know why but I was had to use local folder before source server directive . to make it work
scp -r . [email protected]:/usr/share/nginx/www/example.org/
Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.
Insert single quotes.
Example
$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);
2 from decimal numbering system in binary is as follows
10
now if you do
2 << 11
it would be , 11 zeros would be padded on the right side
1000000000000
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension [..]
left shifting results in multiplication by 2 (*2) in terms or arithmetic
For example
2 in binary 10
, if you do <<1
that would be 100
which is 4
4 in binary 100
, if you do <<1
that would be 1000
which is 8
Also See
Recently came upon a case where this was not true, TI C28x boards can have a sizeof pointer == 1, since a byte for those boards is 16-bits, and pointer size is 16 bits. To make matters more confusing, they also have far pointers which are 22-bits. I'm not really sure what sizeof far pointer would be.
In general, DSP boards can have weird integer sizes.
So pointer sizes can still be weird in 2020 if you are looking in weird places
def hex2bin(s):
hex_table = ['0000', '0001', '0010', '0011',
'0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011',
'1100', '1101', '1110', '1111']
bits = ''
for i in range(len(s)):
bits += hex_table[int(s[i], base=16)]
return bits
This is almost like the other answer but you don't need a scatter
plot at all, you can simply specify a scatter-plot-like format (fmt
-parameter) for errorbar
:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()
Result:
A list of the avaiable fmt
parameters can be found for example in the plot
documentation:
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.
If you have more than one version of python installed, run the respective pip command.
For example for python3.6 run the following
pip3.6 install beautifulsoup4
To check the available command/version of pip and python on Mac run
ls /usr/local/bin
The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:
/js/clock.js
then you could add this code to the top of any page in your site and it would just work:
<script src="/js/clock.js" type="text/javascript"></script>
I usually run this command when I have to copy my ssh-key
:
cat ~/.ssh/id_rsa.pub | pbcopy
ctrl+v
anywhere else.
To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.
size_t forward_length = strlen(forward);
python 3.2
with open("d://test.txt") as f:
k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
d={}
for i,_,v in k:
d.setdefault(i,[]).append(v)
Call the values()
method on the dict.
Hadoop file system does not support appending data to the existing files. Although, you can load your CSV file into HDFS and tell Hive to treat it as an external table.
Previous answers are correct but here is one more way of doing this and some tips:
Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there
Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh
things to watch for /tips:
One clean solution is to use NumPy's outer-product function with a vector of ones:
np.outer(np.ones(n), x)
gives n
repeating rows. Switch the argument order to get repeating columns. To get an equal number of rows and columns you might do
np.outer(np.ones_like(x), x)
strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable
weak: will assign the incoming value to it without retaining it.
So the basic difference is the retaining of the new variable. Generaly you want to retain it but there are situations where you don't want to have it otherwise you will get a retain cycle and can not free the memory the objects. Eg. obj1 retains obj2 and obj2 retains obj1. To solve this kind of situation you use weak references.
- Is there a way to obtain a list of Python modules available (i.e. installed) on a machine?
This works for me:
help('modules')
- Where is the module code actually stored on my machine?
Usually in /lib/site-packages
in your Python folder. (At least, on Windows.)
You can use sys.path
to find out what directories are searched for modules.
Just to expand niko's answer:
You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src
. Example:
Relative location:
<img src="images/image.png">
The image is sought relative to the document's location. If your document is at http://example.com/site/document.html
, then your images
folder should be on the same directory where your document.html
file is.
Absolute location:
<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">
or
<img src="http://another-example.com/images/image.png">
In this case, your image will be sought from the document site's root, so, if your document.html
is at http://example.com/site/document.html
, the root would be at http://example.com/
(or it's respective directory on the server's filesystem, commonly www/
). The first two examples are the same, since both point to the same host, Think of the first /
as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.
Regarding /
, .
and ..
:
The /
symbol will always return the root of a filesystem or site.
The single point ./
points to the same directory where you are.
And the double point ../
will point to the upper directory, or the one that contains the actual working directory.
So you can build relative routes using them.
Examples given the route http://example.com/dir/one/two/three/
and your calling document being inside three/
:
"./pictures/image.png"
or just
"pictures/image.png"
Will try to find a directory named pictures
inside http://example.com/dir/one/two/three/
.
"../pictures/image.png"
Will try to find a directory named pictures
inside http://example.com/dir/one/two/
.
"/pictures/image.png"
Will try to find a directory named pictures
directly at /
or example.com
(which are the same), on the same level as directory
.
You can also use that:
client.Headers.Add(HttpRequestHeader.UserAgent, "My app.");
value
attribute (no CSS needed)Modern browsers will interpret the value
attribute and will display it as you expect. See MDN documentation.
<ol>_x000D_
<li value="3">This is item three.</li>_x000D_
<li value="50">This is item fifty.</li>_x000D_
<li value="100">This is item one hundred.</li>_x000D_
</ol>
_x000D_
Also have a look at the <ol>
article on MDN, especially the documentation for the start
and attribute.
Arrays have an indexOf
method which can be used to search for strings:
js> a = ['foo', 'bar', 'baz']
foo,bar,baz
js> a.indexOf('bar')
1
js> a.indexOf('quux')
-1
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
This is a pretty old post, but none of the answers here really answered the question in my opinion, so I hope my post will help people!
I found this solution on another question that works really well for me:
mysql -Nse 'show tables' DB_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; truncate table \`$table\`" DB_NAME; done
That will actually empty all your tables in the database DB_NAME
, and not only display the TRUNCATE
command line.
Hope this helps!
The smallest change to fix this would be to change
onClick="document.getElementById("datepicker").click()">
to
onClick="$('#datepicker').click()">
click()
is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.
In spark version >= 3 you can convert pandas dataframes to pyspark dataframe in one line
use spark.createDataFrame(pandasDF)
dataset = pd.read_csv("data/AS/test_v2.csv")
sparkDf = spark.createDataFrame(dataset);
if you are confused about spark session variable, spark session is as follows
sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]"))
spark = SparkSession \
.builder \
.getOrCreate()
I think the easiest would be to create a Number
object with the string and check if with the help of isInteger
function provided by Number
class itself.
Number.isInteger(Number('1')) //true
Number.isInteger(Number('1 mango')) //false
Number.isInteger(Number(1)) //true
Number.isInteger(Number(1.9)) //false
Just came across the same issue today...
In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:
list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)
Read This: 1.2 Date
and Time Datatype
best data type to store date and time is:
TEXT
best format is: yyyy-MM-dd HH:mm:ss
Then read this page; this is best explain about date and time in SQLite
.
I hope this help you
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.
http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/
The quick summary is: recursion that passes through the host global object is limited to a stack depth of 13. In other words, if the reference your function call is using (not necessarily the function itself) was defined with some form window.foo = function, then recursing through foo is limited to a depth of 13.
I use this to get rid of invalid characters in filenames without throwing exceptions:
private static readonly Regex InvalidFileRegex = new Regex(
string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*")));
public static string SanitizeFileName(string fileName)
{
return InvalidFileRegex.Replace(fileName, string.Empty);
}
This worked for me on Ubuntu 12.04.
pip install --index-url=https://pypi.python.org/simple/ -U scikit-learn
Add the indent
parameter to json.dumps
data = {'this': ['has', 'some', 'things'],
'in': {'it': 'with', 'some': 'more'}}
print(json.dumps(data, indent=4))
Also note that, you can simply use json.dump
with the open jsonfile
:
json.dump(data, jsonfile)
If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:
<object data="your_url_to_pdf" type="application/pdf">
<iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>
The advice to use Graphviz is good: you can generate the dot file and it will do the hard work of measuring strings, doing the layout, etc. Plus it can output the graphs in lot of formats, including vector ones.
I found a Perl program doing precisely that, in a mailing list, but I just can't find it back! I copied the sample dot file and studied it, since I don't know much of this declarative syntax and I wanted to learn a bit more.
Problem: with latest Graphviz, I have errors (or rather, warnings, as the final diagram is generated), both in the original graph and the one I wrote (by hand). Some searches shown this error was found in old versions and disappeared in more recent versions. Looks like it is back.
I still give the file, maybe it can be a starting point for somebody, or maybe it is enough for your needs (of course, you still have to generate it).
digraph tree
{
rankdir=LR;
DirTree [label="Directory Tree" shape=box]
a_Foo_txt [shape=point]
f_Foo_txt [label="Foo.txt", shape=none]
a_Foo_txt -> f_Foo_txt
a_Foo_Bar_html [shape=point]
f_Foo_Bar_html [label="Foo Bar.html", shape=none]
a_Foo_Bar_html -> f_Foo_Bar_html
a_Bar_png [shape=point]
f_Bar_png [label="Bar.png", shape=none]
a_Bar_png -> f_Bar_png
a_Some_Dir [shape=point]
d_Some_Dir [label="Some Dir", shape=ellipse]
a_Some_Dir -> d_Some_Dir
a_VBE_C_reg [shape=point]
f_VBE_C_reg [label="VBE_C.reg", shape=none]
a_VBE_C_reg -> f_VBE_C_reg
a_P_Folder [shape=point]
d_P_Folder [label="P Folder", shape=ellipse]
a_P_Folder -> d_P_Folder
a_Processing_20081117_7z [shape=point]
f_Processing_20081117_7z [label="Processing-20081117.7z", shape=none]
a_Processing_20081117_7z -> f_Processing_20081117_7z
a_UsefulBits_lua [shape=point]
f_UsefulBits_lua [label="UsefulBits.lua", shape=none]
a_UsefulBits_lua -> f_UsefulBits_lua
a_Graphviz [shape=point]
d_Graphviz [label="Graphviz", shape=ellipse]
a_Graphviz -> d_Graphviz
a_Tree_dot [shape=point]
f_Tree_dot [label="Tree.dot", shape=none]
a_Tree_dot -> f_Tree_dot
{
rank=same;
DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]
}
{
rank=same;
d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]
}
{
rank=same;
d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]
}
{
rank=same;
d_Graphviz -> a_Tree_dot [arrowhead=none]
}
}
> dot -Tpng Tree.dot -o Tree.png
Error: lost DirTree a_Foo_txt edge
Error: lost a_Foo_txt a_Foo_Bar_html edge
Error: lost a_Foo_Bar_html a_Bar_png edge
Error: lost a_Bar_png a_Some_Dir edge
Error: lost a_Some_Dir a_Graphviz edge
Error: lost d_Some_Dir a_VBE_C_reg edge
Error: lost a_VBE_C_reg a_P_Folder edge
Error: lost a_P_Folder a_UsefulBits_lua edge
Error: lost d_P_Folder a_Processing_20081117_7z edge
Error: lost d_Graphviz a_Tree_dot edge
I will try another direction, using Cairo, which is also able to export a number of formats. It is more work (computing positions/offsets) but the structure is simple, shouldn't be too hard.
Here's another sample using JQuery 1.10.2
$(".chkcc9").on('click', function() {
$(this)
.parents('table')
.find('.group1')
.prop('checked', $(this).is(':checked'));
});
layout.setBackgroundResource(R.drawable.ready);
is correct.
Another way to achieve it is to use the following:
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}
But I think the problem occur because you are trying to load big images.
Here is a good tutorial how to load large bitmaps.
UPDATE:
getDrawable(int ) deprecated in API level 22
getDrawable(int )
is now deprecated in API level 22.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, R.drawable.ready)
If you refer to the source code of ContextCompat.getDrawable, it gives you something like this:
/**
* Return a drawable object associated with a particular resource ID.
* <p>
* Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
* drawable will be styled for the specified Context's theme.
*
* @param id The desired resource identifier, as generated by the aapt tool.
* This integer encodes the package, type, and resource entry.
* The value 0 is an invalid identifier.
* @return Drawable An object that can be used to draw this resource.
*/
public static final Drawable getDrawable(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 21) {
return ContextCompatApi21.getDrawable(context, id);
} else {
return context.getResources().getDrawable(id);
}
}
More details on ContextCompat
As of API 22, you should use the getDrawable(int, Theme)
method instead of getDrawable(int).
UPDATE:
If you are using the support v4 library, the following will be enough for all versions.
ContextCompat.getDrawable(context, R.drawable.ready)
You will need to add the following in your app build.gradle
compile 'com.android.support:support-v4:23.0.0' # or any version above
Or using ResourceCompat, in any API like below:
import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);
This solution no longer works with FaceBook's current API (seems it was unintended to begin with)
http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com;
Try to give this link on you signout link or button where "yoursitename.com" is where u want to redirect back after signout may be ur home page.
It works..