What exactly does += do in python?
The short answer is +=
can be translated as "add whatever is to the right of the += to the variable on the left of the +=".
Ex. If you have a = 10
then a += 5
would be: a = a + 5
So, "a" now equal to 15.
import .css file into .less file
I had to use the following with version 1.7.4
@import (less) "foo.css"
I know the accepted answer is @import (css) "foo.css"
but it didn't work. If you want to reuse your css class in your new less file, you need to use (less)
and not (css)
.
Check the documentation.
How to get a path to the desktop for current user in C#?
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
Why do I get a SyntaxError for a Unicode escape in my file path?
I had the same error.
Basically, I suspect that the path cannot start either with "U" or "User" after "C:\".
I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.
In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.
DropDownList in MVC 4 with Razor
Here is the easiest answer:
in your view only just add:
@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))
OR
in your controller add:
var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
ViewBag.ExemploList = exemploList;
and your view just add:
@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )
I learned this with Jess Chadwick
Binding Button click to a method
I do this all the time. Here's a look at an example and how you would implement it.
Change your XAML to use the Command property of the button instead of the Click event. I am using the name SaveCommand since it is easier to follow then something named Command.
<Button Command="{Binding Path=SaveCommand}" />
Your CustomClass that the Button is bound to now needs to have a property called SaveCommand of type ICommand
. It needs to point to the method on the CustomClass that you want to run when the command is executed.
public MyCustomClass
{
private ICommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(
param => this.SaveObject(),
param => this.CanSave()
);
}
return _saveCommand;
}
}
private bool CanSave()
{
// Verify command can be executed here
}
private void SaveObject()
{
// Save command execution logic
}
}
The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)
/// <summary>
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
Get mouse wheel events in jQuery?
I got same problem recently where
$(window).mousewheel
was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}
Reading HTML content from a UIWebView
The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error:
method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:
NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
After running this code, googlePage
will contain the HTML for www.google.com, and error
will contain any errors encountered in the fetch. (You should check the contents of error
after the fetch.)
Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the request from the view, then do the fetch as before:
NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString:
method, as such:
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:
@"document.body.innerHTML"];
This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.
Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *page
as the result of a call to stringWithContentsOfURL:encoding:error:
. You can then push that string into the web view using loadHTMLString:baseURL:
, assuming you also held on to the NSURL you requested:
[yourWebView loadHTMLString:page baseURL:requestURL];
I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString
, is somewhat ambiguous, and the docs don't say much about it).
For more info:
How can I find a specific element in a List<T>?
Use a lambda expression
MyClass result = list.Find(x => x.GetId() == "xy");
Note: C# has a built-in syntax for properties. Instead of writing getter and setter methods (as you might be used to from Java), write
private string _id;
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
value
is a contextual keyword known only in the set accessor. It represents the value assigned to the property.
Since this pattern is often used, C# provides auto-implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).
public string Id { get; set; }
You can simply use properties as if you were accessing a field:
var obj = new MyClass();
obj.Id = "xy"; // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id; // Calls the getter.
Using properties, you would search for items in the list like this
MyClass result = list.Find(x => x.Id == "xy");
You can also use auto-implemented properties if you need a read-only property:
public string Id { get; private set; }
This enables you to set the Id
within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter
public string Id { get; protected set; }
And finally, you can declare properties as virtual
and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.
Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer
public string Id { get; } = "A07"; // Evaluated once when object is initialized.
You can also initialize getter-only properties within the constructor instead. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.
This works also with read-write auto-properties:
public string Id { get; set; } = "A07";
Beginning with C# 6.0 you can also write properties as expression-bodied members
public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }
See: .NET Compiler Platform ("Roslyn")
New Language Features in C# 6
Starting with C# 7.0, both, getter and setter, can be written with expression bodies:
public string Name
{
get => _name; // getter
set => _name = value; // setter
}
Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0
is equivalent to x = (y = (z = 0))
and has the same effect as the statements x = 0; y = 0; z = 0;
.
The next version of the language, C# 9.0, probably available in November 2020, will allow read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.
public string Name { get; init; }
var c = new C { Name = "c-sharp" };
HTML code for INR
How about using fontawesome icon for Indian Rupee (INR).
Add font awesome CSS from CDN in the Head section of your HTML page:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
And then using the font like this:
<i class="fa fa-inr" aria-hidden="true"></i>
How does Java import work?
Java's import statement is pure syntactical sugar. import is only evaluated at compile time to indicate to the compiler where to find the names in the code.
You may live without any import statement when you always specify the full qualified name of classes. Like this line needs no import statement at all:
javax.swing.JButton but = new javax.swing.JButton();
The import statement will make your code more readable like this:
import javax.swing.*;
JButton but = new JButton();
SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column
Since I don't believe "Please use..." plus some random code that is unrelated to the question
is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.
When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
('col1', 'col3', 'col2')
It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.
Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.
TLDR
using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x =>
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));
This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.
How to keep form values after post
If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:
<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />
Get row-index values of Pandas DataFrame as list?
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
pandas resample documentation
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
The application was unable to start correctly (0xc000007b)
In my case the error occurred when I renamed a DLL after building it (using Visual Studio 2015), so that it fits the name expected by an executable, which depended on the DLL. After the renaming the list of exported symbols displayed by Dependency Walker was empty, and the said error message "The application was unable to start correctly" was displayed.
So it could be fixed by changing the output file name in the Visual Studio linker options.
D3.js: How to get the computed width and height for an arbitrary element?
Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGGraphicsElement) { // check if node is svg element
dimensions = node.getBBox();
} else { // else is html element
dimensions = node.getBoundingClientRect();
}
console.log(dimensions);
return dimensions;
}
Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.
_x000D_
_x000D_
var svg = d3.select('svg')
.attr('width', 50)
.attr('height', 50);
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGElement) {
dimensions = node.getBBox();
} else {
dimensions = node.getBoundingClientRect();
}
console.clear();
console.log(dimensions);
return dimensions;
}
var circle = svg
.append("circle")
.attr("r", 20)
.attr("cx", 30)
.attr("cy", 30)
.attr("fill", "red")
.on("click", function() { computeDimensions(circle); });
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #ffd;
}
.div {
display: inline-block;
background-color: blue;
margin-right: 30px;
width: 30px;
height: 30px;
}
_x000D_
<h3>
Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_
Retrieving Property name from lambda expression
This is another answer:
public static string GetPropertyName<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return metaData.PropertyName;
}
Log all queries in mysql
Start mysql with the --log option:
mysqld --log=log_file_name
or place the following in your my.cnf
file:
log = log_file_name
Either one will log all queries to log_file_name.
You can also log only slow queries using the --log-slow-queries
option instead of --log
. By default, queries that take 10 seconds or longer are considered slow, you can change this by setting long_query_time
to the number of seconds a query must take to execute before being logged.
Use PHP composer to clone git repo
I try to join the solutions mention here as there are some important points to it needed to list.
As mentioned in the @igorw's answer the URL to repository must be in that case specified in the composer.json file, however since in both cases the composer.json must exist (unlike the 2nd way @Mike Graf) publishing it on the Packagist is not that much different (furthermore also Github currently provides packages services as npm packages), only difference instead of literally inputting the URL at the packagist interface once being signed up.
Moreover, it has a shortcoming that it cannot rely on an external library that uses this approach as recursive repository definitions do not work in Composer. Furthermore, due to it, there seems to be a "bug" upon it, since the recursive definition failed at the dependency, respecifying the repositories explicitly in the root does not seem to be enough but also all the dependencies from the packages would have to be respecified.
With a composer file (answered Oct 18 '12 at 15:13 igorw)
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
Without a composer file (answered Jan 23 '13 at 17:28 Mike Graf)
"repositories": [
{
"type":"package",
"package": {
"name": "l3pp4rd/doctrine-extensions",
"version":"master",
"source": {
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git",
"reference":"master"
}
}
}
],
"require": {
"l3pp4rd/doctrine-extensions": "master"
}
How to use S_ISREG() and S_ISDIR() POSIX Macros?
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
Creating a REST API using PHP
In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:
- validating the data POSTed
make sure your API is sending the Content-Type
header to tell the client to expect a JSON response:
header('Content-Type: application/json');
echo json_encode($response);
Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.
If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController
with an add()
action/method.
There are a few starting point projects for RESTful APIs on GitHub that are worth a look.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
What is the difference between bottom-up and top-down?
Dynamic Programming is often called Memoization!
1.Memoization is the top-down technique(start solving the given problem by breaking it down) and dynamic programming is a bottom-up technique(start solving from the trivial sub-problem, up towards the given problem)
2.DP finds the solution by starting from the base case(s) and works its way upwards. DP solves all the sub-problems, because it does it bottom-up
Unlike Memoization, which solves only the needed sub-problems
DP has the potential to transform exponential-time brute-force solutions into polynomial-time algorithms.
DP may be much more efficient because its iterative
On the contrary, Memoization must pay for the (often significant) overhead due to recursion.
To be more simple, Memoization uses the top-down approach to solve the problem i.e. it begin with core(main) problem then breaks it into sub-problems and solve these sub-problems similarly. In this approach same sub-problem can occur multiple times and consume more CPU cycle, hence increase the time complexity. Whereas in Dynamic programming same sub-problem will not be solved multiple times but the prior result will be used to optimize the solution.
How to add Button over image using CSS?
If I understood correctly, I would change the HTML to something like this:
<div id="shop">
<div class="content">
<img src="http://placehold.it/182x121"/>
<a href="#">Counter-Strike 1.6 Steam</a>
</div>
</div>
Then I would be able to use position:absolute
and position:relative
to force the blue button down.
I have created a jsfiddle: http://jsfiddle.net/y9w99/
How to make node.js require absolute? (instead of relative)
The big picture
It seems "really bad" but give it time. It is, in fact, really good. The explicit require()
s give a total transparency and ease of understanding that is like a breath of fresh air during a project life cycle.
Think of it this way: You are reading an example, dipping your toes into Node.js and you've decided it is "really bad IMO." You are second-guessing leaders of the Node.js community, people who have logged more hours writing and maintaining Node.js applications than anyone. What is the chance the author made such a rookie mistake? (And I agree, from my Ruby and Python background, it seems at first like a disaster.)
There is a lot of hype and counter-hype surrounding Node.js. But when the dust settles, we will acknowledge that explicit modules and "local first" packages were a major driver of adoption.
The common case
Of course, node_modules
from the current directory, then the parent, then grandparent, great-grandparent, etc. is searched. So packages you have installed already work this way. Usually you can require("express")
from anywhere in your project and it works fine.
If you find yourself loading common files from the root of your project (perhaps because they are common utility functions), then that is a big clue that it's time to make a package. Packages are very simple: move your files into node_modules/
and put a package.json
there. Voila! Everything in that namespace is accessible from your entire project. Packages are the correct way to get your code into a global namespace.
Other workarounds
I personally don't use these techniques, but they do answer your question, and of course you know your own situation better than I.
You can set $NODE_PATH
to your project root. That directory will be searched when you require()
.
Next, you could compromise and require a common, local file from all your examples. That common file simply re-exports the true file in the grandparent directory.
examples/downloads/app.js (and many others like it)
var express = require('./express')
examples/downloads/express.js
module.exports = require('../../')
Now when you relocate those files, the worst-case is fixing the one shim module.
How to execute raw SQL in Flask-SQLAlchemy app
You can get the results of SELECT SQL queries using from_statement()
and text()
as shown here. You don't have to deal with tuples this way. As an example for a class User
having the table name users
you can try,
from sqlalchemy.sql import text
user = session.query(User).from_statement(
text("""SELECT * FROM users where name=:name""")
).params(name="ed").all()
return user
Change Text Color of Selected Option in a Select Box
ONE COLOR CASE - CSS only
Just to register my experience, where I wanted to set only the color of the selected option to a specific one.
I first tried to set by css only the color of the selected option with no success.
Then, after trying some combinations, this has worked for me with SCSS:
select {
color: white; // color of the selected option
option {
color: black; // color of all the other options
}
}
Take a look at a working example with only CSS:
_x000D_
_x000D_
select {_x000D_
color: yellow; // color of the selected option_x000D_
}_x000D_
_x000D_
select option {_x000D_
color: black; // color of all the other options_x000D_
}
_x000D_
<select id="mySelect">_x000D_
<option value="apple" >Apple</option>_x000D_
<option value="banana" >Banana</option>_x000D_
<option value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
For different colors, depending on the selected option, you'll have to deal with js.
How to take complete backup of mysql database using mysqldump command line utility
In addition to the --routines flag you will need to grant the backup user permissions to read the stored procedures:
GRANT SELECT ON `mysql`.`proc` TO <backup user>@<backup host>;
My minimal set of GRANT privileges for the backup user are:
GRANT USAGE ON *.* TO ...
GRANT SELECT, LOCK TABLES ON <target_db>.* TO ...
GRANT SELECT ON `mysql`.`proc` TO ...
How to access the content of an iframe with jQuery?
If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy).
A workaround is saving the external contents in a file, for example (in PHP):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
then, get the new file content (string) and parse it to html, for example (in jquery):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');
see if two files have the same content in python
I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.
There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can
- Compare file sizes first, discarding all which doesn't match
- If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file
Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)
Working with dictionaries/lists in R
Yes, the list
type is a good approximation. You can use names()
on your list to set and retrieve the 'keys':
> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12
$tac
[1] 22
$toe
[1] 33
> names(foo)
[1] "tic" "tac" "toe"
>
Swift: How to get substring from start to last index of character
func substr(myString: String, start: Int, clen: Int)->String
{
var index2 = string1.startIndex.advancedBy(start)
var substring2 = string1.substringFromIndex(index2)
var index1 = substring2.startIndex.advancedBy(clen)
var substring1 = substring2.substringToIndex(index1)
return substring1
}
substr(string1, start: 3, clen: 5)
Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?
In my case, I was getting this error despite registering an existing instance for the interface in question.
Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.
Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.
i.e.
container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());
becomes
container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();
So that IMapper can be resolved successfully here:
public class UserContext : BaseContext, IUserContext
{
public UserContext(IMapper _mapper) : base(_mapper)
{
}
...
}
How to link to a named anchor in Multimarkdown?
I tested Github Flavored Markdown for a while and can summarize with four rules:
- punctuation marks will be dropped
- leading white spaces will be dropped
- upper case will be converted to lower
- spaces between letters will be converted to
-
For example, if your section is named this:
## 1.1 Hello World
Create a link to it this way:
[Link](#11-hello-world)
Python: Tuples/dictionaries as keys, select, sort
A dictionary probably isn't what you should be using in this case. A more full featured library would be a better alternative. Probably a real database. The easiest would be sqlite. You can keep the whole thing in memory by passing in the string ':memory:' instead of a filename.
If you do want to continue down this path, you can do it with the extra attributes in the key or the value. However a dictionary can't be the key to a another dictionary, but a tuple can. The docs explain what's allowable. It must be an immutable object, which includes strings, numbers and tuples that contain only strings and numbers (and more tuples containing only those types recursively...).
You could do your first example with d = {('apple', 'red') : 4}
, but it'll be very hard to query for what you want. You'd need to do something like this:
#find all apples
apples = [d[key] for key in d.keys() if key[0] == 'apple']
#find all red items
red = [d[key] for key in d.keys() if key[1] == 'red']
#the red apple
redapples = d[('apple', 'red')]
Conversion failed when converting date and/or time from character string while inserting datetime
I had this issue when trying to concatenate getdate()
into a string that I was inserting into an nvarchar field.
I did some casting to get around it:
INSERT INTO [SYSTEM_TABLE] ([SYSTEM_PROP_TAG],[SYSTEM_PROP_VAL]) VALUES
(
'EMAIL_HEADER',
'<h2>111 Any St.<br />Anywhere, ST 11111</h2><br />' +
CAST(CAST(getdate() AS datetime2) AS nvarchar) +
'<br /><br /><br />'
)
That's a sanitized example. The key portion of that is:
...' + CAST(CAST(getdate() AS datetime2) AS nvarchar) + '...
Casted the date as datetime2
, then as nvarchar
to concatenate it.
How to compile makefile using MinGW?
I have MinGW and also mingw32-make.exe in my bin in the C:\MinGW\bin . same other I add bin path to my windows path. After that I change it's name to make.exe . Now I can Just write command "make" in my Makefile direction and execute my Makefile same as Linux.
pythonw.exe or python.exe?
If you're going to call a python script from some other process (say, from the command line), use pythonw.exe
. Otherwise, your user will continuously see a cmd
window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an email; python.exe
will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe
avoids this, but still sends the email.
Sharing url link does not show thumbnail image on facebook
I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.
<meta property="og:url" content="<?
$url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];;
echo htmlentities($url,ENT_QUOTES); ?>"/>
How to start a background process in Python?
I found this here:
On windows (win xp), the parent process will not finish until the longtask.py
has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS
Process Creation Flag to the underlying CreateProcess
function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
Can we use join for two different database tables?
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
At runtime, find all classes in a Java application that extend a base class
One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):
public class Dog extends Animal{
static
{
Animal a = new Dog();
//add a to the List
}
It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.
Choosing line type and color in Gnuplot 4.0
I've ran into this topic, because i was struggling with dashed lines too (gnuplot 4.6 patchlevel 0)
If you use:
set termoption dashed
Your posted code will work accordingly.
Related question:
However, if I want to export a png with:
set terminal png, this isn't working anymore. Anyone got a clue why?
Turns out, out, gnuplots png export library doesnt support this.
Possbile solutions:
- one can simply export to ps, then convert it with pstopng
- according to @christoph, if you use
pngcairo
as your terminal (set terminal pngcairo
) it will work
Preventing SQL injection in Node.js
The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.
Mockito : doAnswer Vs thenReturn
You should use thenReturn
or doReturn
when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.
thenReturn(T value)
Sets a return value to be returned when the method is called.
@Test
public void test_return() throws Exception {
Dummy dummy = mock(Dummy.class);
int returnValue = 5;
// choose your preferred way
when(dummy.stringLength("dummy")).thenReturn(returnValue);
doReturn(returnValue).when(dummy).stringLength("dummy");
}
Answer
is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.
Use doAnswer()
when you want to stub a void method with generic Answer
.
Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
@Test
public void test_answer() throws Exception {
Dummy dummy = mock(Dummy.class);
Answer<Integer> answer = new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
String string = invocation.getArgumentAt(0, String.class);
return string.length() * 2;
}
};
// choose your preferred way
when(dummy.stringLength("dummy")).thenAnswer(answer);
doAnswer(answer).when(dummy).stringLength("dummy");
}
LaTeX: Multiple authors in a two-column article
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
How to force a component's re-rendering in Angular 2?
tx, found the workaround I needed:
constructor(private zone:NgZone) {
// enable to for time travel
this.appStore.subscribe((state) => {
this.zone.run(() => {
console.log('enabled time travel');
});
});
running zone.run will force the component to re-render
jQuery check if <input> exists and has a value
Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
/// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
if ( !arguments.length ) {
/// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
/// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
So, you'll either get undefined
or ""
or null
-- all of which evaluate as false in if statements.
How do I commit only some files?
Get a list of files you want to commit
$ git status
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file1
modified: file2
modified: file3
modified: file4
Add the files to staging
$ git add file1 file2
Check to see what you are committing
$ git status
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: file1
modified: file2
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file3
modified: file4
Commit the files with a commit message
$ git commit -m "Fixed files 1 and 2"
If you accidentally commit the wrong files
$ git reset --soft HEAD~1
If you want to unstage the files and start over
$ git reset
Unstaged changes after reset:
M file1
M file2
M file3
M file4
Setting the Vim background colors
As vim's own help on set background
says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."
For example
:highlight Normal ctermfg=grey ctermbg=darkblue
will write in white on blue on your color terminal.
React Hooks useState() with Object
I'm late to the party.. :)
@aseferov answer works very well when the intention is to re-enter the entire object structure. However, if the target/goal is to update a specific field value in an Object, I believe the approach below is better.
situation:
const [infoData, setInfoData] = useState({
major: {
name: "John Doe",
age: "24",
sex: "M",
},
minor:{
id: 4,
collegeRegion: "south",
}
});
Updating a specific record will require making a recall to the previous State prevState
Here:
setInfoData((prevState) => ({
...prevState,
major: {
...prevState.major,
name: "Tan Long",
}
}));
perhaps
setInfoData((prevState) => ({
...prevState,
major: {
...prevState.major,
name: "Tan Long",
},
minor: {
...prevState.minor,
collegeRegion: "northEast"
}));
I hope this helps anyone trying to solve a similar problem.
How can I test if a letter in a string is uppercase or lowercase using JavaScript?
There's a really simple answer, which nobody else has mentioned:
function isLowerCase(str) {
return str !== str.toUpperCase();
}
If str.toUpperCase()
does not return the same str
, it has to be lower case. To test for upper case you change it to str !== str.toLowererCase()
.
Unlike some other answers, it works correctly on non-alpha characters (returns false
) and it works for other alphabets, accented characters etc.
Display PDF within web browser
We render the PDF file pages as PNG files on the server using JPedal (a java library). That, combined with some javascript, gives us high control over visualization and navigation.
System.IO.IOException: file used by another process
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
How do I mock a static method that returns void with PowerMock?
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
Explain why constructor inject is better than other options
By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner
We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.
In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!
But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.
Edit:
Q1: And how to prevent container from creating bean by constructor with null
values instead of missing beans?
You have no option to really miss any <constructor-arg>
(in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null
in your <constructor-arg>
intentionally. Then there is nothing IoC container can do or need to do with it!
How to remove files from git staging area?
If unwanted files were added to the staging area but not yet committed, then a simple reset will do the job:
$ git reset HEAD file
# Or everything
$ git reset HEAD .
To only remove unstaged changes in the current working directory, use:
git checkout -- .
Is an empty href valid?
It is valid.
However, standard practice is to use href="#"
or sometimes href="javascript:;"
.
Going to a specific line number using Less in Unix
From within less (in Linux):
g and the line number to go forward
G and the line number to go backwards
Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.
An example; you want to go to line 320123 of a file,
press 'g' and after the colon type in the number 320123
Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.
NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:
less +12345 -N /var/log/hugelogfile
This will open a file displaying the line numbers and starting at line 12345
Source: man 1 less and built-in help in less (less 418)
How to press/click the button using Selenium if the button does not have the Id?
You can achieve this by using cssSelector
// Use of List web elements:
String cssSelectorOfLoginButton="input[type='button'][id='login']";
//****Add cssSelector of your 1st webelement
//List<WebElement> button
=driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
button.get(0).click();
I hope this work for you
null terminating a string
'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.
When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.
multiple classes on single element html
Short Answer
Yes.
Explanation
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
CSS
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
HTML
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
How to deploy ASP.NET webservice to IIS 7?
- rebuild project in VS
- copy project folder to iis folder, probably C:\inetpub\wwwroot\
- in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
- add web service to created website, almost the same as 3.
- INSTALL ASP
for windows 7 and .net 4.0:
c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
- check access to web service on your browser
How to replace multiple substrings of a string?
Here is a variant of the first solution using reduce, in case you like being functional. :)
repls = {'hello' : 'goodbye', 'world' : 'earth'}
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)
martineau's even better version:
repls = ('hello', 'goodbye'), ('world', 'earth')
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls, s)
Creating PHP class instance with a string
You can simply use the following syntax to create a new class (this is handy if you're creating a factory):
$className = $whatever;
$object = new $className;
As an (exceptionally crude) example factory method:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
How to turn off INFO logging in Spark?
I you want to keep using the logging (Logging facility for Python) you can try splitting configurations for your application and for Spark:
LoggerManager()
logger = logging.getLogger(__name__)
loggerSpark = logging.getLogger('py4j')
loggerSpark.setLevel('WARNING')
How to increase size of DOSBox window?
Looking again at your question, I think I see what's wrong with your conf file. You set:
fullresolution=1366x768
windowresolution=1366x768
That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.
So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.
The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).
Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.
Hope this helps you better.
How can I clear or empty a StringBuilder?
I think many of the answers here may be missing a quality method included in StringBuilder
: .delete(int start, [int] end)
. I know this is a late reply; however, this should be made known (and explained a bit more thoroughly).
Let's say you have a StringBuilder table - which you wish to modify, dynamically, throughout your program (one I am working on right now does this), e.g.
StringBuilder table = new StringBuilder();
If you are looping through the method and alter the content, use the content, then wish to discard the content to "clean up" the StringBuilder
for the next iteration, you can delete it's contents, e.g.
table.delete(int start, int end).
start and end being the indices of the chars you wish to remove. Don't know the length in chars and want to delete the whole thing?
table.delete(0, table.length());
NOW, for the kicker. StringBuilders
, as mentioned previously, take a lot of overhead when altered frequently (and can cause safety issues with regard to threading); therefore, use StringBuffer
- same as StringBuilder
(with a few exceptions) - if your StringBuilder
is used for the purpose of interfacing with the user.
GridView sorting: SortDirection always Ascending
You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.
Example:
DataTable sourceTable = GridAttendence.DataSource as DataTable;
DataView view = new DataView(sourceTable);
string[] sortData = ViewState["sortExpression"].ToString().Trim().Split(' ');
if (e.SortExpression == sortData[0])
{
if (sortData[1] == "ASC")
{
view.Sort = e.SortExpression + " " + "DESC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
Best way to format multiple 'or' conditions in an if statement (Java)
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>
, or if you just want to test membership for a single statement, a Set<Integer>
would do. That's a lot of firepower for a simple if
statement, however, so without more context it's kind of hard to guide you in the right direction.
How to use format() on a moment.js duration?
Use moment-duration-format.
Client Framework (ex: React)
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
Server (node.js)
const moment = require("moment-timezone");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
Dart: mapping a list (list.map)
you can use
moviesTitles.map((title) => Tab(text: title)).toList()
example:
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs:
moviesTitles.map((title) => Tab(text: title)).toList()
,
),
How to read data from a zip file without having to unzip the entire file
Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):
string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
(new System.IO.StreamReader(
System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
.Entries.Where(x => x.Name.Equals(targetFileName,
StringComparison.InvariantCulture))
.FirstOrDefault()
.Open(), Encoding.UTF8)
.ReadToEnd())
.ToArray());
node.js hash string?
If you just want to md5 hash a simple string I found this works for me.
var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de
Android java.exe finished with non-zero exit value 1
After adding a jar file to a project's lib folder and after adding it to the build.gradle file as compile'path example' when you sync the gradle it add an additional line as compile files('libs/example.jar'). You just need to remove the line you previously added to the build.gradle file i.e. the compile'path example' after the gradle sync. You also need to remove the line compile fileTree(dir: 'libs', include: '*.jar')
Better way to right align text in HTML Table
This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.
td + td + td { text-align: right; }
td + td + td + td { text-align: left; }
How to discard local commits in Git?
git reset --hard origin/master
will remove all commits not in origin/master
where origin
is the repo name and master
is the name of the branch.
Node.js request CERT_HAS_EXPIRED
I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.
After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(
Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.
How to find if a given key exists in a C++ std::map
C++17
simplified this a bit more with an If statement with initializer
.
This way you can have your cake and eat it too.
if ( auto it{ m.find( "key" ) }; it != std::end( m ) )
{
// Use `structured binding` to get the key
// and value.
auto[ key, value ] { *it };
// Grab either the key or value stored in the pair.
// The key is stored in the 'first' variable and
// the 'value' is stored in the second.
auto mkey{ it->first };
auto mvalue{ it->second };
// That or just grab the entire pair pointed
// to by the iterator.
auto pair{ *it };
}
else
{
// Key was not found..
}
how to set active class to nav menu from twitter bootstrap
(function (window) {
bs3Utils = {}
bs3Utils.nav = {
activeTab: function (tabId) {
/// <summary>
/// ???????tab
/// </summary>
/// <param name="tabId"></param>
$('.nav-tabs a[href="#' + tabId + '"]').tab('show');
}
}
window.bs3Utils = bs3Utils;
})(window);
example:
var _actvieTab = _type == '0' ? 'portlet_tab2_1' : 'portlet_tab2_2';
bs3Utils.nav.activeTab(_actvieTab);
<ul class="nav nav-tabs">
<li class="active">
<a href="#portlet_tab2_1" data-toggle="tab">?-???? </a>
</li>
<li>
<a href="#portlet_tab2_2" data-toggle="tab">?-???? </a>
</li>
</ul>
What is the correct way to read a serial port using .NET framework?
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
How to redirect user's browser URL to a different page in Nodejs?
If you are using Express
, the cleanest complete answer is this
const express = require('express')
const app = express()
app.get('*', (req, res) => {
// REDIRECT goes here
res.redirect('https://www.YOUR_URL.com/')
})
app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})
How do I push a local Git branch to master branch in the remote?
As people mentioned in the comments you probably don't want to do that...
The answer from mipadi is absolutely correct if you know what you're doing.
I would say:
git checkout master
git pull # to update the state to the latest remote master state
git merge develop # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch
select and echo a single field from mysql db using PHP
$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];
but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.
How to comment out a block of Python code in Vim
You could add the following mapping to your .vimrc
vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>
Highlight your block with:
Shift+v
#
to comment your lines from the first column.
-#
to uncomment the same way.
php error: Class 'Imagick' not found
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
Convert Unicode to ASCII without errors in Python
For broken consoles like cmd.exe
and HTML output you can always use:
my_unicode_string.encode('ascii','xmlcharrefreplace')
This will preserve all the non-ascii chars while making them printable in pure ASCII and in HTML.
WARNING: If you use this in production code to avoid errors then most likely there is something wrong in your code. The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context.
And finally, if you are on windows and use cmd.exe then you can type chcp 65001
to enable utf-8 output (works with Lucida Console font). You might need to add myUnicodeString.encode('utf8')
.
Error creating bean with name
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
How to add/subtract dates with JavaScript?
Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.
HTML:
<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />
JavaScript:
var counter = 0;
$("#SubtractDay").click(function() {
counter--;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
counter++;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
jsfiddle
What does "request for member '*******' in something not a structure or union" mean?
It may also happen in the following case:
eg. if we consider the push function of a stack:
typedef struct stack
{
int a[20];
int head;
}stack;
void push(stack **s)
{
int data;
printf("Enter data:");
scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}
main()
{
stack *s;
s=(stack *)calloc(1,sizeof(stack));
s->head=-1;
push(&s);
return 0;
}
The error is in the push function and in the commented line. The pointer s
has to be included within the parentheses. The correct code:
scanf("%d",&( (*s)->a[++(*s)->head]));
How do I show the number keyboard on an EditText in android?
Below code will only allow numbers "0123456789”, even if you accidentally type other than "0123456789”, edit text will not accept.
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
When or Why to use a "SET DEFINE OFF" in Oracle Database
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
How do you fadeIn and animate at the same time?
$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');
However, this doesn't appear to work on display: none
elements (as fadeIn
does). So, you might need to put this beforehand:
$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);
How to find all occurrences of an element in a list
How about:
In [1]: l=[1,2,3,4,3,2,5,6,7]
In [2]: [i for i,val in enumerate(l) if val==3]
Out[2]: [2, 4]
Change the image source on rollover using jQuery
I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:
#element {
width: 100px; /* width of image */
height: 200px; /* height of image */
background-image: url(/path/to/image.jpg);
}
#element:hover {
background-image: url(/path/to/other_image.jpg);
}
There's a longer description here
Even better, however, is to use sprites: simple-css-image-rollover
Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin
None of these solutions really met my expectations. I wanted to subclass the TextField since I don't want to set the border manually all the time. I also wanted to change the border color e.g. for an error. So here's my solution with Anchors
:
class CustomTextField: UITextField {
var bottomBorder = UIView()
override func awakeFromNib() {
// Setup Bottom-Border
self.translatesAutoresizingMaskIntoConstraints = false
bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
bottomBorder.translatesAutoresizingMaskIntoConstraints = false
addSubview(bottomBorder)
bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength
}
}
---- Optional ----
To change the color add sth like this to the CustomTextField Class
:
@IBInspectable var hasError: Bool = false {
didSet {
if (hasError) {
bottomBorder.backgroundColor = UIColor.red
} else {
bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)
}
}
}
And to trigger the Error call this after you created an instance of CustomTextField
textField.hasError = !textField.hasError
Hope it helps someone ;)
A simple algorithm for polygon intersection
You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)
Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.
Now given two polygons in that representation, you can compute the intersection as:
Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.
You get a new polygon following the same representation.
Since convex polygon intersection is easy, this intersection finding should be easy too.
This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.
Get a substring of a char*
Use char* strncpy(char* dest, char* src, int n)
from <cstring>
. In your case you will need to use the following code:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
Full documentation on the strncpy
function here.
scikit-learn random state in splitting dataset
If you don't mention the random_state in the code, then whenever you execute your code a new random value is generated and the train and test datasets would have different values each time.
However, if you use a particular value for random_state(random_state = 1 or any other value) everytime the result will be same,i.e, same values in train and test datasets.
SQL Server table creation date query
For SQL Server 2005 upwards:
SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables
For SQL Server 2000 upwards:
SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so
WHERE it.[TABLE_NAME] = so.[name]
RuntimeWarning: DateTimeField received a naive datetime
Use django.utils.timezone.make_aware function to make your naive datetime objects timezone aware and avoid those warnings.
It converts naive datetime object (without timezone info) to the one that has timezone info (using timezone specified in your django settings if you don't specify it explicitly as a second argument):
import datetime
from django.conf import settings
from django.utils.timezone import make_aware
naive_datetime = datetime.datetime.now()
naive_datetime.tzinfo # None
settings.TIME_ZONE # 'UTC'
aware_datetime = make_aware(naive_datetime)
aware_datetime.tzinfo # <UTC>
href around input type submit
I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.
IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.
If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.
StringIO in Python3
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The StringIO
and cStringIO
modules are gone. Instead, import the io
module and use io.StringIO
or io.BytesIO
for text and data
respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO
module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
How to remove duplicate white spaces in string using Java?
You can use the regex
(\s)\1
and
replace it with $1
.
Java code:
str = str.replaceAll("(\\s)\\1","$1");
If the input is "foo\t\tbar "
you'll get "foo\tbar "
as output
But if the input is "foo\t bar"
it will remain unchanged because it does not have any consecutive whitespace characters.
If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:
str = str.replaceAll("\\s+"," ");
But if you want to replace two consecutive white space with a single space you should do:
str = str.replaceAll("\\s{2}"," ");
Printing prime numbers from 1 through 100
Finding primes up to a 100 is especially nice and easy:
printf("2 3 "); // first two primes are 2 and 3
int m5 = 25, m7 = 49, i = 5, d = 4;
for( ; i < 25; i += (d=6-d) )
{
printf("%d ", i); // all 6-coprimes below 5*5 are prime
}
for( ; i < 49; i += (d=6-d) )
{
if( i != m5) printf("%d ", i);
if( m5 <= i ) m5 += 10; // no multiples of 5 below 7*7 allowed!
}
for( ; i < 100; i += (d=6-d) ) // from 49 to 100,
{
if( i != m5 && i != m7) printf("%d ", i);
if( m5 <= i ) m5 += 10; // sieve by multiples of 5,
if( m7 <= i ) m7 += 14; // and 7, too
}
The square root of 100 is 10, and so this rendition of the sieve of Eratosthenes with the 2-3 wheel uses the multiples of just the primes above 3 that are not greater than 10 -- viz. 5 and 7 alone! -- to sieve the 6-coprimes below 100 in an incremental fashion.
Java enum with multiple value types
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
How to use background thread in swift?
Multi purpose function for thread
public enum QueueType {
case Main
case Background
case LowPriority
case HighPriority
var queue: DispatchQueue {
switch self {
case .Main:
return DispatchQueue.main
case .Background:
return DispatchQueue(label: "com.app.queue",
qos: .background,
target: nil)
case .LowPriority:
return DispatchQueue.global(qos: .userInitiated)
case .HighPriority:
return DispatchQueue.global(qos: .userInitiated)
}
}
}
func performOn(_ queueType: QueueType, closure: @escaping () -> Void) {
queueType.queue.async(execute: closure)
}
Use it like :
performOn(.Background) {
//Code
}
How to avoid soft keyboard pushing up my layout?
I did have the same problem and at first I added:
<activity
android:name="com.companyname.applicationname"
android:windowSoftInputMode="adjustPan">
to my manifest file. But this alone did not solve the issue. Then as mentioned by Artem Russakovskii, I added:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="false">
</ScrollView>
in the scrollview.
This is what worked for me.
Setting a div's height in HTML with CSS
The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.
How to open a link in new tab (chrome) using Selenium WebDriver?
Selenium 4 is already included this feature now, you can directly
open new Tab or new Window with any URL.
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
driver.get("www.Url1.com");
// below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);
// below code will navigate you to your desirable Url
driver.get("www.Url2.com");
download Maven dependencies, this is what I downloaded -
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/
watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s
google out for - WebDriverManager selenium 4
How to return rows from left table not found in right table?
This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.
For me, the most understandable way I can think of is like so:
--Users that bought from us 6 months ago and between 3 months ago.
DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @6To3MonthsUsers
select u.ID,opd.OrderDate
from OrdersPaid opd
inner join Orders o
on opd.OrderID = o.ID
inner join Users u
on o.BuyerID = u.ID
where 1=1
and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())
--Users that bought from us in the last 3 months
DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @Last3MonthsUsers
select u.ID,opd.OrderDate
from OrdersPaid opd
inner join Orders o
on opd.OrderID = o.ID
inner join Users u
on o.BuyerID = u.ID
where 1=1
and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()
Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.
There are 2 simple ways to achieve that:
Using Left Join:
select distinct a.UserID
from @6To3MonthsUsers a
left join @Last3MonthsUsers b
on a.UserID = b.UserID
where b.UserID is null
Not in:
select distinct a.UserID
from @6To3MonthsUsers a
where a.UserID not in (select b.UserID from @Last3MonthsUsers b)
Both ways will get me the same result, I personally prefer the second way because it's more readable.
Web Reference vs. Service Reference
Add Web Reference is the old-style, deprecated ASP.NET webservices (ASMX) technology (using only the XmlSerializer for your stuff) - if you do this, you get an ASMX client for an ASMX web service. You can do this in just about any project (Web App, Web Site, Console App, Winforms - you name it).
Add Service Reference is the new way of doing it, adding a WCF service reference, which gives you a much more advanced, much more flexible service model than just plain old ASMX stuff.
Since you're not ready to move to WCF, you can also still add the old-style web reference, if you really must: when you do a "Add Service Reference", on the dialog that comes up, click on the [Advanced] button in the button left corner:
and on the next dialog that comes up, pick the [Add Web Reference] button at the bottom.
Online SQL syntax checker conforming to multiple databases
I don't know of any such, and my experience is that it doesn't currently exist. Most are side by side comparisons of two databases. That information requires experts in all the databases encountered, which isn't common. Versions depend too, to know what is supported.
ANSI functions are making strides to ensure syntax is supported across databases, but it's dependent on vendors implementing the spec. And to date, they aren't implementing the entire ANSI spec at a time.
But you can crowd source on sites like this one by asking specific questions and including the databases involved and the versions used.
Iterating each character in a string using Python
As Johannes pointed out,
for c in "string":
#do something with c
You can iterate pretty much anything in python using the for loop
construct,
for example, open("file.txt")
returns a file object (and opens the file), iterating over it iterates over lines in that file
with open(filename) as f:
for line in f:
# do something with line
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the for
loop work on it.
Simply implement an iterator that defines a next()
method, and implement an __iter__
method on a class to make it iterable. (the __iter__
of course, should return an iterator object, that is, an object that defines next()
)
See official documentation
Bootstrap: How to center align content inside column?
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
Rotate label text in seaborn factorplot
I had a problem with the answer by @mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add
plt.xticks(rotation=45)
How do I sort an observable collection?
I needed to be able to sort by multiple things not just one. This answer is based on some of the other answers but it allows for more complex sorting.
static class Extensions
{
public static void Sort<T, TKey>(this ObservableCollection<T> collection, Func<ObservableCollection<T>, TKey> sort)
{
var sorted = (sort.Invoke(collection) as IOrderedEnumerable<T>).ToArray();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
}
When you use it, pass in a series of OrderBy/ThenBy calls. Like this:
Children.Sort(col => col.OrderByDescending(xx => xx.ItemType == "drive")
.ThenByDescending(xx => xx.ItemType == "folder")
.ThenBy(xx => xx.Path));
How do I get a file extension in PHP?
Although the "best way" is debatable, I believe this is the best way for a few reasons:
function getExt($path)
{
$basename = basename($path);
return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
- It works with multiple parts to an extension, eg
tar.gz
- Short and efficient code
- It works with both a filename and a complete path
Index of element in NumPy array
This problem can be solved efficiently using the numpy_indexed library (disclaimer: I am its author); which was created to address problems of this type. npi.indices can be viewed as an n-dimensional generalisation of list.index. It will act on nd-arrays (along a specified axis); and also will look up multiple entries in a vectorized manner as opposed to a single item at a time.
a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]
import numpy_indexed as npi
assert all(i == npi.indices(a, b))
This solution has better time complexity (n log n at worst) than any of the previously posted answers, and is fully vectorized.
HTTP error 403 in Python 3 Web Scraping
"This is probably because of mod_security or some similar server security feature which blocks known
spider/bot
user agents (urllib uses something like python urllib/3.3.0, it's easily detected)" - as already mentioned by Stefano Sanfilippo
from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
The web_byte is a byte object returned by the server and the content type present in webpage is mostly utf-8.
Therefore you need to decode web_byte using decode method.
This solves complete problem while I was having trying to scrap from a website using PyCharm
P.S -> I use python 3.4
How to set a fixed width column with CSS flexbox
You should use the flex
or flex-basis
property rather than width
. Read more on MDN.
.flexbox .red {
flex: 0 0 25em;
}
The flex
CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:
flex-grow: 0; /* do not grow - initial value: 0 */
flex-shrink: 0; /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height - initial value: auto */
A simple demo shows how to set the first column to 50px
fixed width.
_x000D_
_x000D_
.flexbox {_x000D_
display: flex;_x000D_
}_x000D_
.red {_x000D_
background: red;_x000D_
flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
background: green;_x000D_
flex: 1;_x000D_
}_x000D_
.blue {_x000D_
background: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
<div class="red">1</div>_x000D_
<div class="green">2</div>_x000D_
<div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
See the updated codepen based on your code.
Git Push ERROR: Repository not found
The Problem: Github is not familiar with your repository from some reason.
The Error: prompted in git cli like the following:
remote: Repository not found. fatal: repository
‘https://github.com/MyOrganization/projectName.git/’ not found
The Solution : 2 Options
Github might not familiar with your credentials: - The first Option is to clone the project with the right credentials user:password
in case you forgot this Or generate ssh token and adjust this key in your Github. aka git push https://<userName>:<password>@github.com/Company/repositoryName.git
Repo Permissions Issue with some users - In my Use case, I solved this issue when I realized I don't have the right collaborator permissions on Github in my private repo. Users could clone the project but not perform any actions on origin. In order to solve this:
Go to Repository on Github -> Settings -> Collaborators & Teams -> Add
Member/Maintainer your users -> Now they got the permission to commit
and push
How do I install chkconfig on Ubuntu?
But how do I run this? I tried typing: sudo chkconfig.install
which doesn't work.
I'm not sure where you got this package or what it contains; A url of download would be helpful.
Without being able to look at the contents of chkconfig.install; I'm surprised to find a unix tool like chkconfig to be bundled in a zip archive, maybe it is still yet to be uncompressed, a tar.gz? but maybe it is a shell script?
I should suggest editing it and seeing what you are executing.
sh chkconfig.install
or ./chkconfig.install
; which might work....but my suggestion would be to learn to use update-rc.d as the other answers have suggested but do not speak directly to the question...which is pretty hard to answer without being able to look at the data yourself.
How to get a cookie from an AJAX response?
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
http://www.w3schools.com/js/js_cookies.asp
Git copy file preserving history
This process preserve history, but is little workarround:
# make branchs to new files
$: git mv arquivos && git commit
# in original branch, remove original files
$: git rm arquivos && git commit
# do merge and fix conflicts
$: git merge branch-copia-arquivos
# back to original branch and revert commit removing files
$: git revert commit
How to get Android application id?
The PackageInfo.sharedUserId
field will show the user Id assigned in the manifest.
If you want two applications to have the same userId, so they can see each other's data and run in the same process, then assign them the same userId in the manifest:
android:sharedUserId="string"
The two packages with the same sharedUserId need to have the same signature too.
I would also recommend reading here for a nudge in the right direction.
how to install Lex and Yacc in Ubuntu?
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
jQuery Ajax calls and the Html.AntiForgeryToken()
Okay lots of posts here, none of them helped me, days and days of google, and still no further I got to the point the wr-writing the whole app from scratch, and then I noticed this little nugget in my Web.confg
<httpCookies requireSSL="false" domain="*.localLookup.net"/>
Now I don't know why I added it however I have since noticed, its ignored in debug mode and not in a production mode (IE Installed to IIS Somewhere)
For me the solution was one of 2 options, since I don't remember why I added it I cant be sure other things don't depend on it, and second the domain name must be all lower case and a TLD not like ive done in *.localLookup.net
Maybe it helps maybe it don't. I hope it does help someone
How to hide/show more text within a certain length (like youtube)
Put text inside Your Text Here
and copy the script inside your js file. You are ready to go. Working code for see more.. and see less.. options. Works for dynamic as well as static texts
<div class="item">
Your Text Here
</div>
<script type="text/javascript">
$(function(){ /* to make sure the script runs after page load */
$('.item').each(function(event){ /* select all divs with the item class */
var max_length = 150; /* set the max content length before a read more link will be added */
if($(this).html().length > max_length){ /* check for content length */
var short_content = $(this).html().substr(0,max_length); /* split the content in two parts */
var long_content = $(this).html().substr(max_length);
$(this).html(short_content+'<a href="#" class="read_more">Show More</a>'+
'<span class="more_text" style="display:none;">'+long_content+'</span>'+'<a href="#" class="read_less" style="display:none;">Show Less</a>'); /* Alter the html to allow the read more functionality */
$(this).find('a.read_more').click(function(event){ /* find the a.read_more element within the new html and bind the following code to it */
event.preventDefault(); /* prevent the a from changing the url */
$(this).hide(); /* hide the read more button */
$('.read_less').show(); /* show read less button */
$(this).parents('.item').find('.more_text').show(); /* show the .more_text span */
});
$(this).find('a.read_less').click(function(event){
event.preventDefault();
$(this).hide(); /* hide the read more button */
$('.read_less').hide();
$('.read_more').show();
$(this).parents('.item').find('.more_text').hide();
});
}
});
});
</script>
Convert.ToDateTime: how to set format
DateTime
doesn't have a format. the format only applies when you're turning a DateTime
into a string, which happens implicitly you show the value on a form, web page, etc.
Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).
appending array to FormData and send via AJAX
TransForm three formats of Data to FormData :
1. Single value like string, Number or Boolean
let sampleData = {
activityName: "Hunting3",
activityTypeID: 2,
seasonAssociated: true,
};
2. Array to be Array of Objects
let sampleData = {
activitySeason: [
{ clientId: 2000, seasonId: 57 },
{ clientId: 2000, seasonId: 57 },
],
};
3. Object holding key value pair
let sampleData = {
preview: { title: "Amazing World", description: "Here is description" },
};
The that make our life easy:
function transformInToFormObject(data) {
let formData = new FormData();
for (let key in data) {
if (Array.isArray(data[key])) {
data[key].forEach((obj, index) => {
let keyList = Object.keys(obj);
keyList.forEach((keyItem) => {
let keyName = [key, "[", index, "]", ".", keyItem].join("");
formData.append(keyName, obj[keyItem]);
});
});
} else if (typeof data[key] === "object") {
for (let innerKey in data[key]) {
formData.append(`${key}.${innerKey}`, data[key][innerKey]);
}
} else {
formData.append(key, data[key]);
}
}
return formData;
}
Example :
Input Data
let sampleData = {
activityName: "Hunting3",
activityTypeID: 2,
seasonAssociated: true,
activitySeason: [
{ clientId: 2000, seasonId: 57 },
{ clientId: 2000, seasonId: 57 },
],
preview: { title: "Amazing World", description: "Here is description" },
};
Output FormData :
activityName: Hunting3
activityTypeID: 2
seasonAssociated: true
activitySeason[0].clientId: 2000
activitySeason[0].seasonId: 57
activitySeason[1].clientId: 2000
activitySeason[1].seasonId: 57
preview.title: Amazing World
preview.description: Here is description
Permissions for /var/www/html
You just need 775
for /var/www/html
as long as you are logging in as myuser. The 7
octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:
chmod -R g+w /var/www/html
How can I rename a field for all documents in MongoDB?
You can use:
db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);
Or to just update the docs which contain the property:
db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);
The false, true
in the method above are: { upsert:false, multi:true }
. You need the multi:true
to update all your records.
Or you can use the former way:
remap = function (x) {
if (x.additional){
db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
}
}
db.foo.find().forEach(remap);
In MongoDB 3.2 you can also use
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
The general syntax of this is
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
JPQL SELECT between date statement
public List<Student> findStudentByReports(Date startDate, Date endDate) {
System.out.println("call findStudentMethd******************with this pattern"
+ startDate
+ endDate
+ "*********************************************");
return em
.createQuery(
"' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
+ "'")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}
PHP remove commas from numeric strings
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
When would you use the Builder Pattern?
You use it when you have lots of options to deal with. Think about things like jmock:
m.expects(once())
.method("testMethod")
.with(eq(1), eq(2))
.returns("someResponse");
It feels a lot more natural and is...possible.
There's also xml building, string building and many other things. Imagine if java.util.Map
had put as a builder. You could do stuff like this:
Map<String, Integer> m = new HashMap<String, Integer>()
.put("a", 1)
.put("b", 2)
.put("c", 3);
How to check if a file exists in a folder?
Since nobody said how to check if the file exists AND get the current folder the executable is in (Working Directory):
if (File.Exists(Directory.GetCurrentDirectory() + @"\YourFile.txt")) {
//do stuff
}
The @"\YourFile.txt"
is not case sensitive, that means stuff like @"\YoUrFiLe.txt"
and @"\YourFile.TXT"
or @"\yOuRfILE.tXt"
is interpreted the same.