I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
From access help:
Stop Disabled Mode from blocking a query If you try to run an append query and it seems like nothing happens, check the Access status bar for the following message:
This action or event has been blocked by Disabled Mode.
To stop Disabled Mode from blocking the query, you must enable the database content. You use the Options button in the Message Bar to enable the query.
Enable the append query In the Message Bar, click Options. In the Microsoft Office Security Options dialog box, click Enable this content, and then click OK. If you don't see the Message Bar, it may be hidden. You can show it, unless it has also been disabled. If the Message Bar has been disabled, you can enable it.
Show the Message Bar If the Message Bar is already visible, you can skip this step.
On the Database Tools tab, in the Show/Hide group, select the Message Bar check box. If the Message Bar check box is disabled, you will have to enable it.
Enable the Message Bar If the Message Bar check box is enabled, you can skip this step.
Click the Microsoft Office Button , and then click Access Options. In the left pane of the Access Options dialog box, click Trust Center. In the right pane, under Microsoft Office Access Trust Center, click Trust Center Settings. In the left pane of the Trust Center dialog box, click Message Bar. In the right pane, click Show the Message Bar in all applications when content has been blocked, and then click OK. Close and reopen the database to apply the changed setting. Note When you enable the append query, you also enable all other database content.
For more information about Access security, see the article Help secure an Access 2007 database.
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}
I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:
UPDATE FUNCTIONS A
INNER JOIN (
SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
FROM TAX BB, FUNCTIONS AA
WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
GROUP BY AA.Func_ID
) B
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code
Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:
UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
However, this still doesn't work.
I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:
UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
"MinOfTax_Code",
"FUNCTIONS_TAX",
"Func_ID = '" & Func_ID & "'"
)
Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).
Good luck!
Paste this function in your Module and use it as like formula
Public Function format_date(t As String)
format_date = Format(t, "YYYY-MM-DD")
End Function
for example in Cell A1 apply this formula
=format_date(now())
it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.
Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:
me.lstIssues.Column(4)
This saves having to use the ItemsSelected property.
Kristian
Check on yourCheckBox.Value
?
I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.
I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.
Thanks to all above though.
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
Insert this lines:
<Directory "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs">
Options +Indexes
</Directory>
In your C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\extra\httpd-vhosts.conf
file. I assume you are using Virtual Host for development.
And then, of course, just restart Apache.
I have created a library to batch delete or update records with a round trip on EF Core 5.
Sample code as follows:
await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");
await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();
Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
This way we can check for an existing file in a particular folder:
string curFile = @"c:\temp\test.txt"; //Your path
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
You can use nircmd
project here: http://www.nirsoft.net/utils/nircmd.html
Example code:
nircmd win move ititle "cmd.exe" 5 5 10 10
nircmd win setsize ititle "cmd.exe" 30 30 100 200
nircmd cmdwait 1000 win setsize ititle "cmd.exe" 30 30 1000 600
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
Edit > Advanced > View White Space. The keyboard shortcut is CTRL+R, CTRL+W. The command is called Edit.ViewWhiteSpace
.
It works in all Visual Studio versions at least since Visual Studio 2010, the current one being Visual Studio 2019 (at time of writing). In Visual Studio 2013, you can also use CTRL+E, S or CTRL+E, CTRL+S.
By default, end of line markers are not visualized. This functionality is provided by the End of the Line extension.
Don't type python test.py
from inside the Python interpreter. Type it at the command prompt, like so:
Those who still have the problem with onAttach(Activity activity), Its just changed to Context -
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity a; //Your activity class - will probably be a global var.
if (context instanceof mActivity){
a=(mActivity) context;
}
}
As suggested by user1868713.
Add this key in plist file...Everything will be alright..
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Just paste before </dict></plist>
On my AIX system, I tried
nohup -p processid>
This worked well. It continued to run my process even after closing terminal windows. We have ksh as default shell so the bg
and disown
commands didn't work.
"Then" is a command in bash, thus it needs a ";" or a newline before it.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [$[fname%2] -eq 1 ]
then
echo "removing $fname\n"
rm $f
fi
done
The best way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
@NonNull
@TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
If your using the latest version of Itunes and there is no APP section Click on summary while the device is connected to you PC . Then Drag and drop the file onto the "on my device" section.
In Selenium IDE you can do:
Command | clickAndWait Target | //input[@value='Next' and @title='next']
It should work fine.
In my case, the server list was empty for Apache in "Run Configurations" when I opened
I fixed this by creating a server in the Servers Panel as in other answers:
There are only two ways:
If the memory pointer to by your char *
represents a C string (that is, it contains characters that have a 0-byte to mark its end), you can use strlen(a)
.
Otherwise, you need to store the length somewhere. Actually, the pointer only points to one char
. But we can treat it as if it points to the first element of an array. Since the "length" of that array isn't known you need to store that information somewhere.
If you're using at least Java 8, see my other answer.
If you're already using Google Guava, see Sean Patrick Floyd's answer.
If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat()
using no more than Iterable
and Iterator
:
public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
final Iterable<? extends E> iterable2) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
final Iterator<? extends E> iterator1 = iterable1.iterator();
final Iterator<? extends E> iterator2 = iterable2.iterator();
@Override
public boolean hasNext() {
return iterator1.hasNext() || iterator2.hasNext();
}
@Override
public E next() {
return iterator1.hasNext() ? iterator1.next() : iterator2.next();
}
};
}
};
}
@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
return concat(Arrays.asList(iterables));
}
public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
return new Iterable<E>() {
final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();
@Override
public Iterator<E> iterator() {
return !iterablesIterator.hasNext() ? Collections.emptyIterator()
: new Iterator<E>() {
Iterator<? extends E> iterableIterator = nextIterator();
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public E next() {
final E next = iterableIterator.next();
findNext();
return next;
}
Iterator<? extends E> nextIterator() {
return iterablesIterator.next().iterator();
}
Iterator<E> findNext() {
while (!iterableIterator.hasNext()) {
if (!iterablesIterator.hasNext()) {
break;
}
iterableIterator = nextIterator();
}
return this;
}
}.findNext();
}
};
}
What about this trick...
ls -lrt -d -1 $PWD/{*,.*}
OR
ls -lrt -d -1 $PWD/*
I think this has problems with empty directories but if another poster has a tweak I'll update my answer. Also, you may already know this but this is probably be a good candidate for an alias given it's lengthiness.
[update] added some tweaks based on comments, thanks guys.
[update] as pointed out by the comments you may need to tweek the matcher expressions depending on the shell (bash vs zsh). I've re-added my older command for reference.
There is an article talk about this: http://weblog.invasivecode.com/post/42362079291/auto-layout-and-core-animation-auto-layout-was
In which, he coded like this:
- (void)handleTapFrom:(UIGestureRecognizer *)gesture {
if (_isVisible) {
_isVisible = NO;
self.topConstraint.constant = -44.; // 1
[self.navbar setNeedsUpdateConstraints]; // 2
[UIView animateWithDuration:.3 animations:^{
[self.navbar layoutIfNeeded]; // 3
}];
} else {
_isVisible = YES;
self.topConstraint.constant = 0.;
[self.navbar setNeedsUpdateConstraints];
[UIView animateWithDuration:.3 animations:^{
[self.navbar layoutIfNeeded];
}];
}
}
Hope it helps.
On a Fedora 18 with Mongo 2.2.4 instance I was able to get around a similar error by disabling SELinux by calling setenforce 0
as root.
BTW, this was a corporate environment, not an Amazon EC2 instance, but the symptoms were similar.
For SharePoint 2016
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2013
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2010
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs
For SharePoint 2007
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs
Note: The sharePoint Trace log path can be changed by opening Central Administration > Monitoring > Reporting > Configure Diagnostic Logs
For more details check SHAREPOINT ULS VIEWER
If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib
If you are on a Mac or BSD or something else without the --date option, you can use:
date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'
Update: or perhaps...
date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'
I had the same problem. I decided in a very unexpected way. Just opened the command line as an administrator. And then typed:
pip install numpy
The functionality, you described, can be easily achieved using the Bootstrap tooltip.
<button id="example1" data-toggle="tooltip">Tooltip on left</button>
Then call tooltip() function for the element.
$('#example1').tooltip();
I have used in this way.. Working fine!
$inputs = request()->validate([
'name' => 'required | min:6 | max: 20',
'email' => 'required',
'password' => 'required| min:4| max:7 |confirmed',
'password_confirmation' => 'required| min:4'
]);
You can target the first child element with just using CSS selector with jQuery:
$(this).children('img:nth-child(1)');
If you want to target the second child element just change 1 to 2:
$(this).children('img:nth-child(2)');
and so on..
if you want to target more elements, you can use a for loop:
for (i = 1; i <= $(this).children().length; i++) {
let childImg = $(this).children("img:nth-child("+ i +")");
// Do stuff...
}
Haven't tried, but maybe hijacking the DNS resolution process by adding a line in /etc/hosts
for hub.docker.com
or something similar (docker.io
?) could work?
<kdb></kdb>
is required when we have a space in Alias Name like
SELECT employee_id,department_id AS "Department ID"
FROM employees
order by department
This is a generic solution for your problem and others related.
1. Create auxiliar class UIHelper and put on the following methods:
/**This method returns top view controller in application */
class func topViewController() -> UIViewController?
{
let helper = UIHelper()
return helper.topViewControllerWithRootViewController(rootViewController: UIApplication.shared.keyWindow?.rootViewController)
}
/**This is a recursive method to select the top View Controller in a app, either with TabBarController or not */
private func topViewControllerWithRootViewController(rootViewController:UIViewController?) -> UIViewController?
{
if(rootViewController != nil)
{
// UITabBarController
if let tabBarController = rootViewController as? UITabBarController,
let selectedViewController = tabBarController.selectedViewController {
return self.topViewControllerWithRootViewController(rootViewController: selectedViewController)
}
// UINavigationController
if let navigationController = rootViewController as? UINavigationController ,let visibleViewController = navigationController.visibleViewController {
return self.topViewControllerWithRootViewController(rootViewController: visibleViewController)
}
if ((rootViewController!.presentedViewController) != nil) {
let presentedViewController = rootViewController!.presentedViewController;
return self.topViewControllerWithRootViewController(rootViewController: presentedViewController!);
}else
{
return rootViewController
}
}
return nil
}
2. Create a Protocol with your desire behavior, for your specific case will be portrait.
protocol orientationIsOnlyPortrait {}
Nota: If you want, add it in the top of UIHelper Class.
3. Extend your View Controller
In your case:
class Any_ViewController: UIViewController,orientationIsOnlyPortrait {
....
}
4. In app delegate class add this method:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
let presentedViewController = UIHelper.topViewController()
if presentedViewController is orientationIsOnlyPortrait {
return .portrait
}
return .all
}
Final Notes:
If you need to store a password in memory and would like to have it encrypted you should use SecureString:
http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx
For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx
Have you checked that those classes are present in the CSS? Are you using twitter-bootstrap-rails gem? It still uses Bootstrap 2.X version and those are Bootstrap 3.X classes. The CSS grid changed since.
You can switch to the bootstrap3 branch of the gem https://github.com/seyhunak/twitter-bootstrap-rails/tree/bootstrap3 or include boostrap in an alternative way.
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
This may be late, but an extension that works for value and reference types alike based on Eric's answer:
public static partial class Extensions
{
public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null) where T : struct, IComparable
{
object first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (comparer != null && !comparer.Equals(first, item))
return other;
else if (!first.Equals(item))
return other;
}
return (Nullable<T>)first ?? other;
}
public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null) where T : class, IComparable
{
object first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (comparer != null && !comparer.Equals(first, item))
return other;
else if (!first.Equals(item))
return other;
}
return (T)first ?? other;
}
}
Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:
[x * 0.1 for x in range(0, 10)]
(Replace the call to range with that expression.)
For the more general case, you may want to write a custom function or generator.
You can either give class name to all label so that all can have same width :
.class-name { width:200px;}
Example
.labelname{ width:200px;}
or you can simple give rest of label
label { width:200px; display: inline-block;}
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
There are two ways you could approach this better:
Pass a dictionary (associative array) if you want to leave a lot of flexibility
Take an object as the argument and use prototype based inheritance to add flexibility.
\n
is Unix, \r
is Mac, \r\n
is Windows.
Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine
.
Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading
It seems like You haven't set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it. Thank you. Happy learning!
The typeof
operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof
is an operator, not a function. Despite this, you will see typeof(var)
being used a lot in the wild. This makes as much sense as var a = 4 + (1)
.
Also, you may as well use ==
(equality comparison operator) since both operands are String
s (typeof
always returns a String
), JavaScript is defined to perform the same steps had I used ===
(strict comparison operator).
As Box9 mentions, this won't detect a instantiated String
object.
You can detect for that with....
var isString = str instanceof String;
...or...
var isString = str.constructor == String;
But this won't work in a multi window
environment (think iframe
s).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
But again, (as Box9 mentions), you are better off just using the literal String
format, e.g. var str = 'I am a string';
.
Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:
[x for b in a for x in b]
to get the desired result, and yes, one current value can be the iterator for the next loop.
According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras
you can do :
first test if you have h5py installed by running the
import h5py
if you dont have errors while importing h5py you are good to save:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
If you need to install h5py http://docs.h5py.org/en/latest/build.html
You could better use the localStorage of the web browser.
You can find a reference here
cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.
<?php
// Step 1
$cSession = curl_init();
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?>
Step 1: Initialize a curl session using curl_init()
.
Step 2: Set option for CURLOPT_URL
. This value is the URL which we are sending the request to. Append a search term curl
using parameter q=
. Set option for CURLOPT_RETURNTRANSFER
. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER
, false will tell curl to ignore the header in the return value.
Step 3: Execute the curl session using curl_exec()
.
Step 4: Close the curl session we have created.
Step 5: Output the return string.
public function curlCall($apiurl, $auth, $rflag)
{
$ch = curl_init($apiurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($auth == 'auth') {
curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
} else {
curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$dt = curl_exec($ch);
curl_close($ch);
if($rflag != 1) {
$dt = json_decode($dt,true);
}
return $dt;
}
This is also used for authentication. We can also set the username and password for authentication.
For more functionality, see the user manual or the following tutorial:
http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl
Here is a way to change the owner on ALL DBS (excluding System)
EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
exec sp_changedbowner ''sa''
END
'
Check out yowsup
https://github.com/tgalal/yowsup
Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.
A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.
Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.
If you can add the second server to cluster, you may do this:
This will only work if number of replaces equal to number of nodes.
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
Assuming ASCII strings:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:
for index, this in enumerate(mylist):
for that in mylist[index+1:]:
compare(this, that)
This is my code for show dynamics tooltips with delay and loaded by ajax.
$(window).on('load', function () {_x000D_
generatePopovers();_x000D_
_x000D_
$.fn.dataTable.tables({ visible: true, api: true }).on('draw.dt', function () {_x000D_
generatePopovers();_x000D_
});_x000D_
});_x000D_
_x000D_
$(document).ajaxStop(function () {_x000D_
generatePopovers();_x000D_
});
_x000D_
function generatePopovers() {_x000D_
var popover = $('a[href*="../Something.aspx"]'); //locate the elements to popover_x000D_
_x000D_
popover.each(function (index) {_x000D_
var poplink = $(this);_x000D_
if (poplink.attr("data-toggle") == null) {_x000D_
console.log("RENDER POPOVER: " + poplink.attr('href'));_x000D_
poplink.attr("data-toggle", "popover");_x000D_
poplink.attr("data-html", "true");_x000D_
poplink.attr("data-placement", "top");_x000D_
poplink.attr("data-content", "Loading...");_x000D_
poplink.popover({_x000D_
animation: false,_x000D_
html: true,_x000D_
trigger: 'manual',_x000D_
container: 'body',_x000D_
placement: 'top'_x000D_
}).on("mouseenter", function () {_x000D_
var thispoplink = poplink;_x000D_
setTimeout(function () {_x000D_
if (thispoplink.is(":hover")) {_x000D_
thispoplink.popover("show");_x000D_
loadDynamicData(thispoplink); //load data by ajax if you want_x000D_
$('body .popover').on("mouseleave", function () {_x000D_
thispoplink.popover('hide');_x000D_
});_x000D_
}_x000D_
}, 1000);_x000D_
}).on("mouseleave", function () {_x000D_
var thispoplink = poplink;_x000D_
setTimeout(function () {_x000D_
if (!$("body").find(".popover:hover").length) {_x000D_
thispoplink.popover("hide");_x000D_
}_x000D_
}, 100);_x000D_
});_x000D_
}_x000D_
});
_x000D_
function loadDynamicData(popover) {_x000D_
var params = new Object();_x000D_
params.somedata = popover.attr("href").split("somedata=")[1]; //obtain a parameter to send_x000D_
params = JSON.stringify(params);_x000D_
//check if the content is not seted_x000D_
if (popover.attr("data-content") == "Loading...") {_x000D_
$.ajax({_x000D_
type: "POST",_x000D_
url: "../Default.aspx/ObtainData",_x000D_
data: params,_x000D_
contentType: "application/json; charset=utf-8",_x000D_
dataType: 'json',_x000D_
success: function (data) {_x000D_
console.log(JSON.parse(data.d));_x000D_
var dato = JSON.parse(data.d);_x000D_
if (dato != null) {_x000D_
popover.attr("data-content",dato.something); // here you can set the data returned_x000D_
if (popover.is(":hover")) {_x000D_
popover.popover("show"); //use this for reload the view_x000D_
}_x000D_
}_x000D_
},_x000D_
_x000D_
failure: function (data) {_x000D_
itShowError("- Error AJAX.<br>");_x000D_
}_x000D_
});_x000D_
}_x000D_
}
_x000D_
paint.setStrokeWidth(3);
paint.setColor(BLACK);
and either one of your drawRect
should work.
Did you notice your typo, $car2
instead of #car2
?
Anyway, :hidden
seems to be working as expected, try it here.
If you want to use for <input>
it will not work, for <input>
or text area you need to use Javascript
<script language="javascript" type="text/javascript">
function capitaliseName()
{
var str = document.getElementById("name").value;
document.getElementById("name").value = str.charAt(0).toUpperCase() + str.slice(1);
}
</script>
<textarea name="NAME" id="name" onkeydown = "capitaliseName()"></textarea>
that is supposed to work well for <input>
or <textarea>
You can use:
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.
Adjusting the background-size
is permitted. You still need to specify width and height of the block, however.
.pdflink:after {
background-image: url('/images/pdf.png');
background-size: 10px 20px;
display: inline-block;
width: 10px;
height: 20px;
content:"";
}
I wanted to get a file's modification date in YYYYMMDDHHMMSS
format. Here is how I did it:
date -d @$( stat -c %Y myfile.css ) +%Y%m%d%H%M%S
Explanation. It's the combination of these commands:
stat -c %Y myfile.css # Get the modification date as a timestamp
date -d @1503989421 +%Y%m%d%H%M%S # Convert the date (from timestamp)
This question seems to be ambiguous.
I'll try with my interpretation of the request.
def do_something(data)
puts "Found! #{data}"
end
a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }
This will loop over all the key,value pairs and do something only if the key is 'x'.
Can't you just get the size/length of the set/array, generate a random number between 0 and the size/length, then call the element whose index matches that number? HashSet has a .size() method, I'm pretty sure.
In psuedocode -
function randFromSet(target){
var targetLength:uint = target.length()
var randomIndex:uint = random(0,targetLength);
return target[randomIndex];
}
You can play with your array
$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport); // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport); // $day = 'Monday';
$day = end($transport); // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';
To get the first element of array you can use current
and for last element you can use end
Edit
Just for the sake for not getting any more down votes for the answer you can convert you key to value using array_keys
and use as shown above.
As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:
line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
i in line
>> True
>> True
In case anyone else has come here looking for an answer to this question, there's a Windows API function called GetProcessTimes()
. It doesn't look like too much work to write a little C program that would start the command, make this call, and return the process times.
Using g++, you can add the command line option: -fstack-protector-all
.
On your example it resulted in the following:
> g++ -o t -fstack-protector-all t.cc
> ./t
3
4
/bin/bash: line 1: 15450 Segmentation fault ./t
It doesn't really help you find or solve the problem, but at least the segfault will let you know that something is wrong.
Use the _ variable, as I learned when I asked this question, for example:
# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in xrange(power):
product *= num
print product
Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1
This takes the value from an unbound custom field, processes, and saves it into my real description field:
class WidgetForm(forms.ModelForm):
extra_field = forms.CharField(required=False)
def processData(self, input):
# example of error handling
if False:
raise forms.ValidationError('Processing failed!')
return input + " has been processed"
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# self.description = "my result" note that this does not work
# Get the form instance so I can write to its fields
instance = super(WidgetForm, self).save(commit=commit)
# this writes the processed data to the description field
instance.description = self.processData(extra_field)
if commit:
instance.save()
return instance
class Meta:
model = Widget
fields = "__all__"
const diff = require("deep-object-diff").diff;
let differences = diff(obj2, obj1);
There is an npm module with over 500k weekly downloads: https://www.npmjs.com/package/deep-object-diff
I like the object like representation of the differences - especially it is easy to see the structure, when it is formated.
const diff = require("deep-object-diff").diff;
const lhs = {
foo: {
bar: {
a: ['a', 'b'],
b: 2,
c: ['x', 'y'],
e: 100 // deleted
}
},
buzz: 'world'
};
const rhs = {
foo: {
bar: {
a: ['a'], // index 1 ('b') deleted
b: 2, // unchanged
c: ['x', 'y', 'z'], // 'z' added
d: 'Hello, world!' // added
}
},
buzz: 'fizz' // updated
};
console.log(diff(lhs, rhs)); // =>
/*
{
foo: {
bar: {
a: {
'1': undefined
},
c: {
'2': 'z'
},
d: 'Hello, world!',
e: undefined
}
},
buzz: 'fizz'
}
*/
No need to calculate the actual height of the contents; you can just scroll down a lot:
$(function () {
$('.messageScrollArea').scrollTop(1E10);
});
Start with a basic square and borders. Each border will be given a different color so we can tell them apart:
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 200px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
which gives you this:
But there's no need for the top border, so set its width to 0px
. Now our border-bottom of 200px
will make our triangle 200px tall.
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
and we will get this:
Then to hide the two side triangles, set the border-color to transparent. Since the top-border has been effectively deleted, we can set the border-top-color to transparent as well.
.triangle {
border-color: transparent transparent red transparent;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
finally we get this:
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Adding Allow from All
didn't worked for me. Then I tried this and it worked.
OS: Windows 8.1
Wamp : 2.5
I added this in the file C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/wamp/www/"
ServerName localhost
ServerAlias localhost
ErrorLog "logs/localhost-error.log"
CustomLog "logs/localhost-access.log" common
</VirtualHost>
What's the difference between an RDD's map and mapPartitions method?
The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).
And does flatMap behave like map or like mapPartitions?
Neither, flatMap works on a single element (as map
) and produces multiple elements of the result (as mapPartitions
).
As Fragments Version 1.3.0-alpha01
The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
I suggest that you add
#!/usr/bin/env python
instead of #!/usr/bin/python
at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env
you make sure that the system finds python and delegates the script's execution to it.
As said before to make the script executable, something like:
chmod u+x name_of_script.py
should do.
Below code will help you:
public class DeckListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
ArrayList<String> teams=new ArrayList<String>();
ArrayList<Integer> teamcolor=new ArrayList<Integer>();
public DeckListAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
teams.add("Upload");
teams.add("Download");
teams.add("Device Browser");
teams.add("FTP Browser");
teams.add("Options");
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
}
public int getCount() {
return teams.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.decklist, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
holder.text = (TextView) convertView.findViewById(R.id.textname);
.......here you can use holder.text.setonclicklistner(new View.onclick.
for each textview
System.out.println(holder.text.getText().toString());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(teams.get(position));
if(position<teamcolor.size())
holder.text.setBackgroundColor(teamcolor.get(position));
holder.icon.setImageResource(R.drawable.arraocha);
return convertView;
}
class ViewHolder {
ImageView icon;
TextView text;
}
}
Hope this helps.
Aside from the LINQ answers already given, I have a "SmartEnumerable" class which allows you to get the index and the "first/last"-ness. It's a bit ugly in terms of syntax, but you may find it useful.
We can probably improve the type inference using a static method in a nongeneric type, and implicit typing will help too.
Put your JTable
inside a JScrollPane
. Try this:
add(new JScrollPane(scrTbl));
ES6 introduces computed property names, which allows you to do
let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}
Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:
Just adding this in the hope to be of help to someone.
Same as all the answers here, but using StreamReader/StreamWriter to split on new lines (line by line, instead of trying to read the whole file into memory at once). This approach can split big files in the fastest way I know of.
Note: I do very little error checking, so I can't guarantee it'll work smoothly for your case. It did for mine (1.7 GB TXT file of 4 million lines split in 100,000 lines per file in 95 seconds).
#split test
$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
$filename = "C:\Users\Vincent\Desktop\test.txt"
$rootName = "C:\Users\Vincent\Desktop\result"
$ext = ".txt"
$linesperFile = 100000#100k
$filecount = 1
$reader = $null
try{
$reader = [io.file]::OpenText($filename)
try{
"Creating file number $filecount"
$writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
$filecount++
$linecount = 0
while($reader.EndOfStream -ne $true) {
"Reading $linesperFile"
while( ($linecount -lt $linesperFile) -and ($reader.EndOfStream -ne $true)){
$writer.WriteLine($reader.ReadLine());
$linecount++
}
if($reader.EndOfStream -ne $true) {
"Closing file"
$writer.Dispose();
"Creating file number $filecount"
$writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
$filecount++
$linecount = 0
}
}
} finally {
$writer.Dispose();
}
} finally {
$reader.Dispose();
}
$sw.Stop()
Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"
Output splitting a 1.7 GB file:
...
Creating file number 45
Reading 100000
Closing file
Creating file number 46
Reading 100000
Closing file
Creating file number 47
Reading 100000
Closing file
Creating file number 48
Reading 100000
Split complete in 95.6308289 seconds
To add useful information to the conversation, I came across 404 errors for my bundles in the deployment (it was fine in the local dev environment).
For the bundle names, I including version numbers like such:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile.1.4.3").Include(
...
);
On a whim, I removed all the dots and all was working magically again:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile143").Include(
...
);
Hope that helps someone save some time and frustration.
You can set a tabindex to the DOM element. This will trigger a blur event when the user click outside the DOM element.
<div tabindex="1">
Focus me
</div>
document.querySelector("div").onblur = function(){
console.log('clicked outside')
}
document.querySelector("div").onfocus = function(){
console.log('clicked inside')
}
I understood what a merge conflict was, but when I saw the output of git diff
, it looked like non-sense to me at first:
git diff
++<<<<<<< HEAD
+ display full last name boolean in star table
++=======
+ users viewer.id/star.id, and conversation uses user.id
+
++>>>>>>> feat/rspec-tests-for-cancancan
But here is what helped me:
Everything between <<<<<<<
and =======
is what was in one file, and
Everything between =======
and >>>>>>>
is what was in the other file
So literally all you have to do is remove those lines from either branch (or just make them the same), and the merge
will immediately succeed. Problem solved!
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
You need to create both a URL
object and a URLConnection
object. The following code will test both the format of the URL and whether a connection can be established:
try {
URL url = new URL("http://www.yoursite.com/");
URLConnection conn = url.openConnection();
conn.connect();
} catch (MalformedURLException e) {
// the URL is not in a valid form
} catch (IOException e) {
// the connection couldn't be established
}
public ActionResult Index(int id,string value)
This function get values form URL After that you can use below function
Request.RawUrl
- Return complete URL of Current page
RouteData.Values
- Return Collection of Values of URL
Request.Params
- Return Name Value Collections
I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:
#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}
As an administrator working on other people's profile and you need to get the Id of the profile you are working on, you can use a ViewBag to capture the Id e.g ViewBag.UserId = userId; while userId is the string Parameter of the method you are working on.
[HttpGet]
public async Task<IActionResult> ManageUserRoles(string userId)
{
ViewBag.UserId = userId;
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
return View("NotFound");
}
var model = new List<UserRolesViewModel>();
foreach (var role in roleManager.Roles)
{
var userRolesViewModel = new UserRolesViewModel
{
RoleId = role.Id,
RoleName = role.Name
};
if (await userManager.IsInRoleAsync(user, role.Name))
{
userRolesViewModel.IsSelected = true;
}
else
{
userRolesViewModel.IsSelected = false;
}
model.Add(userRolesViewModel);
}
return View(model);
}
You might like this little item... It pulls the list and asks for confirmation of each item before finally deleting all selections...
git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "remove branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done`
Use -D to force deletions (like usual).
For readability, here is that broken up line by line...
git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do
read -p "remove branch: $line (y/N)?" answer </dev/tty;
case "$answer" in y|Y) echo "$line";;
esac;
done`
here is the xargs approach...
git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do
read -p "remove branch: $line (y/N)?" answer </dev/tty;
case "$answer" in
y|Y) echo "$line";;
esac;
done | xargs git branch -D
finally, I like to have this in my .bashrc
alias gitselect='git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "select branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done'
That way I can just say
gitSelect | xargs git branch -D.
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
To view the stdout, you can start the docker container with -i
. This of course does not enable you to leave the started process and explore the container.
docker start -i containerid
Alternatively you can view the filesystem of the container at
/var/lib/docker/containers/containerid/root/
However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v
switch when you use docker run
. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.
You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.
enter = datetime.time(hour=1) # Example enter time
exit = datetime.time(hour=2) # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta
difference_delta is your difference which you can use for your reasons.
As a button value is an attribute you need to use the .attr() method in jquery. This should do it
<script type="text/javascript">
$(document).ready(function() {
$('.my_button').click(function() {
alert($(this).attr("value"));
});
});
</script>
You can also use attr to set attributes, more info in the docs.
This only works in JQuery 1.6+. See postpostmodern's answer for older versions.
Have a look at the ToolStrip.Items collection. It even has a find method available.
To count unique values in column, say hID
of dataframe df
, use:
len(df.hID.unique())
double myAtof ( string &num){
double tmp;
sscanf ( num.c_str(), "%lf" , &tmp);
return tmp;
}
For me it was a fresh NetCore application that was just not loading via IIS. When run standalone it was OK though.
I removed the <aspNetCore
line and then I got a normal error message from IIS saying that NetCoreModule could not be loaded. That module is required to understand this new web.config line.
The error message 0x8007000d
actually says that the web.config is malformed and that error shows up before the error loading module making this error message really crap. (and an unfortunate race condition problem)
I installed the NetCoreSDK and stopped and started IIS (restart didnt work)
The NetCore API started working via IIS as expected.
Try this in config.js
CKEDITOR.editorConfig = function( config )
{
config.enterMode = CKEDITOR.ENTER_BR;
config.shiftEnterMode = CKEDITOR.ENTER_BR;
};
Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...
First, you must enable Intel virtualization technology from the BIOS:
Second, navigate to your SDK ...\extras\intel\Hardware_Accelerated_Execution_Manager:
Then install intelhaxm-android.exe.
Note that if you can't find this file in the directory, make sure you install the package from your SDK manager:
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
Check that the application on the test device and Google Play developer console really match.
I might have a bit of a special case but it might help someone: First, I had uploaded a package to Google Play that I had created with an ant build script. Second, on the test device, I debugged the same application (or so I thought). I got the "Error while retrieving information from server. [RPC:S-7:AEC-0]", and logcat displayed:
Class not found when unmarshalling: com.google.android.finsky.billing.lightpurchase.PurchaseParams, e: java.lang.ClassNotFoundException: com.google.android.finsky.billing.lightpurchase.PurchaseParams
The problem was that in the ant script, I have aapt
command for modifying the package name. However, Eclipse does not run that command, so there was a package name mismatch between the applications in Google Play and the test device.
See Working Demo on jsFiddle: http://jsfiddle.net/qHL8Z/3/
$(function() {_x000D_
var timer = null,_x000D_
interval = 1000,_x000D_
value = 0;_x000D_
_x000D_
$("#start").click(function() {_x000D_
if (timer !== null) return;_x000D_
timer = setInterval(function() {_x000D_
$("#input").val(++value);_x000D_
}, interval);_x000D_
});_x000D_
_x000D_
$("#stop").click(function() {_x000D_
clearInterval(timer);_x000D_
timer = null_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input id="stop" type="button" value="stop" />_x000D_
<input id="start" type="button" value="start" />
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here_x000D_
</p>
_x000D_
Working with dates in javascript is always a bit of a hassle. I always end up using a library. Moment.js and XDate are both great:
Fiddle:
var $output = $('#output'),
tomorrow = moment().add('days', 1);
$('<pre />').appendTo($output).text(tomorrow);
tomorrow = new XDate().addDays(-1);
$('<pre />').appendTo($output).text(tomorrow);
?
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
An alternative to slice
is concat
, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:
var array2 = [].concat(array1);
The second method is:
var array2 = array1.concat();
Cohen (in the comments) pointed out that this latter method has better performance.
The way this works is that the concat
method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.
Lee Penkman, also in the comments, points out that if there's a chance array1
is undefined
, you can return an empty array as follows:
var array2 = [].concat(array1 || []);
Or, for the second method:
var array2 = (array1 || []).concat();
Note that you can also do this with slice
: var array2 = (array1 || []).slice();
.
Here is a simple approach:
my_string = 'abcdefg'
print(text.find('def'))
Output:
3
I the substring is not there, you will get -1. For example:
my_string = 'abcdefg'
print(text.find('xyz'))
Output:
-1
Sometimes, you might want to throw exception if substring is not there:
my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present
Output:
Traceback (most recent call last):
File "test.py", line 6, in print(text.index('xyz'))
ValueError: substring not found
I never managed to get git to work completely in Powershell. But in the git bash shell I did not have any permission related issues, and I did not need to set chmod etc... After adding the ssh to Github I was up and running.
We can create alternative of implode of in javascript:
function my_implode_js(separator,array){
var temp = '';
for(var i=0;i<array.length;i++){
temp += array[i]
if(i!=array.length-1){
temp += separator ;
}
}//end of the for loop
return temp;
}//end of the function
var array = new Array("One", "Two", "Three");
var str = my_implode_js('-',array);
alert(str);
Use XmlTextWriter
...
public static string PrintXML(string xml)
{
string result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(xml);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
string formattedXml = sReader.ReadToEnd();
result = formattedXml;
}
catch (XmlException)
{
// Handle the exception
}
mStream.Close();
writer.Close();
return result;
}
Another application for XOR
is in circuits. It is used to sum bits.
When you look at a truth table:
x | y | x^y
---|---|-----
0 | 0 | 0 // 0 plus 0 = 0
0 | 1 | 1 // 0 plus 1 = 1
1 | 0 | 1 // 1 plus 0 = 1
1 | 1 | 0 // 1 plus 1 = 0 ; binary math with 1 bit
You can notice that the result of XOR
is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND
between x and y.
x^y // is actually ~xy + ~yx
// Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).
For me, it turned out to be an Eclipse/Maven issue after switch from log4j to logback. Take a look into your .classpath
file and search for the string "log4j"
.
In my case I had the following there:
<classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-log4j12/1.7.1/slf4j-log4j12-1.7.1.jar"/>
<classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.17/log4j-1.2.17.jar" />
Removing those entries from the file (or you could regenerate it) fixed the issue.
Just want to update, that in Spring 5, as mentioned in Spring docs, Spring supports 6 scopes, four of which are available only if you use a web-aware ApplicationContext.
singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
git checkout filename
git reset --hard
might do the trick as well
DataTable dt = new DataTable();
dt.Load(reader);
int numRows= dt.Rows.Count;
Create key value pairs on the phpsh commandline like this:
php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
[foo] => bar
[pyramid] => power
)
Get the count of key value pairs:
php> echo count($offerarray);
2
Get the keys as an array:
php> echo implode(array_keys($offerarray));
foopyramid
This works me to Angular 5.2.0
sarasa.Component.ts
import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@Component({
selector: 'app-sarasa',
templateUrl: './sarasa.component.html',
styleUrls: ['./sarasa.component.scss']
})
export class Sarasa implements OnInit {
@Input()
url: string = "https://www.mmlpqtpkasjdashdjahd.com";
urlSafe: SafeResourceUrl;
constructor(public sanitizer: DomSanitizer) { }
ngOnInit() {
this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
}
sarasa.Component.html
<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>
thats all folks!!!
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all()
in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.
Hibernate uses "dialect" configuration to know which database you are using so that it can convert hibernate query to database specific query.
My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
As of Python 3.8 (2018, https://docs.python.org/dev/whatsnew/3.8.html), the recommended method is still:
class CustomExceptionName(Exception):
"""Exception raised when very uncommon things happen"""
pass
Please don't forget to document, why a custom exception is neccessary!
If you need to, this is the way to go for exceptions with more data:
class CustomExceptionName(Exception):
"""Still an exception raised when uncommon things happen"""
def __init__(self, message, payload=None):
self.message = message
self.payload = payload # you could add more args
def __str__(self):
return str(self.message) # __str__() obviously expects a string to be returned, so make sure not to send any other data types
and fetch them like:
try:
raise CustomExceptionName("Very bad mistake.", "Forgot upgrading from Python 1")
except CustomExceptionName as error:
print(str(error)) # Very bad mistake
print("Detail: {}".format(error.payload)) # Detail: Forgot upgrading from Python 1
payload=None
is important to make it pickle-able. Before dumping it, you have to call error.__reduce__()
. Loading will work as expected.
You maybe should investigate in finding a solution using pythons return
statement if you need much data to be transferred to some outer structure. This seems to be clearer/more pythonic to me. Advanced exceptions are heavily used in Java, which can sometimes be annoying, when using a framework and having to catch all possible errors.
There is no such thing in python like forward declaration. You just have to make sure that your function is declared before it is needed. Note that the body of a function isn't interpreted until the function is executed.
Consider the following example:
def a():
b() # won't be resolved until a is invoked.
def b():
print "hello"
a() # here b is already defined so this line won't fail.
You can think that a body of a function is just another script that will be interpreted once you call the function.
You can use the RelativeLayout
.
I know this is an old thread but I thought I'd also make a contribution. My solution being similar to the post already marked as an answer. Some inline JavaScript checks does the trick.
ng-click="form.$invalid ? alert('Please correct the form') : saveTask(task)"
The file extension may be case sentive...but the code works.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Dev\"
Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "pdf" Then
Wscript.Echo objFile.Name
End If
Next
Wscript.Echo
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
Wscript.Echo
ShowSubFolders Subfolder
Next
End Sub
This works because Integer::min
resolves to an implementation of the Comparator<Integer>
interface.
The method reference of Integer::min
resolves to Integer.min(int a, int b)
, resolved to IntBinaryOperator
, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>
.
And the min()
resp max()
methods of the Stream<Integer>
ask the Comparator<Integer>
interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2)
. Which is of type BinaryOperator<Integer>
.
And thus the magic has happened as both methods are a BinaryOperator<Integer>
.
This solution is the combination of @Peter's solution for deleting multiple occurences and @chyno solution for removing first occurence. That's it what I'm using.
/**
* @param array $haystack
* @param mixed $value
* @param bool $only_first
* @return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
You can use CSS to do it for example
<style>
html{
width:100%;
height:100%;
}
body{
width:100%;
height:100%;
background-color:#DDD;
}
</style>
targetList = list1.Concat(list2).ToList();
It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly.
The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID
var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
.Select(group => new { GroupID = group.Key, Customers = group.ToList() })
.ToList();
JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.
mycombo.addItem("Hello Nepal"); //Adds data to the JComboBox.
String s=String.valueOf(mycombo.getSelectedItem()); //Assigns "Hello Nepal" to s.
System.out.println(s); //Prints "Hello Nepal".
This should work:
System.currentTimeMillis();
You need to somehow create a table with these values and then use NOT IN
. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):
SELECT email
FROM
( VALUES
('email1')
, ('email2')
, ('email3')
) AS Checking (email)
WHERE email NOT IN
( SELECT email
FROM Users
)
The second result can be found with a LEFT JOIN
or an EXISTS
subquery:
SELECT email
, CASE WHEN EXISTS ( SELECT *
FROM Users u
WHERE u.email = Checking.email
)
THEN 'Exists'
ELSE 'Not exists'
END AS status
FROM
( VALUES
('email1')
, ('email2')
, ('email3')
) AS Checking (email)
I used AppBarLayout
and custom ImageButton
do to so.
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp"
android:background="@android:color/transparent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:src="@drawable/selector_back_button"
android:layout_centerVertical="true"
android:layout_marginLeft="8dp"
android:id="@+id/back_button"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</RelativeLayout>
</android.support.design.widget.AppBarLayout>
My Java code:
findViewById(R.id.appbar).bringToFront();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
getSupportActionBar().setDisplayShowTitleEnabled(false);
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
use NPOI to read and write excel..it's free and open source
for exapmle
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//.....
private void button1_Click(object sender, EventArgs e)
{
HSSFWorkbook hssfwb;
using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
{
hssfwb= new HSSFWorkbook(file);
}
ISheet sheet = hssfwb.GetSheet("Arkusz1");
for (int row = 0; row <= sheet.LastRowNum; row++)
{
if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
{
MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
}
}
}
see this Stackoverflow question
You can do like this using function:
l = [34,56,78,2,3,5,6,8,45,6]
print ("The list : " + str(l))
def count_greater30(l):
count = 0
for i in l:
if i > 30:
count = count + 1.
return count
print("Count greater than 30 is : " + str(count)).
count_greater30(l)
The way to do this is to run the following command:
bundle update --source gem-name
My prompt includes:
rsync
-style user@host:pathname
for copy-paste goodnessExample:
To do this, add the following to your ~/.bashrc
:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\u@\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: ravi@boxy:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
fi
# Now build the part after git's status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'\$ '"$None"
else
PostGitPS1+="$Mag"'\$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
It might help you!!
The AngularJs code-sample
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, send to /index
$urlRouterProvider.otherwise("/login");
$stateProvider
.state('login', {
url: "/login",
templateUrl: "login.html",
controller: "LoginCheckController"
})
.state('SuccessPage', {
url: "/SuccessPage",
templateUrl: "SuccessPage.html",
//controller: "LoginCheckController"
});
});
app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);
function LoginCheckController($scope, $location) {
$scope.users = [{
UserName: 'chandra',
Password: 'hello'
}, {
UserName: 'Harish',
Password: 'hi'
}, {
UserName: 'Chinthu',
Password: 'hi'
}];
$scope.LoginCheck = function() {
$location.path("SuccessPage");
};
$scope.go = function(path) {
$location.path("/SuccessPage");
};
}
Given answers is for capitalize the first letter of one word only. use following code to capitalize a whole string.
public static void main(String[] args) {
String str = "this is a random string";
StringBuilder capitalizedString = new StringBuilder();
String[] splited = str.trim().split("\\s+");
for (String string : splited) {
String s1 = string.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + string.substring(1);
capitalizedString.append(nameCapitalized);
capitalizedString.append(" ");
}
System.out.println(capitalizedString.toString().trim());
}
output :
This Is A Random String
The following should work in an angular CLI 6 project. I.e if you are getting:
get/set have been deprecated in favor of the config command.
npm install node-sass --save-dev
Then (making sure you change the project name)
ng config projects.YourPorjectName.schematics.@schematics/angular:component.styleext sass
To get your default project name use:
ng config defaultProject
However: If you have migrated your project from <6 up to angular 6 there is a good chance that the config wont be there. In which case you might get:
Invalid JSON character: "s" at 0:0
Therefore a manual editing of angular.json
will be required.
You will want it to look something like this (taking note of the styleex property):
...
"projects": {
"Sassy": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {
"@schematics/angular:component": {
"styleext": "scss"
}
}
...
Seems like an overly complex schema to me. ¯_(?)_/¯
You will now have to go and change all your css/less files to be scss and update any references in components etc, but you should be good to go.
Precision is the number of significant digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38.
Scale is the number of digits to the right (positive) or left (negative) of the decimal point. The scale can range from -84 to 127.
In your case, ID with precision 6 means it won't accept a number with 7 or more significant digits.
Reference:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832
That page also has some examples that will make you understand precision and scale.
It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:
np.einsum('ij->ij', a[a[:,1].argsort(),:])
This is an overkill for two dimensions and a[a[:,1].argsort()]
would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.
Output:
[[7 0 5]
[9 2 3]
[4 5 6]]
is because your schema is already, validate before create new schema.
var mongoose = require('mongoose');
module.exports = function () {
var db = require("../libs/db-connection")();
//schema de mongoose
var Schema = require("mongoose").Schema;
var Task = Schema({
field1: String,
field2: String,
field3: Number,
field4: Boolean,
field5: Date
})
if(mongoose.models && mongoose.models.tasks) return mongoose.models.tasks;
return mongoose.model('tasks', Task);
Gitgraph.js allows to draw pretty git branches without a repository. Just write a Javascript code that configures your branches and commits and render it in browser.
var gitGraph = new GitGraph({
template: "blackarrow",
mode: "compact",
orientation: "horizontal",
reverseArrow: true
});
var master = gitGraph.branch("master").commit().commit();
var develop = gitGraph.branch("develop").commit();
master.commit();
develop.commit().commit();
develop.merge(master);
or with metro
template:
or with commit messages, authors, and tags:
Test it with JSFiddle.
Generate it with Git Grapher by @bsara.
If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.
i.e.
package main
import "fmt"
import "time"
func main() {
go heartBeat()
time.Sleep(time.Second * 5)
}
func heartBeat() {
for range time.Tick(time.Second * 1) {
fmt.Println("Foo")
}
}
Python 3.x Update
From Eli Bendersky answer:
Python 3 removed dict.iteritems use dict.items instead. See Python wiki: https://wiki.python.org/moin/Python3.0
from collections import defaultdict
dd = defaultdict(list)
for d in (d1, d2):
for key, value in d.items():
dd[key].append(value)
This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump
:
objdump -d program
This should give you its dissassembly. You can add -S
if you want it source-annotated.
First you are trying to write to the innerHTML of the input field. This will not work. You need to have a div or span to write to. Try something like:
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<div id="fname_error"></div>
Then change your validate function to read
if(myform.fname.value.length==0)
{
document.getElementById("fname_error").innerHTML="this is invalid name ";
}
Second, I'm always hesitant about using onBlur for this kind of thing. It is possible to submit a form without exiting the field (e.g. return key) in which case your validation code will not be executed. I prefer to run the validation from the button that submits the form and then call the submit() from within the function only if the document has passed validation.
Alternatively:
public static T Cast<T>(this dynamic obj) where T:class
{
return obj as T;
}
You don't need a FK, you can join arbitrary columns.
But having a foreign key ensures that the join will actually succeed in finding something.
Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.
For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.
Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)
in Visual studio 2010 (VB NET)i try the following and works fine
Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>
dim Test1 as string =<a>onother multiline example</a>
They are equivalent, from the standard (emphasis mine) (7.1.3.2):
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Expanding on Brian Camire's Answer:
Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
with CTRL+SHIFT+ENTER
will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:
=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))
Don't forget to press CTRL+SHIFT+ENTER
to treat the formula as an "array formula".
Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check
You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -
In my case, with GitHub Desktop for Windows (as of June 2, 2016) & Android Studio 2.1:
This folder ->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\
Contained a BATCH file called something like 'post-install.bat'. Run this file to create a folder 'cmd' with 'git.exe' inside.
This path-->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\cmd\git.exe
would be the location of 'git.exe' after running the post-install script.
If you really mean any and ASCII (not e.g. all Unicode characters):
xxx[\x00-\x7F]+xxx
JavaScript example:
var re = /xxx[\x00-\x7F]+xxx/;
re.test('xxxabcxxx')
// true
re.test('xxx???xxx')
// false
I got the same error using:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
But once I added https: in the beginning of the href the error disappeared.
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
Use the value
property of the <select>
element. For example:
var value = document.getElementById('your_select_id').value;
alert(value);
$('html,body').animate({
scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)
However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:
public class MainActivity extends Activity {
private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
final TextView textIp = (TextView) findViewById(R.id.Ip);
final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.BSSID = CHIPKIT_BSSID;
wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
myWifiManager.setWifiEnabled(true);
int netID = myWifiManager.addNetwork(wifiConfiguration);
myWifiManager.enableNetwork(netID, true);
textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n'
+ myWifiManager.getWifiState() + "\n\n");
btnDoSomething.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearTextViews(textWifiManager, textIp);
}
});
btnNewScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getNewScan(myWifiManager, textWifiManager, textIp);
}
});
}
private void clearTextViews(TextView...tv) {
for(int i = 0; i<tv.length; i++){
tv[i].setText("");
}
}
public void getNewScan(WifiManager wm, TextView...textViews) {
wm.startScan();
List<ScanResult> scanResult = wm.getScanResults();
String scan = "";
for (int i = 0; i < scanResult.size(); i++) {
scan += (scanResult.get(i).toString() + "\n\n");
}
textViews[0].setText(scan);
textViews[1].setText(wm.toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...
and my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Hope that helps!
There are a couple of tests using the URL constructor which do not delineate whether the input is a string or URL object.
// Testing whether something is a URL
function isURL(url) {
return toString.call(url) === "[object URL]";
}
// Testing whether the input is both a string and valid url:
function isUrl(url) {
try {
return toString.call(url) === "[object String]" && !!(new URL(url));
} catch (_) {
return false;
}
}
In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.
Well, I have made it work my way by changing the JavaScript file version each time the page loads by adding a random number to JavaScript file version as follows:
// Add it to the top of the page
<?php
srand();
$random_number = rand();
?>
Then apply the random number to the JavaScript version as follow:
<script src="file.js?version=<?php echo $random_number;?>"></script>
You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat
into scope before you can create the local variable in main
. I recommend that you move the definition of the type Cat
to a header and include it from the translation unit that has main
.
Overall just add display:block; to your span. You can leave your html unchanged.
You can do it with the following css:
p {
font-size:24px;
font-weight: 300;
-webkit-font-smoothing: subpixel-antialiased;
margin-top:0px;
}
p span {
font-size:16px;
font-style: italic;
margin-top:20px;
padding-left:10px;
display:inline-block;
}
The default port 1433 is used when there is only one SQL Server named instance running on the computer.
When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
You can use .length
, like this:
var count = $("ul li").length;
.length
tells how many matches the selector found, so this counts how many <li>
under <ul>
elements you have...if there are sub-children, use "ul > li"
instead to get only direct children. If you have other <ul>
elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li"
.
In other situations where you don't know the child type, you can use the *
(wildcard) selector, or .children()
, like this:
var count = $(".parentSelector > *").length;
or:
var count = $(".parentSelector").children().length;
In case of Windows(in my case XP):-
The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function() {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function() {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run
, config
, service
, factory
, etc..), which are more professional.In this function you don't even have to inject that by yourself like
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
you can use it, as you know.
If you are using read only input field, you can use ng-value with filter.
for example:
ng-value="price | number:8"
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
In your strings.xml file you can use any Unicode sign you want.
For example, the Unicode number for percent sign is 0025:
<string name="percent_sign">%</string>
You can see a comprehensive list of Unicode signs here
The easy way to handle this (and best HTML solution to boot) is to set up classes that have the styles you want to use. Then it's a simple matter of using addClass() and removeClass(), or even toggleClass().
$('#voltaic_holder').addClass('shiny').removeClass('dull');
or even
$('#voltaic_holder').toggleClass('shiny dull');
Here is a Node.js implementation that is likely to bit.ly. generate a highly random seven-character string.
It uses Node.js crypto to generate a highly random 25 charset rather than randomly selecting seven characters.
var crypto = require("crypto");
exports.shortURL = new function () {
this.getShortURL = function () {
var sURL = '',
_rand = crypto.randomBytes(25).toString('hex'),
_base = _rand.length;
for (var i = 0; i < 7; i++)
sURL += _rand.charAt(Math.floor(Math.random() * _rand.length));
return sURL;
};
}
You are not printing the array, you are printing the value of temp
- which is only half the array...
Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.
Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it.
Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?
Two one liners - I suspect the first one is faster but second one is prettier and unlike end()
and array_pop()
, you can pass the result of a function directly to current()
without generating any notice or warning since it doesn't move the pointer or alter the array.
$var = 'http://www.vimeo.com/1234567';
// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0));
// VERSION 2 - explode, reverse the array, get the first index.
echo current(array_reverse(explode('/',$var)));
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
I used:
git reset --hard
I lost some changes, but this is ok.
As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:
# Read in the file
filedata = None
with file = open('file.txt', 'r') :
filedata = file.read()
# Replace the target string
filedata.replace('ram', 'abcd')
# Write the file out again
with file = open('file.txt', 'w') :
file.write(filedata)`
But this code WILL work (I've tested it):
f = open(filein,'r')
filedata = f.read()
f.close()
newdata = filedata.replace("old data","new data")
f = open(fileout,'w')
f.write(newdata)
f.close()
Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.
it's easy to rewrite this code in C#...
This method works if your value it's between 2 substrings !
for example:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
calls should be:
myNameValue = SplitStringByASubstring(stringContent , "[myName]")
colorValue = SplitStringByASubstring(stringContent , "[color]")
etcValue = SplitStringByASubstring(stringContent , "[etc]")