In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.
[myButton setTitle:@"Play" forState:UIControlStateNormal];
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>
Follow below steps:
Must put the html files in resources/templates/
Replace the @RestController
with @Controller
Remove if you are using any view resolvers.
Your controller method should return file name of view without extension like return "index"
Include the below dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>`
For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:
/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
if (list == null || list.Count == 0) return;
//get type from 0th member
Type t = list[0].GetType();
string newLine = Environment.NewLine;
if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));
using (var sw = new StreamWriter(csvCompletePath))
{
//make a new instance of the class name we figured out to get its props
object o = Activator.CreateInstance(t);
//gets all properties
PropertyInfo[] props = o.GetType().GetProperties();
//foreach of the properties in class above, write out properties
//this is the header row
sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);
//this acts as datarow
foreach (T item in list)
{
//this acts as datacolumn
var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
.ToArray());
sw.Write(row + newLine);
}
}
}
composer create-project laravel/laravel ProjectName
Try adding C:\path\to\java\jre\bin
to your system environment variable PATH and run again. That worked for me!
Make sure that your sas.png
is marked as Build Action: Content
and Copy To Output Directory: Copy Always
in its Visual Studio Properties
...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext
is string
path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image
would be automatically loaded at runtime.
if we make the particular activity
as
android:exported="true"
it will be the launching activity
.
Click on the module name just to the left of the run button
and click on "Edit configurations..." Now make sure "Launch default Activity"
is selected.
A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.
This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.
So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.
This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.
Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.
If you have a Red Hat server use yum. apt-get is only for Debian, Ubuntu and some other related linux.
Why would you want to use apt-get anyway? (It seems like you know what yum is.)
There's no Console.writeline
in Java. Its in .NET.
Console and standard out are not same. If you read the Javadoc page you mentioned, you will see that an application can have access to a console only if it is invoked from the command line and the output is not redirected like this
java -jar MyApp.jar > MyApp.log
Other such cases are covered in SimonJ's answer, though he missed out on the point that there's no Console.writeline
.
Expanding on this answer one could use a stored procedure:
CALL duplicate_table('tableName');
Which will result in a duplicate table called tableName_20181022235959
If called when
SELECT NOW();
results:
2018-10-22 23:59:59
DELIMITER $$
CREATE PROCEDURE duplicate_table(IN tableName VARCHAR(255))
BEGIN
DECLARE schemaName VARCHAR(255) DEFAULT SCHEMA();
DECLARE today VARCHAR(14) DEFAULT REPLACE(REPLACE(REPLACE(NOW(), '-', ''), ' ', ''), ':', ''); -- update @ year 10000
DECLARE backupTableName VARCHAR(255) DEFAULT CONCAT(tableName, '_', today);
IF fn_table_exists(schemaName, tableName)
THEN
CALL statement(CONCAT('CREATE TABLE IF NOT EXISTS ', backupTableName,' LIKE ', tableName));
CALL statement(CONCAT('INSERT INTO ', backupTableName,' SELECT * FROM ', tableName));
CALL statement(CONCAT('CHECKSUM TABLE ', backupTableName,', ', tableName));
ELSE
SELECT CONCAT('ERROR: Table "', tableName, '" does not exist in the schema "', schemaName, '".') AS ErrorMessage;
END IF;
END $$
DELIMITER ;
DELIMITER $$
CREATE FUNCTION fn_table_exists(schemaName VARCHAR(255), tableName VARCHAR(255))
RETURNS TINYINT(1)
BEGIN
DECLARE totalTablesCount INT DEFAULT (
SELECT COUNT(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = schemaName COLLATE utf8_general_ci)
AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
);
RETURN IF(
totalTablesCount > 0,
TRUE,
FALSE
);
END $$
DELIMITER ;
DELIMITER $$
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
BEGIN
SET @dynamic_statement := dynamic_statement;
PREPARE prepared_statement FROM @dynamic_statement;
EXECUTE prepared_statement;
DEALLOCATE PREPARE prepared_statement;
END $$
DELIMITER ;
Probably to guarantee that public webservices will be unique.
It always makes me think of delicious deep fried treats...
use MD5
,
$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
but MD5
is insecure. Use SHA2
.
Add a reference to it in your project and a using clause at the top of the CS file where you want to use it.
Adding a reference:
Adding a using clause:
Add "using [namespace];" to the CS file where you want to reference your library. So, if the library you want to reference has a namespace called MyLibrary, add the following to the CS file:
using MyLibrary;
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Credits : AngularJS Post - Igor Minar
I had this issue on Windows 7. This is apparently an incompatibility issue and the solution is as follows:
Download the libmySQL.dll
file from an older InstantRails installer. It is available from the InstantRails GitHub repo.
Next, copy that file into your Ruby/bin folder.
Now, you are good to go ;)
the third parameter should be like array('selected' =>value)
Adding further...
Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)
So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.
But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.
So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.
So they always have to use the relative addressing mode and hence fpic option.
You probably mean Notification.Builder.setLargeIcon(Bitmap)
, right? :)
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap
s.
Ideally, you should create a self-managed certificate authority. Start with generating a key pair:
ssh-keygen -f cert_signer
Then sign each server's public host key:
ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub
This generates a signed public host key:
/etc/ssh/ssh_host_rsa_key-cert.pub
In /etc/ssh/sshd_config
, point the HostCertificate
to this file:
HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub
Restart the sshd service:
service sshd restart
Then on the SSH client, add the following to ~/.ssh/known_hosts
:
@cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/
The above contains:
@cert-authority
*.example.com
cert_signer.pub
The cert_signer
public key will trust any server whose public host key is signed by the cert_signer
private key.
Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).
For more details, see this wiki page.
Follow this completed solution step by step. it's works for me in VS 2017.
Open Command prompt in administrator mode
Open File explorer and got to .NET Framework folder
Eg:C:\Windows\Microsoft.NET\Framework\v4.0.30319
v4.0.30319 this is my .NET folder. you want to select your relevant folder.
in CMD - Go to .NET folder path
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Execute below command in CMD
aspnet_regiis.exe -i
You can see this message finally - Finished installing ASP.NET (4.0.30319.0)
iisreset
You can see this message finally - Internet services successfully restarted
Open IIS in your computer (if not config Follow this)
Go to Site and right click
Add WebSite
Fill - Site name and select physical path
Then type port number (you can find port number in .csproj file and port number must equal with (IISUrl)
EG : <IISUrl>http://localhost:15724/</IISUrl> my port is 15724
Note : you cannot create port 80 number. because it used default IIS page
Open visual studio with administrator permission
Then right click and reload your project
Your Problem may be solved.
If you are building the code yourself, then this issue could be overcome by giving "-target 1.5" to the java compiler (or by setting the corresponding option in your IDE or your build config).
For Angular 6, put favicon.png
of size 32x32
in the asset folder and change the path in index.html
. Then,
<link rel="icon" type="image/x-icon" href="./assets/favicon.png">
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
Note that if the object you are talking about has a custom property model (such as DataRowView
etc for DataTable
), then you need to use TypeDescriptor
; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverter
for formatting:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
Clone target repository same way like you cloning any other project:
git clone [email protected]:myuser/foo.git
Then install it in develop mode:
cd foo
pip install -e .
You can change anything you wan't and every code using foo
package will use modified code.
There 2 benefits ot this solution:
.git
dir, so it's regular Git repository. You can push to your fork right away.Yes it can be eliminated with the /Yc options like others have pointed out but most likely you wouldn't need to touch it to fix it. Why are you getting this error in the first place without changing any settings? You might have 'cleaned' the project and than try to compile a single cpp file. You would get this error in that case because the precompiler header is now missing. Just build the whole project (even if unsuccessful) and than build any single cpp file and you won't get this error.
It means that $objPage
is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes
for the first parameter.
In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):
this.handleInputChange = (e) => {
item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
}
I've opted for a quick Polyfill based on the above answers:
//# Polyfill
window.addEventListener = window.addEventListener || function (e, f) { window.attachEvent('on' + e, f); };
//# Standard usage
window.addEventListener("message", function(){ /*...*/ }, false);
Of course, like the answers above this doesn't ensure that window.attachEvent
exists, which may or may not be an issue.
In Unix shells, you can quote almost every character in single quotes '
. Except the single quote itself, and you can't express control characters, because \
is not expanded. Accessing the single quote itself from within a quoted string is possible, because you can concatenate strings with single and double quotes, like 'I'"'"'m'
which can be used to access a file called "I'm"
(double quote also possible here).
So you should avoid all control characters, because they are too difficult to enter in the shell. The rest still is funny, especially files starting with a dash, because most commands read those as options unless you have two dashes --
before, or you specify them with ./
, which also hides the starting -
.
If you want to be nice, don't use any of the characters the shell and typical commands use as syntactical elements, sometimes position dependent, so e.g. you can still use -
, but not as first character; same with .
, you can use it as first character only when you mean it ("hidden file"). When you are mean, your file names are VT100 escape sequences ;-), so that an ls garbles the output.
While in insert mode, you can use Ctrl-R {register}
, where register can be:
+
for the clipboard,*
for the X clipboard (last selected text in X), "
for the unnamed register (last delete or yank in Vim),:h registers
).Ctrl-R {register}
inserts the text as if it were typed.
Ctrl-R Ctrl-O {register}
inserts the text with the original indentation.
Ctrl-R Ctrl-P {register}
inserts the text and auto-indents it.
Ctrl-O
can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p
can also be used, for example.
For more information, view the documentation with :h i_ctrl-r
You can use
a.Except(b).Union(b.Except(a));
Or you can use
var difference = new HashSet(a);
difference.SymmetricExceptWith(b);
While the syntax is certainly different between Razor (.cshtml
/.vbhtml
) and WebForms (.aspx
/.ascx
), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.
You have configured the auth.php
and used members
table for authentication but there is no user_email
field in the members
table so, Laravel says
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))
Because, it tries to match the user_email
in the members
table and it's not there. According to your auth
configuration, laravel
is using members
table for authentication not users
table.
I haven't attempted this myself, so its just an idea... but have you tried using media queries with CSS to see when the height of the window changes and then change the design for that? I would imagine that Safari mobile isn't recognizing the keyboard as part of the window so that would hopefully work.
Example:
@media all and (height: 200px){
#content {height: 100px; overflow: hidden;}
}
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
GNU parallel
and xargs
These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:
seq 10 | xargs -P4 -I'{}' echo '{}'
or:
seq 10 | parallel -j4 echo '{}'
See also: how to write a process-pool bash shell
You're confusing PATH and PYTHONPATH. You need to do this:
export PATH=$PATH:/home/randy/lib/python
PYTHONPATH is used by the python interpreter to determine which modules to load.
PATH is used by the shell to determine which executables to run.
A table can easily be placed with the following parameters:
h
Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot)t
Position at the top of the page.b
Position at the bottom of the page.p
Put on a special page for floats only.!
Override internal parameters LaTeX uses for determining "good" float positions.H
Places the float at precisely the location in the LATEX code. Requires the float package. This is somewhat equivalent to h!
.If you want to make use of H
(or h!
) for an exact positioning, make sure you got the float
package correctly set up in the preamble:
\usepackage{float}
\restylefloat{table}
If you want to place the table at the same page, either at the exact place or at least at the top of the page (what fits best for the latex engine), use the parameters h
and t
like this:
\begin{table}[ht]
table content ...
\end{table}
Sources: Overleaf.com
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
If the value contains non-numeric characters, you can convert the value to an integer as follows:
SELECT CASE WHEN <column>~E'^\\d+$' THEN CAST (<column> AS INTEGER) ELSE 0 END FROM table;
The CASE operator checks the < column>, if it matches the integer pattern, it converts the rate into an integer, otherwise it returns 0
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
You can use:
const sha1 = require('sha1');
const crypt = sha1('Text');
console.log(crypt);
For install:
sudo npm install -g sha1
npm install sha1 --save
This is a topic I'm very interested in. There are many purists who say that you shouldn't test technologies such as EF and NHibernate. They are right, they're already very stringently tested and as a previous answer stated it's often pointless to spend vast amounts of time testing what you don't own.
However, you do own the database underneath! This is where this approach in my opinion breaks down, you don't need to test that EF/NH are doing their jobs correctly. You need to test that your mappings/implementations are working with your database. In my opinion this is one of the most important parts of a system you can test.
Strictly speaking however we're moving out of the domain of unit testing and into integration testing but the principles remain the same.
The first thing you need to do is to be able to mock your DAL so your BLL can be tested independently of EF and SQL. These are your unit tests. Next you need to design your Integration Tests to prove your DAL, in my opinion these are every bit as important.
There are a couple of things to consider:
There are two main approaches to setting up your database, the first is to run a UnitTest create DB script. This ensures that your unit test database will always be in the same state at the beginning of each test (you may either reset this or run each test in a transaction to ensure this).
Your other option is what I do, run specific setups for each individual test. I believe this is the best approach for two main reasons:
Unfortunately your compromise here is speed. It takes time to run all these tests, to run all these setup/tear down scripts.
One final point, it can be very hard work to write such a large amount of SQL to test your ORM. This is where I take a very nasty approach (the purists here will disagree with me). I use my ORM to create my test! Rather than having a separate script for every DAL test in my system I have a test setup phase which creates the objects, attaches them to the context and saves them. I then run my test.
This is far from the ideal solution however in practice I find it's a LOT easier to manage (especially when you have several thousand tests), otherwise you're creating massive numbers of scripts. Practicality over purity.
I will no doubt look back at this answer in a few years (months/days) and disagree with myself as my approaches have changed - however this is my current approach.
To try and sum up everything I've said above this is my typical DB integration test:
[Test]
public void LoadUser()
{
this.RunTest(session => // the NH/EF session to attach the objects to
{
var user = new UserAccount("Mr", "Joe", "Bloggs");
session.Save(user);
return user.UserID;
}, id => // the ID of the entity we need to load
{
var user = LoadMyUser(id); // load the entity
Assert.AreEqual("Mr", user.Title); // test your properties
Assert.AreEqual("Joe", user.Firstname);
Assert.AreEqual("Bloggs", user.Lastname);
}
}
The key thing to notice here is that the sessions of the two loops are completely independent. In your implementation of RunTest you must ensure that the context is committed and destroyed and your data can only come from your database for the second part.
Edit 13/10/2014
I did say that I'd probably revise this model over the upcoming months. While I largely stand by the approach I advocated above I've updated my testing mechanism slightly. I now tend to create the entities in in the TestSetup and TestTearDown.
[SetUp]
public void Setup()
{
this.SetupTest(session => // the NH/EF session to attach the objects to
{
var user = new UserAccount("Mr", "Joe", "Bloggs");
session.Save(user);
this.UserID = user.UserID;
});
}
[TearDown]
public void TearDown()
{
this.TearDownDatabase();
}
Then test each property individually
[Test]
public void TestTitle()
{
var user = LoadMyUser(this.UserID); // load the entity
Assert.AreEqual("Mr", user.Title);
}
[Test]
public void TestFirstname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Joe", user.Firstname);
}
[Test]
public void TestLastname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Bloggs", user.Lastname);
}
There are several reasons for this approach:
I feel this makes the test class simpler and the tests more granular (single asserts are good)
Edit 5/3/2015
Another revision on this approach. While class level setups are very helpful for tests such as loading properties they are less useful where the different setups are required. In this case setting up a new class for each case is overkill.
To help with this I now tend to have two base classes SetupPerTest
and SingleSetup
. These two classes expose the framework as required.
In the SingleSetup
we have a very similar mechanism as described in my first edit. An example would be
public TestProperties : SingleSetup
{
public int UserID {get;set;}
public override DoSetup(ISession session)
{
var user = new User("Joe", "Bloggs");
session.Save(user);
this.UserID = user.UserID;
}
[Test]
public void TestLastname()
{
var user = LoadMyUser(this.UserID); // load the entity
Assert.AreEqual("Bloggs", user.Lastname);
}
[Test]
public void TestFirstname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Joe", user.Firstname);
}
}
However references which ensure that only the correct entites are loaded may use a SetupPerTest approach
public TestProperties : SetupPerTest
{
[Test]
public void EnsureCorrectReferenceIsLoaded()
{
int friendID = 0;
this.RunTest(session =>
{
var user = CreateUserWithFriend();
session.Save(user);
friendID = user.Friends.Single().FriendID;
} () =>
{
var user = GetUser();
Assert.AreEqual(friendID, user.Friends.Single().FriendID);
});
}
[Test]
public void EnsureOnlyCorrectFriendsAreLoaded()
{
int userID = 0;
this.RunTest(session =>
{
var user = CreateUserWithFriends(2);
var user2 = CreateUserWithFriends(5);
session.Save(user);
session.Save(user2);
userID = user.UserID;
} () =>
{
var user = GetUser(userID);
Assert.AreEqual(2, user.Friends.Count());
});
}
}
In summary both approaches work depending on what you are trying to test.
Plain JavaScript
If a DOM element which is removed is reference-free (no references pointing to it) then yes - the element itself is picked up by the garbage collector as well as any event handlers/listeners associated with it.
var a = document.createElement('div');
var b = document.createElement('p');
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b);
b = null;
// A reference to 'b' no longer exists
// Therefore the element and any event listeners attached to it are removed.
However; if there are references that still point to said element, the element and its event listeners are retained in memory.
var a = document.createElement('div');
var b = document.createElement('p');
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b);
// A reference to 'b' still exists
// Therefore the element and any associated event listeners are still retained.
jQuery
It would be fair to assume that the relevant methods in jQuery (such as remove()
) would function in the exact same way (considering remove()
was written using removeChild()
for example).
However, this isn't true; the jQuery library actually has an internal method (which is undocumented and in theory could be changed at any time) called cleanData()
(here is what this method looks like) which automatically cleans up all the data/events associated with an element upon removal from the DOM (be this via. remove()
, empty()
, html("")
etc).
Older browsers - specifically older versions of IE - are known to have memory leak issues due to event listeners keeping hold of references to the elements they were attached to.
If you want a more in-depth explanation of the causes, patterns and solutions used to fix legacy IE version memory leaks, I fully recommend you read this MSDN article on Understanding and Solving Internet Explorer Leak Patterns.
A few more articles relevant to this:
Manually removing the listeners yourself would probably be a good habit to get into in this case (only if the memory is that vital to your application and you are actually targeting such browsers).
If you want to convert a string like "Mohammad"
to String[]
that contains all characters as String
, this may help you:
"Mohammad".ToCharArray().Select(c => c.ToString()).ToArray()
Directly with PHP is not possible but...
I write this simple code to save screen resolution on a PHP session to use on a image gallery.
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
You don't show us the declaration of carBootSaleList
. However from the exception message I can see that it is of type CarBootSaleList
. This type doesn't implement the IEnumerable
interface and therefore cannot be used in a foreach.
Your CarBootSaleList
class should implement IEnumerable<CarBootSale>
:
public class CarBootSaleList : IEnumerable<CarBootSale>
{
private List<CarBootSale> carbootsales;
...
public IEnumerator<CarBootSale> GetEnumerator()
{
return carbootsales.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return carbootsales.GetEnumerator();
}
}
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.
I am assuming that you know how to iterate over elements in some list:
for el in my_list:
# do something
Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:
i = 0
for el in my_list:
# do somethings, and use value of "i" somehow
i += 1
However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list: So if you have
arr = ['a', 'b', 'c']
Then the command
enumerate(arr)
returns something like:
[(0,'a'), (1,'b'), (2,'c')]
Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for
loop like below:
for index, value in enumerate(arr):
print(index,value)
which would print out the sub-elements of the output of enumerate.
And in general you can basically "unpack" multiple items from list into multiple variables like below:
idx,value = (2,'c')
print(idx)
print(value)
which would print
2
c
This is the kind of assignment happening in each iteration of that loop with enumerate(arr)
as iterable.
As a fallback there's always od -xc filename
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
In the newer apache poi versions:
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both;
OR what does clear: both;
exactly do...
I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both;
is required or what it does...
Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.
Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...
Live Example of the demo image.
Code For Demo
/* CSS: */_x000D_
_x000D_
* { /* Not related to floats / clear both, used it for demo purpose only */_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
header, footer {_x000D_
border: 5px solid #000;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
aside {_x000D_
float: left;_x000D_
width: 30%;_x000D_
border: 5px solid #000;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
section {_x000D_
float: left;_x000D_
width: 70%;_x000D_
border: 5px solid #000;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.clear {_x000D_
clear: both;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<header>_x000D_
Header_x000D_
</header>_x000D_
<aside>_x000D_
Aside (Floated Left)_x000D_
</aside>_x000D_
<section>_x000D_
Content (Floated Left, Can Be Floated To Right As Well)_x000D_
</section>_x000D_
<!-- Clearing Floating Elements-->_x000D_
<div class="clear"></div>_x000D_
<footer>_x000D_
Footer_x000D_
</footer>
_x000D_
Note: You might have to add header
, footer
, aside
, section
(and other HTML5 elements) as display: block;
in your stylesheet for explicitly mentioning that the elements are block level elements.
I have a basic layout, 1 header, 1 side bar, 1 content area and 1 footer.
No floats for header
, next comes the aside
tag which I'll be using for my website sidebar, so I'll be floating the element to left.
Note: By default, block level element takes up document 100% width, but when floated left or right, it will resize according to the content it holds.
So as you note, the left floated div
leaves the space to its right unused, which will allow the div
after it to shift in the remaining space.
div
's will render one after the other if they are NOT floateddiv
will shift beside each other if floated left or rightOk, so this is how block level elements behave when floated left or right, so now why is clear: both;
required and why?
So if you note in the layout demo - in case you forgot, here it is..
I am using a class called .clear
and it holds a property called clear
with a value of both
. So lets see why it needs both
.
I've floated aside
and section
elements to the left, so assume a scenario, where we have a pool, where header
is solid land, aside
and section
are floating in the pool and footer is solid land again, something like this..
So the blue water has no idea what the area of the floated elements are, they can be bigger than the pool or smaller, so here comes a common issue which troubles 90% of CSS beginners: why the background of a container element is not stretched when it holds floated elements. It's because the container element is a POOL here and the POOL has no idea how many objects are floating, or what the length or breadth of the floated elements are, so it simply won't stretch.
(Refer [Clearfix] section of this answer for neat way to do this. I am using an empty div
example intentionally for explanation purpose)
I've provided 3 examples above, 1st is the normal document flow where red
background will just render as expected since the container doesn't hold any floated objects.
In the second example, when the object is floated to left, the container element (POOL) won't know the dimensions of the floated elements and hence it won't stretch to the floated elements height.
After using clear: both;
, the container element will be stretched to its floated element dimensions.
Another reason the clear: both;
is used is to prevent the element to shift up in the remaining space.
Say you want 2 elements side by side and another element below them... So you will float 2 elements to left and you want the other below them.
div
Floated left resulting in section
moving into remaining spacediv
cleared so that the section
tag will render below the floated div
s Last but not the least, the footer
tag will be rendered after floated elements as I've used the clear
class before declaring my footer
tags, which ensures that all the floated elements (left/right) are cleared up to that point.
Coming to clearfix which is related to floats. As already specified by @Elky, the way we are clearing these floats is not a clean way to do it as we are using an empty div
element which is not a div
element is meant for. Hence here comes the clearfix.
Think of it as a virtual element which will create an empty element for you before your parent element ends. This will self clear your wrapper element holding floated elements. This element won't exist in your DOM literally but will do the job.
To self clear any wrapper element having floated elements, we can use
.wrapper_having_floated_elements:after { /* Imaginary class name */
content: "";
clear: both;
display: table;
}
Note the :after
pseudo element used by me for that class
. That will create a virtual element for the wrapper element just before it closes itself. If we look in the dom you can see how it shows up in the Document tree.
So if you see, it is rendered after the floated child div
where we clear the floats which is nothing but equivalent to have an empty div
element with clear: both;
property which we are using for this too. Now why display: table;
and content
is out of this answers scope but you can learn more about pseudo element here.
Note that this will also work in IE8 as IE8 supports :after
pseudo.
Most of the developers float their content left or right on their pages, probably divs holding logo, sidebar, content etc., these divs are floated left or right, leaving the rest of the space unused and hence if you place other containers, it will float too in the remaining space, so in order to prevent that clear: both;
is used, it clears all the elements floated left or right.
------------------ ----------------------------------
div1(Floated Left) Other div takes up the space here
------------------ ----------------------------------
Now what if you want to make the other div render below div1
, so you'll use clear: both;
so it will ensure you clear all floats, left or right
------------------
div1(Floated Left)
------------------
<div style="clear: both;"><!--This <div> acts as a separator--></div>
----------------------------------
Other div renders here now
----------------------------------
The context that * is in, confuses the meaning sometimes.
// when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.
//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.)
//when calling a function
int main(){
function(&var); // we are giving the function a 'reference', we are giving it an 'address'
}
So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.
In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)
int* p;
int *a; // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).
int c = 10; //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)
p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c
a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"
*a = 10;
a = 0xab33d111;
Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.
//Why it's used
int function(b){
b = b + 1; // we just want to add one to any variable that this function operates on.
}
int main(){
int c = 1; // I want this variable to be 3.
function(c);
function(c);// I call the function I made above twice, because I want c to be 3.
// this will return c as 1. Even though I called it twice.
// when you call a function it makes a copy of the variable.
// so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
//let's redo this whole thing, and use pointers
int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}
int main(){
int c = 1; //again, I want this to be three at the end of the program
int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.
function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...
//now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.
}
Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.
You are missing a space between Basic
and the encoded username and password.
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
The SET
clause should come after the table specification.
UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
After
apply plugin: 'com.android.application'
You should add this:
repositories {
mavenCentral()
maven {
url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
}
}
@Benjamin explained the reason.
If you have a maven with authentication you can use:
repositories {
mavenCentral()
maven {
credentials {
username xxx
password xxx
}
url 'http://mymaven/xxxx/repositories/releases/'
}
}
It is important the order.
Find out how to fix this here:
https://github.com/blog/1614-two-factor-authentication#how-does-it-work-for-command-line-git
How does it work for command-line Git?
If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
</script>
That assigns an onclick
event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id
attribute plus the .html
extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.
<div>
<div style="padding-bottom: 33%;">
i have 33% height of my parents width
</div>
</div>
One solution is to make your own params string.
This is the actual method I've been using for my latest project. You need to change args from hashtable to namevaluepair's:
private static String getPostParamString(Hashtable<String, String> params) {
if(params.size() == 0)
return "";
StringBuffer buf = new StringBuffer();
Enumeration<String> keys = params.keys();
while(keys.hasMoreElements()) {
buf.append(buf.length() == 0 ? "" : "&");
String key = keys.nextElement();
buf.append(key).append("=").append(params.get(key));
}
return buf.toString();
}
POSTing the params:
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions
This is an ancient question, but why is everyone overlooking the simplest regexp-based solution? Normal regexp quantifiers are greedy, people! If you want to find the last instance of a pattern, just stick .*
in front of it. Here's how:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
This will replace the last instance of "fox" to "DUCK", like it's supposed to, and print:
The quick brown fox, fox, fox, DUCK, jumps over etc.
From the angular docs
Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
The reason for this is that when you first visit the page (/about
), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about
Angular can get in there before the browser tries to hit the server and handle it accordingly
The following works if you have something like this in your app.js:
http.createServer(app).listen(app.get('port'),
function(){
console.log("Express server listening on port " + app.get('port'));
});
Either explicitly hardcode your code to use the port you want, like:
app.set('port', process.env.PORT || 3000);
This code means set your port to the environment variable PORT
or if that is undefined
then set it to the literal 3000
.
Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION
and DEVELOPMENT
and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.
$ PORT=8080 node app.js
In reference to your code example, you want something like this:
var express = require("express");
var app = express();
// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
function(data){
$scope.subjects = [];
$.each(data, function(i,subject){
//Store array of data types
$scope.subjects.push(subject.name);
//Split data in to arrays
$scope[subject.name] = subject.data;
});
}
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff
if you set your context model as code first based on exist database so you have to for set migration:
Add-Migration InitialCreate –IgnoreChanges
Update-database -force
and then change your context model and set:
Add-migration RemoveIspositive
Update-database -force
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
?
Right Click on Project -> Build Path -> Configure Build Path. Check if Maven Dependencies is there in list, if not then update maven project by Right Click on Project -> Maven -> Update Project
I have 1 WorkBook("SOURCE") that contains around 20 Sheets. I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA. Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.
Another Way
Sub Sample()
'~~> Change Sheet1 to the relevant sheet
'~~> This will create a new workbook with the relevant sheet
ThisWorkbook.Sheets("Sheet1").Copy
'~~> Save the new workbook
ActiveWorkbook.SaveAs "C:\Target.xlsx", FileFormat:=51
End Sub
This will automatically create a new workbook called Target.xlsx with the relevant sheet
File modification:
ls -t
Inode change:
ls -tc
File access:
ls -tu
"Newest" one at the bottom:
ls -tr
None of this is a creation time. Most Unix filesystems don't support creation timestamps.
After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']);
. Or you can just return the array return array('success' => 'hi, atiq');
which will be rendered as json in Laravel version 5.2 .
Add
div.ui-datepicker, .ui-datepicker td{
font-size:10px;
}
in a stylesheet loaded after the ui-files. This will also resize the date items.
I know this isn't directly what OP was originally asking for but this helped me a lot in this situation when I had a similar question.. Adding this for people looking to change the layout window size (which i use regularly), via code. Add this to your onCreate in the activity of question. (Changes it to 80%)
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width * 0.8), (int)(height * 0.8));
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
install cocoapods from https://cocoapods.org/app
Commands & versions keep onchanging
so download tar and enjoy
Try this
RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29);
relative.setBackgroundResource(0);
Check the setBackground functions in the RelativeLayout documentation
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
Try giving the full path to apache2ctl.
List last updated on December 1, 2020:
As of November 30, 2020, AWS now has EC2 Mac instances:
We previously used and had good experiences with:
Here are some other sites that I am aware of:
When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).
In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.
If you really need to do it in separate transaction you need to use REQUIRES_NEW
and live with the performance overhead. Watch out for dead locks.
I'd rather do it the other way:
Aangular 2 final has updated APIs. They have added many methods for this.
To update the form control from controller do this:
this.form.controls['dept'].setValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
No need to reset the errors
References
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
https://toddmotto.com/angular-2-form-controls-patch-value-set-value
Works great, minimal setup and no third parties.
According to Chrome's documentation:
Here's the updated workflow:What happens when you blackbox a script?
Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.
jquery\..*\.js
(glob pattern/human translation: jquery.*.js
)|
, like so: jquery\..*\.js|include\.postload\.js
(which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/
You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:
It's an excellent tool to have:
Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:
- Which elements have events attached to them
- The type of events attached to an element
- The code that will be run with the event is triggered
- The source file and line number for where the attached function was defined (Webkit browsers and Opera only)
You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.
In this instance, I want to know what exactly goes on when I click the button.
Open Dev Tools -> Sources tab, and on the right find Event
Listener Breakpoints
:
Expand Mouse
and select click
With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:
and searching #envio
or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.
Be aware sometimes there's not only an img
but lots of elements stacked, and you may not know which one triggers the code.
If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.
To send javascript obj to php using json and ajax:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
You can use my plugin for this purpose.
JQuery:
(function() {_x000D_
$.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
for (var element of parameters.elements.get()) {_x000D_
if (!element.pseudoElements) element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (element.pseudoElements.id !== null) {_x000D_
if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);_x000D_
return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = $.pseudoElements.length;_x000D_
$.pseudoElements.length++_x000D_
_x000D_
element.pseudoElements.id = id;_x000D_
element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {_x000D_
element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = $.extend({}, parameters.argument);_x000D_
_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
};_x000D_
_x000D_
return $(parameters.elements);_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var element = $(parameters.elements).get(0);_x000D_
_x000D_
var windowStyle = window.getComputedStyle(_x000D_
element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (element.pseudoElements) {_x000D_
return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
$.fn.cssBefore = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
$.fn.cssAfter = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
})();_x000D_
_x000D_
$(function() {_x000D_
$('.element').cssBefore('content', '"New before!"');_x000D_
});
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="element"></div>
_x000D_
The values should be specified, as in the normal function of jQuery.css
In addition, you can also get the value of the pseudo-element parameter, as in the normal function of jQuery.css:
console.log( $(element).cssBefore(parameter) );
JS:
(function() {_x000D_
document.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (parameters.element.pseudoElements.id !== null) {_x000D_
if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);_x000D_
return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = document.pseudoElements.length;_x000D_
document.pseudoElements.length++_x000D_
_x000D_
parameters.element.pseudoElements.id = id;_x000D_
parameters.element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
parameters.element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
parameters.element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = (function() {_x000D_
var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
cloneObject[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
return cloneObject;_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var windowStyle = window.getComputedStyle(_x000D_
parameters.element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (parameters.element.pseudoElements) {_x000D_
return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
Object.defineProperty(Element.prototype, 'styleBefore', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
Object.defineProperty(Element.prototype, 'styleAfter', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
})();_x000D_
_x000D_
document.querySelector('.element').styleBefore('content', '"New before!"');
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<div class="element"></div>
_x000D_
GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/
its too simple, you can just type "cache:" before the URL of the page. for example
if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page
this will show you the last webcache of the page.see here:
But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.
this will do the job easily to get the last part of the required URL
$url="http://domain.com/artist/song/music-videos/song-title/9393903";
$requred_string= substr(strrchr($url, "/"), 1);
this will get you the string after first "/" from the right.
Here is a new authentication library that uses timestamped tokens. The tokens can be emailed or texted to users without the need to store them in a database. It can be used for passwordless authentication or for two-factor authentication.
https://github.com/vote539/easy-no-password
Disclosure: I am the developer of this library.
You have to define both the schema and the table in two different places.
the context defines the schema
public class BContext : DbContext
{
public BContext(DbContextOptions<BContext> options) : base(options)
{
}
public DbSet<PriorityOverride> PriorityOverrides { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("My.Schema");
builder.ApplyConfiguration(new OverrideConfiguration());
}
}
and for each table
class PriorityOverrideConfiguration : IEntityTypeConfiguration<PriorityOverride>
{
public void Configure(EntityTypeBuilder<PriorityOverride> builder)
{
builder.ToTable("PriorityOverrides");
...
}
}
Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.
Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
If you already have the string, you can use this function:
bool isNumber( const string& s )
{
bool hitDecimal=0;
for( char c : s )
{
if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
hitDecimal=1; // first hit here, we forgive and skip
else if( !isdigit( c ) )
return 0 ; // not ., not
}
return 1 ;
}
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
System.out.println("enter the number");//how many number you want to enter
Scanner input = new Scanner(System.in);
int n = input.nextInt();
num = input.nextInt();
smallest = num; //assume first entered number as small one
// i starts from 2 because we already took one num value
for (int i = 2; i < n; i++) {
num = input.nextInt();
//comparing each time entered number with large one
if (num > large) {
large = num;
}
//comparing each time entered number with smallest one
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
With fetch api it turned out that you do NOT have to include headers "Content-type": "multipart/form-data".
So the following works:
let formData = new FormData()
formData.append("nameField", fileToSend)
fetch(yourUrlToPost, {
method: "POST",
body: formData
})
Note that with axios I had to use the content-type.
I've been recently working on it. Check out this jsFiddle test, try it yourself changing the width of the base table to check the behavior).
The solution is to embedded a table into another:
<table style="width: 200px;border:0;border-collapse:collapse">
<tbody>
<tr>
<td style="width: 100%;">
<table style="width: 100%;border:0;border-collapse:collapse">
<tbody>
<tr>
<td>
<div style="position: relative;overflow:hidden">
<p> </p>
<p style="overflow:hidden;text-overflow: ellipsis;position: absolute; top: 0pt; left: 0pt;width:100%">This cells has more content</p>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td style="white-space:nowrap">Less content here</td>
</tr>
</tbody>
</table>
Is Fred now happy with Celldito's expansion?
In .NET you can use grouping to your advantage like this:
http://regexhero.net/tester/?id=65b32601-2326-4ece-912b-6dcefd883f31
You'll notice that:
(ABC)|(.)
Will grab everything except ABC in the 2nd group. Parenthesis surround each group. So (ABC) is group 1 and (.) is group 2.
So you just grab the 2nd group like this in a replace:
$2
Or in .NET look at the Groups collection inside the Regex class for a little more control.
You should be able to do something similar in most other regex implementations as well.
UPDATE: I found a much faster way to do this here: http://regexhero.net/tester/?id=997ce4a2-878c-41f2-9d28-34e0c5080e03
It still uses grouping (I can't find a way that doesn't use grouping). But this method is over 10X faster than the first.
Or, as inspired by @MatheusAraujo:
df[nrow(df) + 1,] = list("v1","v2")
This would allow for mixed data types.
I would do it using a for loop as shown below :
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
we have to install the M2E Eclipse WTP plugin To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
And restart eclipse
For the centering, I don't get what's with the overly complicated solutions. bootstrap already centers it horizontally for you, so you don't need to mess with this. My solution is just set a top margin only using jQuery.
$('#myModal').on('loaded.bs.modal', function() {
$(this).find('.modal-dialog').css({
'margin-top': function () {
return (($(window).outerHeight() / 2) - ($(this).outerHeight() / 2));
}
});
});
I've used the loaded.bs.modal event as I am remotely loading content, and using the shown.ba.modal event causes the height calculation to be incorrect. You can of course add in an event for the window being resized if you need it to be that responsive.
Set the second function parameter to true if you require an associative array
Some versions of php require a 2nd paramter of true if you require an associative array
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
Have a look at CSS compose: https://bambielli.com/til/2017-08-11-css-modules-composes/
according to them:
.serif-font {
font-family: Georgia, serif;
}
.display {
composes: serif-font;
font-size: 30px;
line-height: 35px;
}
I use it in my react project.
I extended @Hao's answer using the same counting principal but supporting richer data return, so you get back size, recursive size, directory count, and recursive directory count, N levels deep.
public class DiskSizeUtil
{
/// <summary>
/// Calculate disk space usage under <paramref name="root"/>. If <paramref name="levels"/> is provided,
/// then return subdirectory disk usages as well, up to <paramref name="levels"/> levels deep.
/// If levels is not provided or is 0, return a list with a single element representing the
/// directory specified by <paramref name="root"/>.
/// </summary>
/// <returns></returns>
public static FolderSizeInfo GetDirectorySize(DirectoryInfo root, int levels = 0)
{
var currentDirectory = new FolderSizeInfo();
// Add file sizes.
FileInfo[] fis = root.GetFiles();
currentDirectory.Size = 0;
foreach (FileInfo fi in fis)
{
currentDirectory.Size += fi.Length;
}
// Add subdirectory sizes.
DirectoryInfo[] dis = root.GetDirectories();
currentDirectory.Path = root;
currentDirectory.SizeWithChildren = currentDirectory.Size;
currentDirectory.DirectoryCount = dis.Length;
currentDirectory.DirectoryCountWithChildren = dis.Length;
currentDirectory.FileCount = fis.Length;
currentDirectory.FileCountWithChildren = fis.Length;
if (levels >= 0)
currentDirectory.Children = new List<FolderSizeInfo>();
foreach (DirectoryInfo di in dis)
{
var dd = GetDirectorySize(di, levels - 1);
if (levels >= 0)
currentDirectory.Children.Add(dd);
currentDirectory.SizeWithChildren += dd.SizeWithChildren;
currentDirectory.DirectoryCountWithChildren += dd.DirectoryCountWithChildren;
currentDirectory.FileCountWithChildren += dd.FileCountWithChildren;
}
return currentDirectory;
}
public class FolderSizeInfo
{
public DirectoryInfo Path { get; set; }
public long SizeWithChildren { get; set; }
public long Size { get; set; }
public int DirectoryCount { get; set; }
public int DirectoryCountWithChildren { get; set; }
public int FileCount { get; set; }
public int FileCountWithChildren { get; set; }
public List<FolderSizeInfo> Children { get; set; }
}
}
One other thing that affected me: If you have multiple test devices, make sure you are making changes to the layout used by the device. In my case, I spent a while making changes to xmls in the "layout" directory until I discovered that my larger phone (which I switched to halfway through testing) was using xmls in the "layout-sw360dp" directory. Grrr!
uppose a list of number and you want to remove all no which are divisible by 3,
list_number =[i for i in range(100)]
using list comprehension
,this will careate a new list and create new memory space
new_list =[i for i in list_number if i%3!=0]
using lambda filter
function, this will create resultant new list and consume memeory space
new_list = list(filter(lambda x:x%3!=0, list_number))
without consuming memory space for new list and modify existing list
for index, value in enumerate(list_number):
if list_number[index]%3==0:
list_number.remove(value)
Suppose your data looks like this:
import pandas as pd
import numpy as np
np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
data = dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5)))
data = pd.DataFrame(data.items())
data = data.transpose()
data.columns = data.iloc[0]
data = data.drop(data.index[[0]])
df = df.append(data)
print('{}\n'.format(df))
# 0 0 1 2 3 4 5 6 7 8 9
# 1 6 NaN NaN 8 5 NaN NaN 7 0 NaN
# 1 NaN 9 6 NaN 2 NaN 1 NaN NaN 2
# 1 NaN 2 2 1 2 NaN 1 NaN NaN NaN
# 1 6 NaN 6 NaN 4 4 0 NaN NaN NaN
# 1 NaN 9 NaN 9 NaN 7 1 9 NaN NaN
Then it could be replaced with
np.random.seed(2015)
data = []
for i in range(5):
data.append(dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)
In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data)
once at the end, outside the loop.
Each call to df.append
requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append
in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
Try the below query
CREATE TABLE card_types (
card_type_id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL default '',
PRIMARY KEY (card_type_id),
) ENGINE = MyISAM ;
The property()
function returns a special descriptor object:
>>> property()
<property object at 0x10ff07940>
It is this object that has extra methods:
>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>
These act as decorators too. They return a new property object:
>>> property().getter(None)
<property object at 0x10ff079f0>
that is a copy of the old object, but with one of the functions replaced.
Remember, that the @decorator
syntax is just syntactic sugar; the syntax:
@property
def foo(self): return self._foo
really means the same thing as
def foo(self): return self._foo
foo = property(foo)
so foo
the function is replaced by property(foo)
, which we saw above is a special object. Then when you use @foo.setter()
, what you are doing is call that property().setter
method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.
The following sequence also creates a full-on property, by using those decorator methods.
First we create some functions and a property
object with just a getter:
>>> def getter(self): print('Get!')
...
>>> def setter(self, value): print('Set to {!r}!'.format(value))
...
>>> def deleter(self): print('Delete!')
...
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True
Next we use the .setter()
method to add a setter:
>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True
Last we add a deleter with the .deleter()
method:
>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True
Last but not least, the property
object acts as a descriptor object, so it has .__get__()
, .__set__()
and .__delete__()
methods to hook into instance attribute getting, setting and deleting:
>>> class Foo: pass
...
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!
The Descriptor Howto includes a pure Python sample implementation of the property()
type:
class Property: "Emulate PyProperty_Type() in Objects/descrobject.c" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") return self.fget(obj) def __set__(self, obj, value): if self.fset is None: raise AttributeError("can't set attribute") self.fset(obj, value) def __delete__(self, obj): if self.fdel is None: raise AttributeError("can't delete attribute") self.fdel(obj) def getter(self, fget): return type(self)(fget, self.fset, self.fdel, self.__doc__) def setter(self, fset): return type(self)(self.fget, fset, self.fdel, self.__doc__) def deleter(self, fdel): return type(self)(self.fget, self.fset, fdel, self.__doc__)
You can combine filter with the text.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<title>SVG colored patterns via mask</title>_x000D_
</head>_x000D_
<body>_x000D_
<svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">_x000D_
<defs>_x000D_
<filter x="0" y="0" width="1" height="1" id="bg-text">_x000D_
<feFlood flood-color="white"/>_x000D_
<feComposite in="SourceGraphic" operator="xor" />_x000D_
</filter>_x000D_
</defs>_x000D_
<!-- something has already existed -->_x000D_
<rect fill="red" x="150" y="20" width="100" height="50" />_x000D_
<circle cx="50" cy="50" r="50" fill="blue"/>_x000D_
_x000D_
<!-- Text render here -->_x000D_
<text filter="url(#bg-text)" fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
<text fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
</svg>_x000D_
</body>_x000D_
</html>
_x000D_
perldoc perlvar is the first place to check for any special-named Perl variable info.
Quoting:
@_
: Within a subroutine the array@_
contains the parameters passed to that subroutine.
More details can be found in perldoc perlsub (Perl subroutines) linked from the perlvar:
Any arguments passed in show up in the array
@_
.Therefore, if you called a function with two arguments, those would be stored in
$_[0]
and$_[1]
.The array
@_
is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @_ removes that aliasing, and does not update any arguments.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "[email protected]";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}
1st: If you know that your code isn't right, you should fix it before do anything!
You could do something like this:
function validateForm() {
var radios = document.getElementsByName("yesno");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}?
See it in action: http://jsfiddle.net/FhgQS/
If you don't want to download anything, you can use sqlite3 tool which is provided with adb :
Examining sqlite3 databases from a remote shell
and :
You can use the UNPIVOT function to convert the columns into rows:
select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;
Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.
You could also use CROSS APPLY
with UNION ALL to convert the columns:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
select 'Indicator1', Indicator1 union all
select 'Indicator2', Indicator2 union all
select 'Indicator3', Indicator3 union all
select 'Indicator4', Indicator4
) c (indicatorname, indicatorvalue);
Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
values
('Indicator1', Indicator1),
('Indicator2', Indicator2),
('Indicator3', Indicator3),
('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);
Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'yourtable' and
C.column_name like 'Indicator%'
for xml path('')), 1, 1, '')
set @query
= 'select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in ('+ @colsunpivot +')
) u'
exec sp_executesql @query;
Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).
Based on cocco's idea, here's a less compact -but hopefully more comprehensive- example.
<!DOCTYPE html>
<html>
<head>
<title>File info</title>
<script>
<!--
function fileSize(bytes) {
var exp = Math.log(bytes) / Math.log(1024) | 0;
var result = (bytes / Math.pow(1024, exp)).toFixed(2);
return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}
function info(input) {
input.nextElementSibling.textContent = fileSize(input.files[0].size);
}
-->
</script>
</head>
<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html>
One difference is for r+
if the files does not exist, it'll not be created and open fails. But in case of a+
the file will be created if it does not exist.
$post = Post::select(DB::raw('count(*) as user_count, category_id'))
->groupBy('category_id')
->get();
This is an example which results count of post by category.
I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:
test:
( NODE_ENV=test mocha --harmony --reporter spec test )
In management studio:
Properties
, then Options
.Tasks
-> Shrink
-> Files
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
Updating Eli's answer to Python 3:
class Timer(object):
def __init__(self, name=None, filename=None):
self.name = name
self.filename = filename
def __enter__(self):
self.tstart = time.time()
def __exit__(self, type, value, traceback):
message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
if self.name:
message = '[%s] ' % self.name + message
print(message)
if self.filename:
with open(self.filename,'a') as file:
print(str(datetime.datetime.now())+": ",message,file=file)
Just like Eli's, it can be used as a context manager:
import time
with Timer('Count'):
for i in range(0,10_000_000):
pass
Output:
[Count] Elapsed: 0.27 seconds
I have also updated it to print the units of time reported (seconds) and trim the number of digits as suggested by Can, and with the option of also appending to a log file. You must import datetime to use the logging feature:
import time
import datetime
with Timer('Count', 'log.txt'):
for i in range(0,10_000_000):
pass
You can use Request.Url.AbsolutePath
to get the page name, and Request.Url.Authority
for the host name and port. I don't believe there is a built in property to give you exactly what you want, but you can combine them yourself.
A React Hook you can add to your Route component. Using useLayoutEffect
instead of custom listeners.
import React, { useLayoutEffect } from 'react';
import { Switch, Route, useLocation } from 'react-router-dom';
export default function Routes() {
const location = useLocation();
// Scroll to top if path changes
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, [location.pathname]);
return (
<Switch>
<Route exact path="/">
</Route>
</Switch>
);
}
Update: Updated to use useLayoutEffect
instead of useEffect
, for less visual jank. Roughly this translates to:
useEffect
: render components -> paint to screen -> scroll to top (run effect)useLayoutEffect
: render components -> scroll to top (run effect) -> paint to screenDepending on if you're loading data (think spinners) or if you have page transition animations, useEffect
may work better for you.
Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools
If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.
$("span").toggle();
Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
Try to look at Net2Java It seems to me the best option for automatic (or semi-automatic at least) conversion from C# to Java
I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.
in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.
In Wordpress hide Warnings and Notices add following code in wp-config.php file
ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Here is what I follow on My system.
All Projects: There is a projects directory in my home folder i.e. ~/projects
. All the projects rest inside it.
Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.
Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs
. This gives me flexibility that I know what all virtual environments I have and can look use easily
The above 3 are the main partitions of My working environment.
All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.
You can use Xtreme Download Manager(XDM) software for this. This software can download from any site in this format. Even this software can change the ts file format. You only need to change the format when downloading.
like:https://www.videohelp.com/software/Xtreme-Download-Manager-
If you happened to use Typescript and have dom in your the lib of tsconfig.json
, you can do:
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check
params.append('newKey', 'newValue');
You can use the curses.h
library in linux as mentioned in the other answer.
You can install it in Ubuntu by:
sudo apt-get update
sudo apt-get install ncurses-dev
I took the installation part from here.
Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?
Here is a simple standalone Winforms custom control, derived from the standard TextBox, that allows only System.Int32 input (it could be easily adapted for other types such as System.Int64, etc.). It supports copy/paste operations and negative numbers:
public class Int32TextBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
NumberFormatInfo fi = CultureInfo.CurrentCulture.NumberFormat;
string c = e.KeyChar.ToString();
if (char.IsDigit(c, 0))
return;
if ((SelectionStart == 0) && (c.Equals(fi.NegativeSign)))
return;
// copy/paste
if ((((int)e.KeyChar == 22) || ((int)e.KeyChar == 3))
&& ((ModifierKeys & Keys.Control) == Keys.Control))
return;
if (e.KeyChar == '\b')
return;
e.Handled = true;
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
const int WM_PASTE = 0x0302;
if (m.Msg == WM_PASTE)
{
string text = Clipboard.GetText();
if (string.IsNullOrEmpty(text))
return;
if ((text.IndexOf('+') >= 0) && (SelectionStart != 0))
return;
int i;
if (!int.TryParse(text, out i)) // change this for other integer types
return;
if ((i < 0) && (SelectionStart != 0))
return;
}
base.WndProc(ref m);
}
Update 2017: My first answer has some issues:
So I came up with another version that's more generic, that still supports copy/paste, + and - sign, etc.
public class ValidatingTextBox : TextBox
{
private string _validText;
private int _selectionStart;
private int _selectionEnd;
private bool _dontProcessMessages;
public event EventHandler<TextValidatingEventArgs> TextValidating;
protected virtual void OnTextValidating(object sender, TextValidatingEventArgs e) => TextValidating?.Invoke(sender, e);
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (_dontProcessMessages)
return;
const int WM_KEYDOWN = 0x100;
const int WM_ENTERIDLE = 0x121;
const int VK_DELETE = 0x2e;
bool delete = m.Msg == WM_KEYDOWN && (int)m.WParam == VK_DELETE;
if ((m.Msg == WM_KEYDOWN && !delete) || m.Msg == WM_ENTERIDLE)
{
DontProcessMessage(() =>
{
_validText = Text;
_selectionStart = SelectionStart;
_selectionEnd = SelectionLength;
});
}
const int WM_CHAR = 0x102;
const int WM_PASTE = 0x302;
if (m.Msg == WM_CHAR || m.Msg == WM_PASTE || delete)
{
string newText = null;
DontProcessMessage(() =>
{
newText = Text;
});
var e = new TextValidatingEventArgs(newText);
OnTextValidating(this, e);
if (e.Cancel)
{
DontProcessMessage(() =>
{
Text = _validText;
SelectionStart = _selectionStart;
SelectionLength = _selectionEnd;
});
}
}
}
private void DontProcessMessage(Action action)
{
_dontProcessMessages = true;
try
{
action();
}
finally
{
_dontProcessMessages = false;
}
}
}
public class TextValidatingEventArgs : CancelEventArgs
{
public TextValidatingEventArgs(string newText) => NewText = newText;
public string NewText { get; }
}
For Int32, you can either derive from it, like this:
public class Int32TextBox : ValidatingTextBox
{
protected override void OnTextValidating(object sender, TextValidatingEventArgs e)
{
e.Cancel = !int.TryParse(e.NewText, out int i);
}
}
or w/o derivation, use the new TextValidating event like this:
var vtb = new ValidatingTextBox();
...
vtb.TextValidating += (sender, e) => e.Cancel = !int.TryParse(e.NewText, out int i);
but what's nice is it works with any string, and any validation routine.
You should use a DialogFragment instead.
I use codeigniter 3+. I had the same problem and in my case I changed model file name starting from uppser case.
Logon_model.php
This error happens to me because there is an invalid input in my activity_main.xml file.
When you try to build or clean your project you will see error messages.
I resolved mine by reading those error messages, correct what is wrong in my xml file. then rebuild project.
foo4
is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.Foo foo5
is a declaration, not an expression; function (and constructor) arguments must be expressions.Foo()
rather than the equivalent Foo::Foo()
(or indeed Foo::Foo::Foo::Foo::Foo()
)When do I use each?
Bar
from a temporary Foo
.You can just specify the python version when running a program:
for python 2:
python filename.py
for python 3:
python3 filename.py
This was happening in the production environment for me.
rm /vendor/bundle
then
bundle install --deployment
resolved the issue.
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
its work short code
$('.SeeMore2').click(function(){
var $this = $(this).toggleClass('SeeMore2');
if($(this).hasClass('SeeMore2'))
{
$(this).text('See More');
} else {
$(this).text('See Less');
}
});
if pptCreator is a function/procedure in the same file, you could call it as below
call pptCreator()
You could google for PDF viewer component, and come up with more than a few hits.
If you don't really need to embed them in your app, though - you can just require Acrobat Reader or FoxIt (or bundle it, if it meets their respective licensing terms) and shell out to it. It's not as cool, but it gets the job done for free.
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
For Perfect DateTime
Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
I'd like to add a little CoffeeScript code (not field tested):
$ ->
$(window).bind 'keypress', (event) ->
if event.keyCode == 13
unless {'TEXTAREA', 'SELECT'}[event.originalEvent.srcElement.tagName]
event.preventDefault()
(I hope you like the nice trick in the unless clause.)
I've used Tail For Windows. Certainly not as elegant as using
tailbut then, you're using Windows. ;)
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
(a) wwww.somewebsite.com/a.txt
isn't a 'file URL'. It isn't a URL at all. If you put http://
on the front of it it would be an HTTP URL, which is clearly what you intend here.
(b) FileInputStream
is for files, not URLs.
(c) The way to get an input stream from any URL is via URL.openStream(),
or URL.getConnection().getInputStream(),
which is equivalent but you might have other reasons to get the URLConnection
and play with it first.
Using Jquery
You only need to add class to every input, i have add class "source" you can change it of course
<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />
<script type="text/javascript">
$(document).ready(function() {
var selected_value = []; // initialize empty array
$(".source:checked").each(function(){
selected_value.push($(this).val());
});
console.log(selected_value); //Press F12 to see all selected values
});
</script>
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
In order to run scripts, you should write the "python test.py" command in the command prompt, and not within the python shell. also, the test.py file should be at the path you run from in the cli.
For anyone else who runs into this...
Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.
Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:
<div class="input-group" data-datepicker="true">
<input name="date" type="text" class="form-control" />
<span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>
It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).
$('*[data-datepicker="true"] input[type="text"]').datepicker({
todayBtn: true,
orientation: "top left",
autoclose: true,
todayHighlight: true
});
Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).
$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
$('input[type="text"]', $(this).parent()).focus();
});
NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.
As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;
//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;
printf("conver is now %f\n",conver);
return 0;
}
I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.
Be careful if you are working on localhost ! If you store your cookie in js like this:
document.cookie = "key=value;domain=localhost"
It might not be accessible to your subdomain, like sub.localhost
. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName
localhost.com
then you will be able to store your cookie on your domain and subdomain like this:
document.cookie = "key=value;domain=localhost.com"
Use CollectionUtils.filter(Collection,Predicate), from Apache Commons.
In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.
If you want to debug IAB what do you have to do is:
Submit to google play a version of your app with the IAB permission on the manifest:
Add a product to your app on google play: Administering In-app Billing
Set a custom debug keystore signed: Configure Eclipse to use signed keystore
This answer posted by Todd helped me.
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;
The \( ! -name . \)
avoids executing the command in current directory.
Yes, you can use regular expressions
in C#.
Using regular expressions with C#
:
using System.Text.RegularExpressions;
string your_String = "Hello@Hello&Hello(Hello)";
string my_String = Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");
Programming Hub randomly provided a code snippet which in fact does reduce the length of an array
for (i = position_to_remove; i < length_of_array; ++i) {
inputarray[i] = inputarray[i + 1];
}
Not sure if it's behaviour that was added only later. It does the trick though.
You should do:
try:
value_index = my_list.index(value)
except:
value_index = -1;
All previous links no more direct to "Reviews" tab,
This link would direct to "Reviews Tab" directly: ?
https://itunes.apple.com/app/viewContentsUserReviews?id=AppID
or ?
itms-apps://itunes.apple.com/app/viewContentsUserReviews?id=AppID
Your problem is new (object creation in java style)
MileageFeeCalculator calc = new MileageFeeCalculator();
With annotation @Service
, @Component
, @Configuration
beans are created in the
application context of Spring when server is started. But when we create objects
using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.
Check this out:
public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String name = "tenant";
System.out.println("Bean factory post processor is initialized");
beanFactory.registerScope("employee", new Employee());
Assert.state(beanFactory instanceof BeanDefinitionRegistry,
"BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
if (name.equals(definition.getScope())) {
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
}
}
}
}
As of NP++ V6.2.3 (nor sure about older versions) simply:
Hope this helps to achieve goal in simple and yet fast way:)
Error connecting Redis on Apple Silicon( Macbook Pro M1 - Dec 2020), you have to just know 2 things:
shell% sudo redis-server
shell% sudo redis-server --daemonize yes
Verify using below steps:
shell% redis-cli ping
Hope this helps all Macbook Pro M1 users who are really worried about lack of documentation on this.
Reload the page isn't the best approach.
you can handle state change events for reload data without reload the view itself.
read about ionicView life-cycle here:
http://blog.ionic.io/navigating-the-changes/
and handle the event beforeEnter for data reload.
$scope.$on('$ionicView.beforeEnter', function(){
// Any thing you can think of
});
Try copying _sqlite3.so
so that Python can find it.
It should be as simple as:
cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/
Trust me, try it.
UPDATE: with the compact
command and WiredTiger it looks like the extra disk space will actually be released to the OS.
UPDATE: as of v1.9+ there is a compact
command.
This command will perform a compaction "in-line". It will still need some extra space, but not as much.
MongoDB compresses the files by:
You can do this "compression" by running mongod --repair
or by connecting directly and running db.repairDatabase()
.
In either case you need the space somewhere to copy the files. Now I don't know why you don't have enough space to perform a compress, however, you do have some options if you have another computer with more space.
mongoexport
) and then you can Import that same database (using mongoimport
). This will result in a new database that is more compressed. Now you can stop the original mongod
replace with the new database files and you're good to go.There is not currently a good way to "compact in place" using Mongo. And Mongo can definitely suck up a lot of space.
The best strategy right now for compaction is to run a Master-Slave setup. You can then compact the Slave, let it catch up and switch them over. I know still a little hairy. Maybe the Mongo team will come up with better in place compaction, but I don't think it's high on their list. Drive space is currently assumed to be cheap (and it usually is).
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
SourceTree is a git GUI which has a pretty convenient interface for staging just the bits you want. It does not have anything remotely similar for amending a proper revision.
So git reset --soft HEAD~1
is much more useful than commit --amend
in this scenario. I can undo the commit, get all the changes back into the staging area, and resume tweaking the staged bits using SourceTree.
Really, it seems to me that commit --amend
is the more redundant command of the two, but git is git and does not shy away from similar commands that do slightly different things.
Based on various answers on Stack Overflow and blogs I've come across, this is the method I'm using, and it seems to return real words quite well. The idea is to split the incoming text into an array of words (use whichever method you'd like), and then find the parts of speech (POS) for those words and use that to help stem and lemmatize the words.
You're sample above doesn't work too well, because the POS can't be determined. However, if we use a real sentence, things work much better.
import nltk
from nltk.corpus import wordnet
lmtzr = nltk.WordNetLemmatizer().lemmatize
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wordnet.ADJ
elif treebank_tag.startswith('V'):
return wordnet.VERB
elif treebank_tag.startswith('N'):
return wordnet.NOUN
elif treebank_tag.startswith('R'):
return wordnet.ADV
else:
return wordnet.NOUN
def normalize_text(text):
word_pos = nltk.pos_tag(nltk.word_tokenize(text))
lemm_words = [lmtzr(sw[0], get_wordnet_pos(sw[1])) for sw in word_pos]
return [x.lower() for x in lemm_words]
print(normalize_text('cats running ran cactus cactuses cacti community communities'))
# ['cat', 'run', 'ran', 'cactus', 'cactuses', 'cacti', 'community', 'community']
print(normalize_text('The cactus ran to the community to see the cats running around cacti between communities.'))
# ['the', 'cactus', 'run', 'to', 'the', 'community', 'to', 'see', 'the', 'cat', 'run', 'around', 'cactus', 'between', 'community', '.']
MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.
I had a sub folder named web.config renaming this folder resolved the issue
I have just used dompdf and the code was a little different but it worked.
Here it is:
require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('Brochure.pdf', $output);
Only difference here is that all of the files in the include directory are included.
Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.
As Andrie said, system.time()
works fine. For short function I prefer to put replicate()
in it:
system.time( replicate(10000, myfunction(with,arguments) ) )
Map is a part of the enumerable module. Very similar to "collect" For Example:
Class Car
attr_accessor :name, :model, :year
Def initialize (make, model, year)
@make, @model, @year = make, model, year
end
end
list = []
list << Car.new("Honda", "Accord", 2016)
list << Car.new("Toyota", "Camry", 2015)
list << Car.new("Nissan", "Altima", 2014)
p list.map {|p| p.model}
Map provides values iterating through an array that are returned by the block parameters.
I've placed this answer because Erwin Smout posted a answer that was so wrong it highlighted that there is probably a need to specifically guard against it.
Erwin suggested:
"Why should every SELECT always include DISTINCT ?"
A more appropriate question would be: If someone were to make the claim that: "every SELECT always include DISTINCT"; how would you comment on the claim?
If a candidate is unable to shoot the claim down in flames they either:
For the record
jspcal's answer as a string extension.
Program.cs
class Program
{
static void Main(string[] args)
{
var myText = "MYTEXT";
Console.WriteLine(myText.ToTitleCase()); //Mytext
}
}
StringExtensions.cs
using System;
public static class StringExtensions
{
public static string ToTitleCase(this string str)
{
if (str == null)
return null;
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
}
What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.
static void Main(string[] args)
{
try
{
// Start Working
}
catch (Exception ex)
{
// Output/Log Exception
}
finally
{
// Clean Up If Needed
}
}
And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.
Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
If you have Microsoft Office Professional Plus 2013, you can use Microsoft Spreadsheet Compare to run a report on the differences between two workbooks.
Launch Spreadsheet Compare:
In Windows 7: On the Windows Start menu, under Office 2013 Tools, click Spreadsheet Compare.
In Windows 8: On the Start screen, click Spreadsheet Compare. If you do not see a Spreadsheet Compare tile, begin typing the words Spreadsheet Compare, and then select its tile.
Compare two Excel workbooks:
Reference:
If rm cannot remove a symlink, perhaps you need to look at the permissions on the directory that contains the symlink. To remove directory entries, you need write permission on the containing directory.
Simple, just wrap it up in a table div...
The HTML:
<div class="fake-table">
<div class="left-side">
some text
</div>
<div class="right-side">
My Navigation or something
</div>
</div>
The CSS:
<style>
.fake-table{display:table;width:100%;height:100%;}
.left-size{width:30%;height:100%;}
.left-size{width:70%;height:100%;}
</style>