use the "maxlength" attribute as others have said.
if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript
Update in 2018: I just got some points for this old answer, and just wanted to add that the best solution would be to make the operation idempotent so that duplicate submissions are harmless.
Eg, if the form creates an order, put a unique ID in the form. The first time the server sees an order creation request with that id, it should create it and respond "success". Subsequent submissions should also respond "success" (in case the client didn't get the first response) but shouldn't change anything.
Duplicates should be detected via a uniqueness check in the database to prevent race conditions.
I think that your problem is this line:
$('input').attr('disabled','disabled');
You're disabling ALL the inputs, including, I'd guess, the ones whose data the form is supposed to submit.
To disable just the submit button(s), you could do this:
$('button[type=submit], input[type=submit]').prop('disabled',true);
However, I don't think IE will submit the form if even those buttons are disabled. I'd suggest a different approach.
We just solved this problem with the following code. The trick here is using jQuery's data()
to mark the form as already submitted or not. That way, we don't have to mess with the submit buttons, which freaks IE out.
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
Use it like this:
$('form').preventDoubleSubmission();
If there are AJAX forms that should be allowed to submit multiple times per page load, you can give them a class indicating that, then exclude them from your selector like this:
$('form:not(.js-allow-double-submission)').preventDoubleSubmission();
Can you please test this structure. If I remember correct you can use it this way:
{
"applesRequest": {
"applesDO": [
{
"apple": "Green Apple"
},
{
"apple": "Red Apple"
}
]
}
}
Second, please add default constructor to each class it also might help.
Here is another variation for a file upload that has a nicer looking bootstrap button than the default file upload browse button. This is the html:
<div class="form-group">
@Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "col-md-2 control-label" })
<div class="col-md-1 btn btn-sn btn-primary" id="browseButton" onclick="$(this).parent().find('input[type=file]').click();">browse</div>
<div class="col-md-7">
<input id="fileSpace" name="uploaded_file" type="file" style="display: none;"> @*style="display: none;"*@
@Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control", @id = "modelField"} })
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
</div>
Here is the script:
$('#fileSpace').on("change", function () {
$("#modelField").val($('input[name="uploaded_file"]').val());
fix json values, it's add \ before u{xxx} to all +" "
$item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
$matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
$matches[2] = preg_replace('/(")/', '"', $matches[2]);
$matches[2] = json_decode('"' . $matches[2] . '"');
return '"' . $matches[1] . '":"' . $matches[2] . '",';
}, $item);
I'd just make a small change to @NoDisplayName's answer and use QUOTENAME()
on the TABLE_NAME
column and also include the TABLE_SCHEMA
column encase the tables aren't in the dbo
schema.
DECLARE @sql nvarchar(max) = '';
SELECT @sql += 'DROP TABLE ' + QUOTENAME([TABLE_SCHEMA]) + '.' + QUOTENAME([TABLE_NAME]) + ';'
FROM [INFORMATION_SCHEMA].[TABLES]
WHERE [TABLE_TYPE] = 'BASE TABLE';
EXEC SP_EXECUTESQL @sql;
Or using sys
schema views (as per @swasheck's comment):
DECLARE @sql nvarchar(max) = '';
SELECT @sql += 'DROP TABLE ' + QUOTENAME([S].[name]) + '.' + QUOTENAME([T].[name]) + ';'
FROM [sys].[tables] AS [T]
INNER JOIN [sys].[schemas] AS [S] ON ([T].[schema_id] = [S].[schema_id])
WHERE [T].[type] = 'U' AND [T].[is_ms_shipped] = 0;
EXEC SP_EXECUTESQL @sql;
mongo.exe
db.test.save({Field:'Hello mongodb'})
this command
will insert a field having name Field and value is Hello
mongodb.db.test.find()
and press enter you will find
the record that you have recently entered.Java mysteriously broke on my work PC after a security patch was pushed out to us, giving this error whenever you tried to run a Java program. Somehow the 'lib' subdirectory of the Java 7 install had vanished! It might have been related to having multiple Java versions installed simultaneously.
If you're getting this error there are basically two things that could be wrong:
1) Your Java installation is broken. If the file/directory it's complaining about doesn't exist, uninstall and reinstall the JRE and then it should be there. This fixed it for me.
2) If the files are there, your PATH is somehow incorrect or pointing at an old/broken Java install. In this case you either need to fix your PATH to point to the correct java.exe/javaw.exe, or use a fully qualified path. So instead of:
java <whatever>
Use
c:\<full path to correct JRE>\bin\java.exe <whatever>
3) If your PATH is correct and files are there and it's still failing, the path could be getting truncated because it is too long. see: Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'" .
fibo = f.fibo
references the class itself. You probably wanted fibo = f.fibo()
(note the parentheses) to make an instance of the class, after which fibo.f()
should succeed correctly.
f.fibo.f()
fails because you are essentially calling f(self, a=0)
without supplying self
; self
is "bound" automatically when you have an instance of the class.
Here is the one-liner by AbacusUtil:
String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())
Random doesn't mean it must be unique. To get unique strings, use:
N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
You forgot to call startActivity. It should look like this:
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("mobilePhone")));
context.startActivity(intent);
An intent by itself is simply an object that describes something. It doesn't do anything.
Don't forget to add the relevant permission to your manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />
The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.
I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line
now I added these two lines to copy the output dll into the two folders:
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug
$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)
My database was larger than 500mb, I then used the following
C:\Windows>sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -d DATABASE -i C:\FILE.sql
It loaded everything including SP's
*NB: Run the cmd as Administrator
Perhaps with dataframes one of the most easy and practical solution is:
data = dplyr::mutate(data, rownum=row_number())
You can also get value by name instead of id like this:
var message = $('textarea:input[name=message]').val();
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
$_POST should only get populated on POST requests. The browser usually sends GET requests. If you reached a page via POST it usually asks you if it should resend the POST data when you hit refresh. What it does is simply that - sending the POST data again. To PHP that looks like a different request although it semantically contains the same data.
I've encountered the same problem in OSX.
I've tried to replace the things like
$cfg['Servers'][$i]['usergroups'] to $cfg['Servers'][$i]['pma__usergroups']
...
It works in safari but still fails in chrome.
But the so called 'work' in safari can get the message that the features which have been modified are not in effect at all.
However, the 'work' means that I can access the dbs listed left.
I think this problem maybe a bug in the new version of XAMPP, since the #1932 problems in google is new and boomed.
You can have a try at an older version of XAMPP instead until the bug is solved.
http://sourceforge.net/projects/xampp/files/XAMPP%20Linux/5.6.12/
Hope it can help you.
There is a comment on the top answer by @RyanMann that suggests:
Store your connection strings in one config file, then reference them in other projects by
<connectionString configSource="../ProjectDir/SharedConnections.config" />
This is a fantastic suggestion!
It also works to share connection strings between App.config and Web.config files!
Anyone wanting to follow this suggestion, should head on over to this SO answer. It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.
The only caveat is that configSource
must exist in the same directory or a sub-directory. The link above explains how to use "Add as Link" to get around this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
i donot think onSaveInstanceState
is a good solution. it just use for activity which had been destoryed.
From android 3.0 the Fragmen has been manager by FragmentManager, the condition is: one activity mapping manny fragments, when the fragment is added(not replace: it will recreated) in backStack, the view will be destored. when back to the last one, it will display as before.
So i think the fragmentManger and transaction is good enough to handle it.
In lines with the answer of NoToast, you would need to have multiple versions of "your_image" in your res/drawable-ldpi,mdpi, hdpi, x-hdpi (for xtra large screens), remove match_parent and keep android: adjustViewBounds="true"
Here is a version based on the accepted answer. It fixes two problems...
I found this tool to be fast and effective for both JPG and PNG files.
private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
const int thumbnailSize = 150;
using (var image = Image.FromFile(imageFileName))
{
var imageHeight = image.Height;
var imageWidth = image.Width;
if (imageHeight > imageWidth)
{
imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
imageHeight = thumbnailSize;
}
else
{
imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
imageWidth = thumbnailSize;
}
using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
//Save off the new thumbnail
thumb.Save(thumbnailFileName);
}
return new FileInfo(thumbnailFileName);
}
Try
java -cp .:mail-1.4.1.jar JavaxMailHTML
no need to have manifest
file.
Try using this:
$(".move_to").on("click", function(e){
e.preventDefault();
$('#contactsForm').attr('action', "/test1").submit();
});
Moving the order in which you use .preventDefault()
might fix your issue. You also didn't use function(e)
so e.preventDefault();
wasn't working.
Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined
. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1
.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
First of all you should create property with employee details in the Employee
class:
public class Employee
{
public Employee()
{
EmployeeDetails = new EmployeeDetails();
EmployeeDetails.EmpID = 123;
EmployeeDetails.EmpName = "ABC";
}
public EmployeeDetails EmployeeDetails { get; set; }
}
If you don't do that, you will create instance of object in Employee
constructor and you lose reference to it.
In the XAML you should create instance of Employee
class, and after that you can assign it to DataContext
.
Your XAML should look like this:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:SampleApplication"
>
<Window.Resources>
<local:Employee x:Key="Employee" />
</Window.Resources>
<Grid DataContext="{StaticResource Employee}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
</Grid>
</Window>
Now, after you created property with employee details you should binding by using this property:
Text="{Binding EmployeeDetails.EmpID}"
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
annotation. This will remove the need to using @ResponseBody
.
ptomato's code can also be written in a cleaner manner like:
ifeq ($(TARGET_CPU),x86) TARGET_CPU_IS_X86 := 1 else ifeq ($(TARGET_CPU),x86_64) TARGET_CPU_IS_X86 := 1 else TARGET_CPU_IS_X86 := 0 endif
This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.
You can use a variety of methods, one uses Javascript window.onload function in a simple function call from a script or from the body as in the solutions above, you can also use jQuery to do this but its just a modification of Javascript...Just add Jquery to your header by pasting
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
to your head section and open another script tag where you display the alert when the DOM is ready i.e. `
<script>
$("document").ready( function () {
alert("Hello, world");
});
</script>
`
This uses Jquery to run the function but since jQuery is a Javascript framework it contains Javascript code hence the Javascript alert function..hope this helps...
But still I am not sure how it works?
Let's say an entity MyEntity
has an annotated version
property:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
On update, the field annotated with @Version
will be incremented and added to the WHERE
clause, something like this:
UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))
If the WHERE
clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException
.
Does it mean that we should declare our version field as final
No but you could consider making the setter protected as you're not supposed to call it.
In SSMS 2012 there is a documented way to delete the server name from the "Connect to Server" dialog. Now, we can remove the server name by selecting it in the dialog and pressing DELETE.
This is issue has almost driven me nut in the past. To buttress what others have said, after making sure that all the indentations on the yaml file has been corrected and the problem persist, run a 'flutter clean' command at the terminal in Android studio. As at flutter 1.9, this should fix the issue.
Here is how to do that with the last version of HTTPClient
(4.3.4)
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost target = new HttpHost("localhost", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/");
request.setConfig(config);
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, request);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}
Is this a commercial application or some hobbyist / open source software?
I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.
But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.
Do you want something like the given fiddle!
HTML
<div class="button">
<input type="button" value="TELL ME MORE" onClick="document.location.reload(true)">
</div>
CSS
.button input[type="button"] {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
display:block;
width:100%;
}
.button input[type="button"]:hover {
background-color:rgba(255,204,0,0.8);
}
Michael and yoda are both right. What you can do is use the <p>
tag, which, being a block tag, uses a bottom-margin to offset the following block, so you can do something similar to this to get bigger spacing:
<p>
A block of text.
</p>
<p>
Another block
</p>
Another alternative is to use the block <hr>
tag, with which you can explicitly define the height of the spacing.
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
POCO stands for "Plain Old CLR Object".
Uhm, you are describing dict1 == dict2
( check if boths dicts are equal )
But what your code does is all( dict1[k]==dict2[k] for k in dict1 )
( check if all entries in dict1 are equal to those in dict2 )
Archive process (using Xcode 8.3.2)
Note : If you are using creating IPA using drag-and-drop process using iTunes Mac app then this is no longer applicable for iTunes 12.7 since there is no built-in App store in iTunes 12.7.
‘Generic iOS Device
’ on device list in Xcodecmd + shift + k
as shortcut)Product
-> Archive
your projectOnce archive is succeeded this will open a window with archived project
You can validate your archive by pressing Validate
(optional step but recommended)
Now press on Export
button
Next
button.list of team for provisioning
. Select accordingly and press on ‘Choose
’ button.Export one app for all compatible devices
(recommended). If you want IPA for specific device then select the device variant from list and press on ‘Next
’ button.Summary
’ and then press on ‘Next
’ buttonexport the IPA as [App Name - Date Time]
and then press on ‘Done
’.window.opener.$("#serverMsg")
You can also use XmlConvert.ToDateString
var dateStr = "2011-03-21 13:26";
var parsedDate = XmlConvert.ToDateTime(dateStr, "yyyy-MM-dd hh:mm");
It is good to specify the date kind, the code is:
var anotherParsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
More details on different parsing options http://amir-shenodua.blogspot.ie/2017/06/datetime-parsing-in-net.html
Yes, this is possible. As previously noted by multiple users, there seems to be a problem with excel reading the correct Byte Order Mark when the file is encoded in UTF-8. With UTF-16 it does not seem to have a problem, so it is endemic to UTF-8. The solution I use for this is adding the BOM, TWICE. For this I execute the following sed command twice:
sed -I '1s/^/\xef\xbb\xbf/' *.csv
, where the wildcard can be replaced with any file name. However, this leads to a mutation of the sep= at the beginning of the .csv file. The .csv file will then open normally in excel, but with an extra row with "sep=" in the first cell. The "sep=" can also be removed in the source .csv itself, but when opening the file with VBA the delimiter should be specified:
Workbooks.Open(name, Format:=6, Delimiter:=";", Local:=True)
Format 6 is the .csv format. Set Local to true, in case there are dates in the file. If Local is not set to true the dates will be Americanized, which in some cases will corrupt the .csv format.
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
I've been trying to get this done for a large number of tables during development, and this works as a charm.
DBCC CHECKIDENT('www.newsType', RESEED, 1);
DBCC CHECKIDENT('www.newsType', RESEED);
So, you first force it to be set to 1, then you set it to the highest index of the rows present in the table. Quick and easy rest of the idex.
If you have a class file at build/com/foo/Hello.class
, you can check what java version it is compiled at using the command:
javap -v build/com/foo/Hello.class | grep "major"
Example usage:
$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
major version: 57
According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level
UPDATE:
Thank you for the quick response. open http://localhost/
opened that domain in my default browser on my Mac.
I ended up writing this alias, did the trick:
# Opens git file's localhost; ${PWD##*/} is the current directory's name
alias lcl='open "http://localhost/${PWD##*/}/"'
Thank you again!
The spring docs are great on this: 3.8.1. BeanFactory or ApplicationContext?. They have a table with a comparison, I'll post a snippet:
Bean Factory
Application Context
So if you need any of the points presented on the Application Context side, you should use ApplicationContext.
If you are using form data to upload file,in which a parameter name must be specified , you can use:
curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
You have to define public String toString()
method in your Student
class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
If you do not care about repetitive form elements with the same name, then you can do:
var data = $("form.login").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));
I am using Underscore.js here.
The easiest way is to use the create
Manager method, which creates and saves the object in a single step.
for item in items:
MyModel.objects.create(name=item.name)
I have occurred the same error look following example-
async.waterfall([function(waterCB) {
waterCB(null);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.
Cheak your function parameters Below are a correct example.
async.waterfall([function(waterCB) {
waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
Thanks
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
On Windows with Android Studio 1.5.1 : File --> Settings --> Editor --> General --> Auto Import
You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.
The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.
What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.
var arr = ['a','b',1];
var results = arr.filter(function(item){
return typeof item ==='string';
});
Did you try to give the layout_width and layout_height like the following? Since you are setting with wrap_content, the image button expands to the size of source image's height and width.
<blink>
<ImageButton>
android:id="@+id/Button01"
android:scaleType="fitXY"
android:layout_width="80dip"
android:layout_height="80dip"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:src="@drawable/eye">
</ImageButton>
</blink>
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
I follow the PEP8, it is a great piece of coding style.
The amount of "neurons", or "cells", or whatever the layer has inside it.
It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:
Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.
Ex: a shape (30,4,10)
means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.
What flows between layers are tensors. Tensors can be seen as matrices, with shapes.
In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.
Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3)
. Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).
Each type of layer requires the input with a certain number of dimensions:
Dense
layers require inputs as (batch_size, input_size)
(batch_size, optional,...,optional, input_size)
channels_last
: (batch_size, imageside1, imageside2, channels)
channels_first
: (batch_size, channels, imageside1, imageside2)
(batch_size, sequence_length, features)
Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.
All the other shapes are calculated automatically based on the units and particularities of each layer.
Given the input shape, all other shapes are results of layers calculations.
The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).
Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)
Let's show what happens with "Dense" layers, which is the type shown in your graph.
A dense layer has an output shape of (batch_size,units)
. So, yes, units, the property of the layer, also defines the output shape.
(batch_size,4)
. (batch_size,4)
. (batch_size,1)
. Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.
In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.
In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.
Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3)
.
Since the input shape is the only one you need to define, Keras will demand it in the first layer.
But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:
input_shape = (50,50,3)
#regardless of how many images I have, each image has this shape
Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3)
or batch_shape=(30,50,50,3)
. This limits your training possibilities to this unique batch size, so it should be used only when really required.
Either way you choose, tensors in the model will have the batch dimension.
So, even if you used input_shape=(50,50,3)
, when keras sends you messages, or when you print the model summary, it will show (None,50,50,3)
.
The first dimension is the batch size, it's None
because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None
)
Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.
input_shape=(50,50,3)
(30,50,50,3)
(None,50,50,3)
or (30,50,50,3)
, depending on what type of message it sends you. And in the end, what is dim
?
If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim
as a scalar number.
So, in your model, where your input layer has 3 elements, you can use any of these two:
input_shape=(3,)
-- The comma is necessary when you have only one dimension input_dim = 3
But when dealing directly with the tensors, often dim
will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.
Keras has two ways of doing it, Sequential
models, or the functional API Model
. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.
PS: here I ignored other aspects, such as activation functions.
With the Sequential model:
from keras.models import Sequential
from keras.layers import *
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
With the functional API Model:
from keras.models import Model
from keras.layers import *
#Start defining the input tensor:
inpTensor = Input((3,))
#create the layers and pass them the input tensor to get the output tensor:
hidden1Out = Dense(units=4)(inpTensor)
hidden2Out = Dense(units=4)(hidden1Out)
finalOut = Dense(units=1)(hidden2Out)
#define the model's start and end points
model = Model(inpTensor,finalOut)
Shapes of the tensors
Remember you ignore batch sizes when defining layers:
(None,3)
(None,4)
(None,4)
(None,1)
If you have android studio installed, simply open the Project/android
using Android Studio, and it will notify you to switch the SDK location path in the project.
Here is my whole code of a map activity with 4 clickable markers. Click on a marker shows an info window, and after click on info window you are going to another activity: English, German, Spanish or Italian. If you want to use OnMarkerClickListener in spite of OnInfoWindowClickListener, you just have to swap this line:
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
to this:
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
this line:
public void onInfoWindowClick(Marker arg0)
to this:
public boolean onMarkerClick(Marker arg0)
and at the end of the method "onMarkerClick":
return true;
I think it may be helpful for someone ;)
package pl.pollub.translator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toast.makeText(this, "Choose a language.", Toast.LENGTH_LONG).show();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
@Override
public void onInfoWindowClick(Marker arg0) {
if(arg0 != null && arg0.getTitle().equals("English")){
Intent intent1 = new Intent(MapsActivity.this, English.class);
startActivity(intent1);}
if(arg0 != null && arg0.getTitle().equals("German")){
Intent intent2 = new Intent(MapsActivity.this, German.class);
startActivity(intent2);}
if(arg0 != null && arg0.getTitle().equals("Italian")){
Intent intent3 = new Intent(MapsActivity.this, Italian.class);
startActivity(intent3);}
if(arg0 != null && arg0.getTitle().equals("Spanish")){
Intent intent4 = new Intent(MapsActivity.this, Spanish.class);
startActivity(intent4);}
}
});
LatLng greatBritain = new LatLng(51.30, -0.07);
LatLng germany = new LatLng(52.3107, 13.2430);
LatLng italy = new LatLng(41.53, 12.29);
LatLng spain = new LatLng(40.25, -3.41);
mMap.addMarker(new MarkerOptions()
.position(greatBritain)
.title("English")
.snippet("Click on me:)"));
mMap.addMarker(new MarkerOptions()
.position(germany)
.title("German")
.snippet("Click on me:)"));
mMap.addMarker(new MarkerOptions()
.position(italy)
.title("Italian")
.snippet("Click on me:)"));
mMap.addMarker(new MarkerOptions()
.position(spain)
.title("Spanish")
.snippet("Click on me:)"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(greatBritain));
mMap.moveCamera(CameraUpdateFactory.newLatLng(germany));
mMap.moveCamera(CameraUpdateFactory.newLatLng(italy));
mMap.moveCamera(CameraUpdateFactory.newLatLng(spain));
}
}
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
$("#grid_GridHeader").eq(0)
For completeness here is another method for emulating INTERSECT
. Note that the IN (SELECT ...)
form suggested in other answers is generally more efficient.
Generally for a table called mytable
with a primary key called id
:
SELECT id
FROM mytable AS a
INNER JOIN mytable AS b ON a.id = b.id
WHERE
(a.col1 = "someval")
AND
(b.col1 = "someotherval")
(Note that if you use SELECT *
with this query you will get twice as many columns as are defined in mytable
, this is because INNER JOIN
generates a Cartesian product)
The INNER JOIN
here generates every permutation of row-pairs from your table. That means every combination of rows is generated, in every possible order. The WHERE
clause then filters the a
side of the pair, then the b
side. The result is that only rows which satisfy both conditions are returned, just like intersection two queries would do.
With Bootstrap 4, there is a css class specifically for this. The below will center row content:
<div class="row justify-content-center">
...inner divs and content...
</div>
See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.
Here's a function I wrote that uses pseudo-transparency to represent overlapping histograms
plotOverlappingHist <- function(a, b, colors=c("white","gray20","gray50"),
breaks=NULL, xlim=NULL, ylim=NULL){
ahist=NULL
bhist=NULL
if(!(is.null(breaks))){
ahist=hist(a,breaks=breaks,plot=F)
bhist=hist(b,breaks=breaks,plot=F)
} else {
ahist=hist(a,plot=F)
bhist=hist(b,plot=F)
dist = ahist$breaks[2]-ahist$breaks[1]
breaks = seq(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks),dist)
ahist=hist(a,breaks=breaks,plot=F)
bhist=hist(b,breaks=breaks,plot=F)
}
if(is.null(xlim)){
xlim = c(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks))
}
if(is.null(ylim)){
ylim = c(0,max(ahist$counts,bhist$counts))
}
overlap = ahist
for(i in 1:length(overlap$counts)){
if(ahist$counts[i] > 0 & bhist$counts[i] > 0){
overlap$counts[i] = min(ahist$counts[i],bhist$counts[i])
} else {
overlap$counts[i] = 0
}
}
plot(ahist, xlim=xlim, ylim=ylim, col=colors[1])
plot(bhist, xlim=xlim, ylim=ylim, col=colors[2], add=T)
plot(overlap, xlim=xlim, ylim=ylim, col=colors[3], add=T)
}
Here's another way to do it using R's support for transparent colors
a=rnorm(1000, 3, 1)
b=rnorm(1000, 6, 1)
hist(a, xlim=c(0,10), col="red")
hist(b, add=T, col=rgb(0, 1, 0, 0.5) )
The results end up looking something like this:
You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.
worker.RunWorkerAsync(5);
private void worker_DoWork(object sender, DoWorkEventArgs e) {
int argument = (int)e.Argument; //5
}
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket is not correct and will not give a good impression on the interviewer .
If key is null , then Null keys always map to hash 0, thus index 0.
If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks like
int hash = hash(hashValue)
and now ,it applies returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.
Now final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex)
Use ax.yaxis.tick_right()
for example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head
section that uses body
. Not cool.
You want to wrap this code in a window.onload
handler or place it after the <body>
tag (as mentioned by e-bacho 2.0).
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
window.onload = function() {
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
}
</script>
</head>
its kind of hacky but it works well-ish
function close_frame(){
if(!window.should_close){
window.should_close=1;
}else if(window.should_close==1){
location.reload();
//or iframe hide or whatever
}
}
<iframe src="iframe_index.php" onload="close_frame()"></iframe>
then inside the frame
$('#close_modal_main').click(function(){
window.location = 'iframe_index.php?close=1';
});
and if you want to get fancy through a
if(isset($_GET['close'])){
die;
}
at the top of your frame page to make that reload unnoticeable
so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
Hope it helps!
If you can change the signature of your function to async Task
then you can use the code presented here
There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)
This works fine in Safari and Mozilla/FireFox.
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
Thought this might help someone in the future.
If you know the property name already, you can do something like the following:
[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
var stringValue = args.MyPropertyName.ToString();
//do something with the string value. If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
//some more code here....
return stringValue;
}
The low level iterator
manipulate code:
List<Money> myMoney = new List<Money>
{
new Money{amount = 10, type = "US"},
new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
while (enumerator.MoveNext())
{
var element = enumerator.Current;
Console.WriteLine(element.amount);
}
}
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.
^\d{1,2}[\W_]?po$
\d
defines a number and {1,2}
means 1 or two of the expression before, \W
defines a non word character.
I see this nice tutorial on how to get the like count from facebook using PHP.
public static function get_the_fb_like( $url = '' ){
$pageURL = 'http://nextopics.com';
$url = ($url == '' ) ? $pageURL : $url; // setting a value in $url variable
$params = 'select comment_count, share_count, like_count from link_stat where url = "'.$url.'"';
$component = urlencode( $params );
$url = 'http://graph.facebook.com/fql?q='.$component;
$fbLIkeAndSahre = json_decode( $this->file_get_content_curl( $url ) );
$getFbStatus = $fbLIkeAndSahre->data['0'];
return $getFbStatus->like_count;
}
here is a sample code.. I don't know how to paste the code with correct format in here, so just kindly visit this link for better view of the code.
Since it's an array before you cast it, casting it makes no sense.
You may want a recursive cast, which would look something like this:
function arrayCastRecursive($array)
{
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = arrayCastRecursive($value);
}
if ($value instanceof stdClass) {
$array[$key] = arrayCastRecursive((array)$value);
}
}
}
if ($array instanceof stdClass) {
return arrayCastRecursive((array)$array);
}
return $array;
}
Usage:
$obj = new stdClass;
$obj->aaa = 'asdf';
$obj->bbb = 'adsf43';
$arr = array('asdf', array($obj, 3));
var_dump($arr);
$arr = arrayCastRecursive($arr);
var_dump($arr);
Result before:
array
0 => string 'asdf' (length = 4)
1 =>
array
0 =>
object(stdClass)[1]
public 'aaa' => string 'asdf' (length = 4)
public 'bbb' => string 'adsf43' (length = 6)
1 => int 3
Result after:
array
0 => string 'asdf' (length = 4)
1 =>
array
0 =>
array
'aaa' => string 'asdf' (length = 4)
'bbb' => string 'adsf43' (length = 6)
1 => int 3
Note:
Tested and working with complex arrays where a stdClass object can contain other stdClass objects.
This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
disable the transactionmanager in your Bean.xml
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
comment out these lines, and you'll see the exception causing the rollback ;)
For anybody who is getting an error like : '2*' string cannot be converted to Length.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
<ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition MinHeight="30" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>
I would rather use FusedLocationApi
since OnMyLocationChangeListener
is deprecated.
First declare these 3 variables:
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
Define methods:
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
@Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
@Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
initGoogleApiClient()
is used to initialize GoogleApiClient
objectsetLocationListener()
is used to setup location change listenerremoveLocationListener()
is used to remove the listenerCall initGoogleApiClient
method to start the code working :) Don't forget to remove the listener (mLocationListener
) at the end to avoid memory leak issues.
You can use a constructor with no parameters in your Parent class :
public parent() { }
Write in .htaccess :)
## Redirect from non-www to www (remove the two lines below to enable)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Java 7 and above
You can also pass your desired encoding to the String
constructor as a Charset
constant from StandardCharsets. This may be safer than passing the encoding as a String
, as suggested in the other answers.
For example, for UTF-8 encoding
String bytesAsString = new String(bytes, StandardCharsets.UTF_8);
If you want get an array of filenames including symlinks, use
Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }
or even
Dir.new('/path/to/dir').reject { |f| File.directory? f }
and if you want to go without symlinks, use
Dir.new('/path/to/dir').select { |f| File.file? f }
As shown in other answers, use Dir.glob('/path/to/dir/**/*')
instead of Dir.new('/path/to/dir')
if you want to get all the files recursively.
DECLARE @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE @IsolationLevel varchar(100)
INSERT @UserOptions
EXEC('DBCC USEROPTIONS WITH NO_INFOMSGS')
SELECT @IsolationLevel = Value
FROM @UserOptions
WHERE SetOption = 'isolation level'
-- Do whatever you want with the variable here...
PRINT @IsolationLevel
It will work for both iphone and ipad
func showImagePicker() {
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let alert = UIAlertController(title: "", message: "Upload Attachment", preferredStyle: alertStyle)
alert.addAction(UIAlertAction(title: "Choose from gallery", style: .default , handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction) in
}))
present(alert, animated: true, completion: nil)
}
Based on the answer by Fred-II I wanted to share my take on the getOS function, it avoids globals, merges both lists and detects the architecture (x32/x64)
/**
* @param $user_agent null
* @return string
*/
function getOS($user_agent = null)
{
if(!isset($user_agent) && isset($_SERVER['HTTP_USER_AGENT'])) {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
}
// https://stackoverflow.com/questions/18070154/get-operating-system-info-with-php
$os_array = [
'windows nt 10' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1|windows nt 7.0' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows Server 2003/XP x64',
'windows nt 5.1' => 'Windows XP',
'windows xp' => 'Windows XP',
'windows nt 5.0|windows nt5.1|windows 2000' => 'Windows 2000',
'windows me' => 'Windows ME',
'windows nt 4.0|winnt4.0' => 'Windows NT',
'windows ce' => 'Windows CE',
'windows 98|win98' => 'Windows 98',
'windows 95|win95' => 'Windows 95',
'win16' => 'Windows 3.11',
'mac os x 10.1[^0-9]' => 'Mac OS X Puma',
'macintosh|mac os x' => 'Mac OS X',
'mac_powerpc' => 'Mac OS 9',
'linux' => 'Linux',
'ubuntu' => 'Linux - Ubuntu',
'iphone' => 'iPhone',
'ipod' => 'iPod',
'ipad' => 'iPad',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'webos' => 'Mobile',
'(media center pc).([0-9]{1,2}\.[0-9]{1,2})'=>'Windows Media Center',
'(win)([0-9]{1,2}\.[0-9x]{1,2})'=>'Windows',
'(win)([0-9]{2})'=>'Windows',
'(windows)([0-9x]{2})'=>'Windows',
// Doesn't seem like these are necessary...not totally sure though..
//'(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'Windows NT',
//'(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})'=>'Windows NT', // fix by bg
'Win 9x 4.90'=>'Windows ME',
'(windows)([0-9]{1,2}\.[0-9]{1,2})'=>'Windows',
'win32'=>'Windows',
'(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})'=>'Java',
'(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}'=>'Solaris',
'dos x86'=>'DOS',
'Mac OS X'=>'Mac OS X',
'Mac_PowerPC'=>'Macintosh PowerPC',
'(mac|Macintosh)'=>'Mac OS',
'(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'SunOS',
'(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'BeOS',
'(risc os)([0-9]{1,2}\.[0-9]{1,2})'=>'RISC OS',
'unix'=>'Unix',
'os/2'=>'OS/2',
'freebsd'=>'FreeBSD',
'openbsd'=>'OpenBSD',
'netbsd'=>'NetBSD',
'irix'=>'IRIX',
'plan9'=>'Plan9',
'osf'=>'OSF',
'aix'=>'AIX',
'GNU Hurd'=>'GNU Hurd',
'(fedora)'=>'Linux - Fedora',
'(kubuntu)'=>'Linux - Kubuntu',
'(ubuntu)'=>'Linux - Ubuntu',
'(debian)'=>'Linux - Debian',
'(CentOS)'=>'Linux - CentOS',
'(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - Mandriva',
'(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - SUSE',
'(Dropline)'=>'Linux - Slackware (Dropline GNOME)',
'(ASPLinux)'=>'Linux - ASPLinux',
'(Red Hat)'=>'Linux - Red Hat',
// Loads of Linux machines will be detected as unix.
// Actually, all of the linux machines I've checked have the 'X11' in the User Agent.
//'X11'=>'Unix',
'(linux)'=>'Linux',
'(amigaos)([0-9]{1,2}\.[0-9]{1,2})'=>'AmigaOS',
'amiga-aweb'=>'AmigaOS',
'amiga'=>'Amiga',
'AvantGo'=>'PalmOS',
//'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}'=>'Linux',
//'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}'=>'Linux',
//'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})'=>'Linux',
'[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}'=>'Linux',
'(webtv)/([0-9]{1,2}\.[0-9]{1,2})'=>'WebTV',
'Dreamcast'=>'Dreamcast OS',
'GetRight'=>'Windows',
'go!zilla'=>'Windows',
'gozilla'=>'Windows',
'gulliver'=>'Windows',
'ia archiver'=>'Windows',
'NetPositive'=>'Windows',
'mass downloader'=>'Windows',
'microsoft'=>'Windows',
'offline explorer'=>'Windows',
'teleport'=>'Windows',
'web downloader'=>'Windows',
'webcapture'=>'Windows',
'webcollage'=>'Windows',
'webcopier'=>'Windows',
'webstripper'=>'Windows',
'webzip'=>'Windows',
'wget'=>'Windows',
'Java'=>'Unknown',
'flashget'=>'Windows',
// delete next line if the script show not the right OS
//'(PHP)/([0-9]{1,2}.[0-9]{1,2})'=>'PHP',
'MS FrontPage'=>'Windows',
'(msproxy)/([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
'(msie)([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
'libwww-perl'=>'Unix',
'UP.Browser'=>'Windows CE',
'NetAnts'=>'Windows',
];
// https://github.com/ahmad-sa3d/php-useragent/blob/master/core/user_agent.php
$arch_regex = '/\b(x86_64|x86-64|Win64|WOW64|x64|ia64|amd64|ppc64|sparc64|IRIX64)\b/ix';
$arch = preg_match($arch_regex, $user_agent) ? '64' : '32';
foreach ($os_array as $regex => $value) {
if (preg_match('{\b('.$regex.')\b}i', $user_agent)) {
return $value.' x'.$arch;
}
}
return 'Unknown';
}
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
This depends on what's actually being added by the pseudoselectors. In your situation, setting content to ""
will get rid of it, but if you're setting borders or backgrounds or whatever, you need to zero those out specifically. As far as I know, there's no one cure-all for removing everything about a before/after element regardless of what it is.
It is possible to use the format()
function, so in your case you can use:
return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)
There are multiple ways of using this function, so for further information you can check the documentation.
f-strings is a new feature that has been added to the language in Python 3.6. This facilitates formatting strings notoriously:
return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'
I prefer this solution:
df = spark.table(selected_table).filter(condition)
counter = df.count()
df = df.select([(counter - count(c)).alias(c) for c in df.columns])
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
Try this:
PM> Enable-migrations -force
PM> Add-migration MigrationName
PM> Update-database -force
From Filename parsing in batch file and more idioms - Real's How-to:
The path (without drive) where the script is : ~p0
The drive where the script is : ~d0
m.find == m.end() // not found
If you want to use other API, then find go for m.count(c)>0
if (m.count("f")>0)
cout << " is an element of m.\n";
else
cout << " is not an element of m.\n";
Using the codes below, you can swap between BigEndian and LittleEndian easily
#define uint32_t unsigned
#define uint16_t unsigned short
#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \
(((uint16_t)(x) & 0xff00)>>8))
#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \
(((uint32_t)(x) & 0x0000ff00)<<8)| \
(((uint32_t)(x) & 0x00ff0000)>>8)| \
(((uint32_t)(x) & 0xff000000)>>24))
Because in Python 3, print statement
has been replaced with a print() function
, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as
print("Hello World")
But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:
from __future__ import print_function
Now your code works on both 2.x & 3.x.
Check out below examples also to get familiar with print() function.
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
Source: What’s New In Python 3.0?
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
Null is supported by the Stream provided My library AbacusUtil. Here is code:
Stream.of(things).map(e -> resolve(e).orNull()).skipNull().first();
If you have a function, then you probably need this:foo(&array[0], array.size());
. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.
[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]
bit
. It stores 1 or 0 (or NULL
).Alternatively, you could use the strings 'true'
and 'false'
in place of 1 or 0, like so-
declare @b1 bit = 'false'
print @b1 --prints 0
declare @b2 bit = 'true'
print @b2 --prints 1
Also, any non 0 value (either positive or negative) evaluates to (or converts to in some cases) a 1.
declare @i int = -42
print cast(@i as bit) --will print 1, because @i is not 0
Note that SQL Server uses three valued logic (true
, false
, and NULL
), since NULL
is a possible value of the bit
data type. Here are the relevant truth tables -
More information on three valued logic-
Example of three valued logic in SQL Server
http://www.firstsql.com/idefend3.htm
https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/
One more alternative, in the case you are working with the Appstore, need "Entitlements" and as such need to link with an Apple-Framework.
For Entitlements to work (e.g. GameCenter) you need to have a "Link Binary with Libraries"-buildstep and then link with "GameKit.framework". CMake "injects" the libraries on a "low level" into the commandline, hence Xcode doesn't really know about it, and as such you will not get GameKit enabled in the Capabilities screen.
One way to use CMake and have a "Link with Binaries"-buildstep is to generate the xcodeproj with CMake, and then use 'sed' to 'search & replace' and add the GameKit in the way XCode likes it...
The script looks like this (for Xcode 6.3.1).
s#\/\* Begin PBXBuildFile section \*\/#\/\* Begin PBXBuildFile section \*\/\
26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks \*\/ = {isa = PBXBuildFile; fileRef = 26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/; };#g
s#\/\* Begin PBXFileReference section \*\/#\/\* Begin PBXFileReference section \*\/\
26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System\/Library\/Frameworks\/GameKit.framework; sourceTree = SDKROOT; };#g
s#\/\* End PBXFileReference section \*\/#\/\* End PBXFileReference section \*\/\
\
\/\* Begin PBXFrameworksBuildPhase section \*\/\
26B12A9F1C10543B00A9A2BA \/\* Frameworks \*\/ = {\
isa = PBXFrameworksBuildPhase;\
buildActionMask = 2147483647;\
files = (\
26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks xxx\*\/,\
);\
runOnlyForDeploymentPostprocessing = 0;\
};\
\/\* End PBXFrameworksBuildPhase section \*\/\
#g
s#\/\* CMake PostBuild Rules \*\/,#\/\* CMake PostBuild Rules \*\/,\
26B12A9F1C10543B00A9A2BA \/\* Frameworks xxx\*\/,#g
s#\/\* Products \*\/,#\/\* Products \*\/,\
26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/,#g
save this to "gamecenter.sed" and then "apply" it like this ( it changes your xcodeproj! )
sed -i.pbxprojbak -f gamecenter.sed myproject.xcodeproj/project.pbxproj
You might have to change the script-commands to fit your need.
Warning: it's likely to break with different Xcode-version as the project-format could change, the (hardcoded) unique number might not really by unique - and generally the solutions by other people are better - so unless you need to Support the Appstore + Entitlements (and automated builds), don't do this.
This is a CMake bug, see http://cmake.org/Bug/view.php?id=14185 and http://gitlab.kitware.com/cmake/cmake/issues/14185
If you aren't worried about squeaking every single last bit of performance the suggestion to use a HashSet or binary search is solid. Your datasets just aren't large enough that this is going to be a problem 99% of the time.
But if this just one of thousands of times you are going to do this and performance is critical (and proven to be unacceptable using HashSet/binary search), you could certainly write your own algorithm that walked the sorted lists doing comparisons as you went. Each list would be walked at most once and in the pathological cases wouldn't be bad (once you went this route you'd probably find that the comparison, assuming it's a string or other non-integral value, would be the real expense and that optimizing that would be the next step).
In XML
use:
android:editable="false"
As an example:
<EditText
android:id="@+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
In my case, I found that I need the -f option. Such as the following:
git rm -f first_file.txt
to get rid of the "needs merge" error.
I wanted this:
MapVC is a Map in full screen.
When I press a button, it opens PopupVC (not in full screen) above the map.
When I press a button in PopupVC, it returns to MapVC, and then I want to execute viewDidAppear.
I did this:
MapVC.m: in the button action, a segue programmatically, and set delegate
- (void) buttonMapAction{
PopupVC *popvc = [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
popvc.delegate = self;
[self presentViewController:popvc animated:YES completion:nil];
}
- (void)dismissAndPresentMap {
[self dismissViewControllerAnimated:NO completion:^{
NSLog(@"dismissAndPresentMap");
//When returns of the other view I call viewDidAppear but you can call to other functions
[self viewDidAppear:YES];
}];
}
PopupVC.h: before @interface, add the protocol
@protocol PopupVCProtocol <NSObject>
- (void)dismissAndPresentMap;
@end
after @interface, a new property
@property (nonatomic,weak) id <PopupVCProtocol> delegate;
PopupVC.m:
- (void) buttonPopupAction{
//jump to dismissAndPresentMap on Map view
[self.delegate dismissAndPresentMap];
}
Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.
Example #
// tsconfig.json_x000D_
_x000D_
{_x000D_
"compilerOptions": {_x000D_
"module": "commonjs",_x000D_
"resolveJsonModule": true,_x000D_
"esModuleInterop": true_x000D_
}_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true; // OK_x000D_
settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
"repo": "TypeScript",_x000D_
"dry": false,_x000D_
"debug": false_x000D_
}
_x000D_
I faced the same problem. I had a zip archive which java.util.zip.ZipFile was not able to handle but WinRar unpacked it just fine. I found article on SDN about compressing and decompressing options in Java. I slightly modified one of example codes to produce method which was finally capable of handling the archive. Trick is in using ZipInputStream instead of ZipFile and in sequential reading of zip archive. This method is also capable of handling empty zip archive. I believe you can adjust the method to suit your needs as all zip classes have equivalent subclasses for .jar archives.
public void unzipFileIntoDirectory(File archive, File destinationDir)
throws Exception {
final int BUFFER_SIZE = 1024;
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(archive);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File destFile;
while ((entry = zis.getNextEntry()) != null) {
destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
if (entry.isDirectory()) {
destFile.mkdirs();
continue;
} else {
int count;
byte data[] = new byte[BUFFER_SIZE];
destFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
fos.close();
}
}
zis.close();
fis.close();
}
For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
Syntax
auto variable initializer (1) (since C++11)
auto function -> return type (2) (since C++11)
auto function (3) (since C++14)
decltype(auto) variable initializer (4) (since C++14)
decltype(auto) function (5) (since C++14)
auto :: (6) (concepts TS)
cv(optional) auto ref(optional) parameter (7) (since C++14)
Explanation
1) When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier.
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;
, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u)
if the function call f(expr)
was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop.
If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0;
is ill-formed, while the declaration auto i = 0, *p = &i;
is well-formed and the auto is deduced as int.
2) In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.
3) In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.
4) If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.
5) If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.
6) A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.
7) A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)
Notes
Until C++11, auto had the semantic of a storage duration specifier.
Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0;
is not allowed.
For more info : http://en.cppreference.com/w/cpp/language/auto
This is a very old question, but i don't see my understanding here so I will add my 2 cents:
Every level corresponds/maps to a type of user:
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
This is by design. You can cast null
to any reference type. Otherwise you wouldn't be able to assign it to reference variables.
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.
If you want to get any element that has part of a URL in their href attribute you could use:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
As stated by @BalusC in the comments below, it will also match elements that have google.com
at any position in the href, like blahgoogle.com
.
As already pointed out by all the answers goto
- a reserved word in Java
and is not used in the language.
restart:
is called an identifier followed by a colon.
Here are a few things you need to take care of if you wish to achieve similar
behavior -
outer: // Should be placed exactly before the loop
loopingConstructOne { // We can have statements before the outer but not inbetween the label and the loop
inner:
loopingConstructTwo {
continue; // This goes to the top of loopingConstructTwo and continue.
break; // This breaks out of loopingConstructTwo.
continue outer; // This goes to the outer label and reenters loopingConstructOne.
break outer; // This breaks out of the loopingConstructOne.
continue inner; // This will behave similar to continue.
break inner; // This will behave similar to break.
}
}
I'm not sure of whether should I say similar
as I already have.
I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.
Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.
new Vue({
methods: {
setValue: function() {
this.$data.oldPeople = _.cloneDeep(this.$data.people);
},
},
mounted() {
this.setValue();
},
el: '#app',
data: {
people: [
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
],
oldPeople: []
},
watch: {
people: {
handler: function (after, before) {
// Return the object that changed
var vm = this;
let changed = after.filter( function( p, idx ) {
return Object.keys(p).some( function( prop ) {
return p[prop] !== vm.$data.oldPeople[idx][prop];
})
})
// Log it
vm.setValue();
console.log(changed)
},
deep: true,
}
}
})
See the updated codepen
Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).
E.g.
// This assignment is possible because B extends A
A a = new B();
// polymorphic call/ access
a.foo();
-> Though the static/ declaration type of a is A, the actual dynamic/ runtime type is B and thus a.foo() will execute foo as defined in B not in A.
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
Who is Jon Skeet?
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Just wanted to mention react-router v4 changed radically since this question was posted/answed.
There is no <Match>
component any more! <Switch>
is to make sure only the first match is rendered. <Redirect>
well .. redirects to another route. Use or leave out exact
to either in- or exclude a partial match.
See the docs. They are great. https://reacttraining.com/react-router/
Here's an example I hope is useable to answer your question.
<Router>
<div>
<Redirect exact from='/' to='/front'/>
<Route path="/" render={() => {
return (
<div>
<h2>Home menu</h2>
<Link to="/front">front</Link>
<Link to="/back">back</Link>
</div>
);
}} />
<Route path="/front" render={() => {
return (
<div>
<h2>front menu</h2>
<Link to="/front/help">help</Link>
<Link to="/front/about">about</Link>
</div>
);
}} />
<Route exact path="/front/help" render={() => {
return <h2>front help</h2>;
}} />
<Route exact path="/front/about" render={() => {
return <h2>front about</h2>;
}} />
<Route path="/back" render={() => {
return (
<div>
<h2>back menu</h2>
<Link to="/back/help">help</Link>
<Link to="/back/about">about</Link>
</div>
);
}} />
<Route exact path="/back/help" render={() => {
return <h2>back help</h2>;
}} />
<Route exact path="/back/about" render={() => {
return <h2>back about</h2>;
}} />
</div>
</Router>
Hope it helped, let me know. If this example is not answering your question well enough, tell me and I'll see if I can modify it.
Firstly: The >>>
code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:
>>> 4+5
9
Here we see that the line that starts with >>>
is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.
You never enter the >>>
part into a .py
file.
That takes care of your syntax error.
Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.
They all have benefits and drawbacks.
SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.
Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.
ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.
Actually it depends on your use case.
1) You want to protect your route from unauthorized users
If that is the case you can use the component called <Redirect />
and can implement the following logic:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Keep in mind that if you want <Redirect />
to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.
2) You want to redirect after a certain action (let's say after creating an item)
In that case you can use history:
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
or
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
In order to have access to history, you can wrap your component with an HOC called withRouter
. When you wrap your component with it, it passes match
location
and history
props. For more detail please have a look at the official documentation for withRouter.
If your component is a child of a <Route />
component, i.e. if it is something like <Route path='/path' component={myComponent} />
, you don't have to wrap your component with withRouter
, because <Route />
passes match
, location
, and history
to its child.
3) Redirect after clicking some element
There are two options here. You can use history.push()
by passing it to an onClick
event:
<div onClick={this.props.history.push('/path')}> some stuff </div>
or you can use a <Link />
component:
<Link to='/path' > some stuff </Link>
I think the rule of thumb with this case is to try to use <Link />
first, I suppose especially because of performance.
Amyuni WebkitPDF could be used with JNI for a Windows-only solution. This is a HTML to PDF/XAML conversion library, free for commercial and non-commercial use.
If the output files are not needed immediately, for better scalability it may be better to have a queue and a few background processes taking items from there, converting them and storing then on the database or file system.
usual disclaimer applies
print "financial return of outcome 1 = $%.2f" % (out1)
Get rid of the values
keyword and the parens. You can see an example here.
This is basic INSERT syntax:
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);
This is the INSERT SELECT syntax:
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";
This answer is a bit late but I hope it helps someone out there all the same.
In my case, it was because the repository had been moved. I recloned the project and everything became alright afterwards. A better alternative would have been to re-initialize git.
I hope this helps.. Merry coding!
Below code may help you to achieve session attribution inside java script:
var name = '<%= session.getAttribute("username") %>';
My usual ajax calling function:
function xhr_new(targetId, url, busyMsg, finishCB)
{
var xhr;
if(busyMsg !== undefined)
document.getElementById(targetId).innerHTML = busyMsg;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch(e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch(e2)
{
try { xhr = new XMLHttpRequest(); }
catch(e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var target = document.getElementById(targetId)
target.innerHTML = xhr.responseText;
var scriptElements = target.getElementsByTagName("script");
var i;
for(i = 0; i < scriptElements.length; i++)
eval(scriptElements[i].innerHTML);
if(finishCB !== undefined)
finishCB();
}
else
document.getElementById(targetId).innerHTML = 'Error code: ' + xhr.status;
}
};
xhr.open('GET', url, true);
xhr.send(null);
// return xhr;
}
Some explanation:
targetId
is an (usually div) element ID where the ajax call result text will goes.
url
is the ajax call url.
busyMsg
will be the temporary text in the target element.
finishCB
will be called when the ajax transaction finished successfully.
As you see in the xhr.onreadystatechange = function() {...}
all of the <script>
elements will be collected from the ajax response and will be run one by one. It appears to work very well for me. The two last parameter is optional.
Here is another neat trick to define enum using X Macro:
#include <iostream>
#define WEEK_DAYS \
X(MON, "Monday", true) \
X(TUE, "Tuesday", true) \
X(WED, "Wednesday", true) \
X(THU, "Thursday", true) \
X(FRI, "Friday", true) \
X(SAT, "Saturday", false) \
X(SUN, "Sunday", false)
#define X(day, name, workday) day,
enum WeekDay : size_t
{
WEEK_DAYS
};
#undef X
#define X(day, name, workday) name,
char const *weekday_name[] =
{
WEEK_DAYS
};
#undef X
#define X(day, name, workday) workday,
bool weekday_workday[]
{
WEEK_DAYS
};
#undef X
int main()
{
std::cout << "Enum value: " << WeekDay::THU << std::endl;
std::cout << "Name string: " << weekday_name[WeekDay::THU] << std::endl;
std::cout << std::boolalpha << "Work day: " << weekday_workday[WeekDay::THU] << std::endl;
WeekDay wd = SUN;
std::cout << "Enum value: " << wd << std::endl;
std::cout << "Name string: " << weekday_name[wd] << std::endl;
std::cout << std::boolalpha << "Work day: " << weekday_workday[wd] << std::endl;
return 0;
}
Live Demo: https://ideone.com/bPAVTM
Outputs:
Enum value: 3
Name string: Thursday
Work day: true
Enum value: 6
Name string: Sunday
Work day: false
If your form is PHP based, it would work this way within your " <?php $data = array(" code:
'onkeypress' => 'return /[a-z 0-9]/i.test(event.key)',
The easiest is probably to create a PKCS#12 file using OpenSSL:
openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12
You should be able to use the resulting file directly using the PKCS12
keystore type.
If you really need to, you can convert it to JKS using keytool -importkeystore
(available in keytool
from Java 6):
keytool -importkeystore -srckeystore abc.p12 \
-srcstoretype PKCS12 \
-destkeystore abc.jks \
-deststoretype JKS
As others said, Sessions are clever and has more advantage of hiding the information from the client.
But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.
To pass multiple headers in a curl request you simply add additional -H
or --header
to your curl command.
Example
//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL
//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json' https://www.example.com
Going Further
For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:
For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.
$ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
$ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com
I had to implement a heap traversal which outputs in a BFS order. It isn't actually BFS but accomplishes the same task.
private void getNodeValue(Node node, int index, int[] array) {
array[index] = node.value;
index = (index*2)+1;
Node left = node.leftNode;
if (left!=null) getNodeValue(left,index,array);
Node right = node.rightNode;
if (right!=null) getNodeValue(right,index+1,array);
}
public int[] getHeap() {
int[] nodes = new int[size];
getNodeValue(root,0,nodes);
return nodes;
}
No, but you can do this almost as easily.
Go here:
https://romannurik.github.io/AndroidAssetStudio/
Build your icons using that page, and then download the zip package. Unzip it into the right directory and it'll overwrite all the drawable-*/ic_launcher.png correctly.
Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.
Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.
Here's some updated code:
var myarray = [];
$("#test").click(function() {
myarray.push($("#drop").val());
alert(myarray);
});
though this question had a solution already, I just want to share mine to make it be cleared, hope it could help:
/*
* The root cause is method doesn't in the App's context
* so that it can't access other attributes of "this".
* Below are few ways to define App's method property
*/
class App extends React.Component {
constructor() {
this.sayHi = 'hello';
// create method inside constructor, context = this
this.method = ()=> { console.log(this.sayHi) };
// bind method1 in constructor into context 'this'
this.method1 = this.method.bind(this)
}
// method1 was defined here
method1() {
console.log(this.sayHi);
}
// create method property by arrow function. I recommend this.
method2 = () => {
console.log(this.sayHi);
}
render() {
//....
}
}
In my case I also have unmanaged dll's (C++) in workspace and if you specify:
<files>
<file src="bin\*.dll" target="lib" />
</files>
nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this
behaviour explicitly define your C# assemblies with references
tag:
<references>
<reference file="Managed1.dll" />
<reference file="Managed2.dll" />
</references>
Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema
Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec
You can declare a @service as @Controller.
You can NOT declare an @Controller as @Service
@Service
It is regular. You are just declaring class as a Component.
@Controller
It is a little more special than Component. The dispatcher will search for @RequestMapping here. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called
So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
An alternative to the custom filter is to create an extension method to serialize any object to JSON.
public static class ObjectExtensions
{
/// <summary>Serializes the object to a JSON string.</summary>
/// <returns>A JSON string representation of the object.</returns>
public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
return JsonConvert.SerializeObject(value, settings);
}
}
Then call it when returning from the controller action.
return Content(person.ToJson(), "application/json");
public static Date convertTimestampToDate(Timestamp timestamp) {
Instant ins=timestamp.toLocalDateTime().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(ins);
}
simple example would be using substring like :
string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));
go to http://nodejs.org/
and hit the button that says "Download For ..."
This'll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.
I managed to do this with the following code:
ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This is the only way I could make a column auto increment.
INT(11) shows that the maximum int length is 11, you can skip it if you want.
Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.
SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
Assuming this is a windows system and we are using gradle-2.1-all [Applicable to any gradle version, just change the version as we need]
All the gradles can be found in http://services.gradle.org/distributions/
Check the <Your Project>\gradle\wrapper\gradle-wrapper.properties
Make sure the distributionUrl is
distributionUrl=http\://services.gradle.org/distributions/gradle-2.1-all.zip
This is enough as it will automatically download the gradle.
After doing the above stuff, if you have downloaded the zip, paste the gradle-2.1-all.zip in
C:\Users\<username>\.gradle\wrapper\dists\gradle-2.1-all\<some_hash_key>\
It will save the extra downloading time.
Check this out (this is a working solution for me)
public long AvailableFreeSpace()
{
long longAvailableFreeSpace = 0;
try{
DriveInfo[] arrayOfDrives = DriveInfo.GetDrives();
foreach (var d in arrayOfDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" Drive type: {0}", d.DriveType);
if (d.IsReady == true && d.Name == "/data")
{
Console.WriteLine("Volume label: {0}", d.VolumeLabel);
Console.WriteLine("File system: {0}", d.DriveFormat);
Console.WriteLine("AvailableFreeSpace for current user:{0, 15} bytes",d.AvailableFreeSpace);
Console.WriteLine("TotalFreeSpace {0, 15} bytes",d.TotalFreeSpace);
Console.WriteLine("Total size of drive: {0, 15} bytes \n",d.TotalSize);
}
longAvailableFreeSpaceInMB = d.TotalFreeSpace;
}
}
catch(Exception ex){
ServiceLocator.GetInsightsProvider()?.LogError(ex);
}
return longAvailableFreeSpace;
}
If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.
On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)
On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.
You should try. When you clear your Graphics you must choose color. SystemColors.Control is native color of form
Graphics g = pB.CreateGraphics();
g.Clear(SystemColors.Control);
Without going into tech stack implementation details, architecturally speaking there are at least two solutions to N + 1 Problem:
The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this
FOR SQL SERVER 2005 and above
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified =(int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return modified;
}
}
FOR previous versions
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified = Convert.ToInt32(cmd.ExecuteScalar());
if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
The best way to help memory to be freed is to nullify large objects:
Sub Whatever()
Dim someLargeObject as SomeObject
'expensive computation
Set someLargeObject = Nothing
End Sub
Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.
However this won't help if:
Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).
You can create a generic extension method and then use it on the object like:
public static class Extensions
{
public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
{
// if obj is null throws exception
Contract.Requires(obj != null);
// gets the type of the obj parameter
var type = obj.GetType();
// checks if obj is of type KeyValuePair
if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
{
return new KeyValuePair<TKey, TValue>(
(TKey)type.GetProperty("Key").GetValue(obj, null),
(TValue)type.GetProperty("Value").GetValue(obj, null)
);
}
// if obj type does not match KeyValuePair throw exception
throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");
}
and usage would be like:
KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken
to return either Optional.empty()
instead of null, or Optional.of(myReturnObject)
, where myReturnObject
is your chicken
.
Then you can call getChicken()
and if it would return Optional.empty()
the orElse(fallback)
would give you whatever the fallback would be, in your case the second method.
We have set up a solution for Team Foundation Server Source Control (not SourceSafe as you mention) similar to what Grant suggests; scheduled TF Get, Search Server Express. However the IFilter used for C# files (text) was not giving the results we wanted, so we convert source files to .htm files. We can now add additional meta-data to the files such as:
We would however prefer a protocolhandler for TFS Source Control, and a dedicated source code IFilter for a much more targeted solution.
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
Job done :)
Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
&& x.DestinationType.Equals(destinationType));
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
to be used as follow :
Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();
thanks to Can Gencer for the tip :)
source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/
Adding to all the answers above (which is why I made it a community wiki), it is probably best to mark any input<type="text">
with tabindex="-1"
, especially if using readonly instead of disabled (and perhaps the <input type="file">
, although it should be hidden, it is still in the document, apparently). Labels did not act correctly when using the tab / enter key combinations, but the button did. So if you are copying one of the other solutions on this page, you may want to make those changes.
Public Declare Function GetUserName Lib "advapi32.dll"
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
....
Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String
strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))
Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
Note that Python3 does not read the html code as a string but as a bytearray
, so you need to convert it to one with decode
.
import urllib.request
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
print(mystr)
It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.
Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."
I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.
On Windows, the PGDATA directory that the PostgresSQL docs describe is at somewhere like C:\Program Files\PostgreSQL\8.1\data
. The data for a particular database is under (for example) C:\Program Files\PostgreSQL\8.1\data\base\100929
, where I guess 100929 is the database number.
document.getElementsByClassName
returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0];
should get you what you want.
Update #1:
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Update #2: (with removeEventListener
incorporated as well)
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment(e) {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
for (var i = 0; i < numComments; i++) {
comments[i].removeEventListener('click', showComment, false);
}
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
NOTE this answer is now incorrect. I may get back to it at a later time.
As others have pointed out, you can't set the height of a table unless you set its display to block
, but then you get a scrolling header. So what you're looking for is to set the height
and display:block
on the tbody
alone:
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Here's the fiddle.
First, we need to filter the XML so as to parse that change objects become array
//catch xml
$xmlElement = file_get_contents ('php://input');
//change become array
$Data = (array)simplexml_load_string($xmlElement);
//and see
print_r($Data);
SHOW CREATE TABLE <tablename>\G
will format it much nicer compared to the output of
SHOW CREATE TABLE <tablename>;
The \G
trick is also useful to remember for many other queries/commands.
You can't declare an array using a variable so Byte byteData[len];
won't work. If you want to copy the data from a pointer, you also need to memcpy (which will go through the data pointed to by the pointer and copy each byte up to a specified length).
Try:
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
This code will dynamically allocate the array to the correct size (you must free(byteData)
when you're done) and copy the bytes into it.
You could also use getBytes:length:
as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.
Login into the database. then run the below query
select * from dba_role_privs where grantee = 'SCHEMA_NAME';
All the role granted to the schema will be listed.
Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.
Using JavaScript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';</script>");
}
Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.
Hope this helps.
Go to file \phpMyAdmin\config.inc.php at the very bottom, change the hosting details such as host, username, password etc.
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.
Assumed that I'm editing hello.txt.
Add a class to the body of each page:
<body class="home">
Or if you're on the contact page:
<body class="contact">
Then take this into consideration when you're creating your styles:
#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}
#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }
Lastly, apply class names to your list items:
<ul>
<li class="home"><a href="index.php">Home</a></li>
<li class="contact"><a href="contact.php">Contact Us</a></li>
<li class="about"><a href="about.php">About Us</a></li>
</ul>
This point, whenever you're on the body.home
page, your li.home a
link will have default styling indicating it is the current page.
with '0x' prefix, you might also use eval function
For example
>>a='0xff'
>>eval(a)
255
EXPOSE is used to map local port container port ie : if you specify expose in docker file like
EXPOSE 8090
What will does it will map localhost port 8090 to container port 8090
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".