Just to clarify the best practice:
Text format messages should almost always be stored as TEXT (they end up being arbitrarily long)
String attributes should be stored as VARCHAR (the destination user name, the subject, etc...).
I understand that you've got a front end limit, which is great until it isn't. *grin* The trick is to think of the DB as separate from the applications that connect to it. Just because one application puts a limit on the data, doesn't mean that the data is intrinsically limited.
What is it about the messages themselves that forces them to never be more then 3000 characters? If it's just an arbitrary application constraint (say, for a text box or something), use a TEXT
field at the data layer.
Excerpts from Kafka docs
Deprecations in 0.9.0.0
The kafka-consumer-offset-checker.sh (kafka.tools.ConsumerOffsetChecker) has been deprecated. Going forward, please use kafka-consumer-groups.sh (kafka.admin.ConsumerGroupCommand) for this functionality.
I am running Kafka broker with SSL enabled for both server and client. Below command I use
kafka-consumer-groups.sh --bootstrap-server Broker_IP:Port --list --command-config /tmp/ssl_config
kafka-consumer-groups.sh --bootstrap-server Broker_IP:Port --command-config /tmp/ssl_config --describe --group group_name_x
where /tmp/ssl_config is as below
security.protocol=SSL
ssl.truststore.location=truststore_file_path.jks
ssl.truststore.password=truststore_password
ssl.keystore.location=keystore_file_path.jks
ssl.keystore.password=keystore_password
ssl.key.password=key_password
Use CSS position: absolute;
followed by top: 0px; left 0px;
in the style
attribute of each DIV. Replace the pixel values with whatever you want.
You can use z-index: x;
to set the vertical "order" (which one is "on top"). Replace x
with a number, higher numbers are on top of lower numbers.
Here is how your new code would look:
<div>
<div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
Try this one -
function getYouTubeIdFromURL($url)
{
$pattern = '/(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})/i';
preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : false;
}
I think you've actually got a wider confusion here.
The initial error is that you're trying to call split
on the whole list of lines, and you can't split
a list of strings, only a string. So, you need to split
each line, not the whole thing.
And then you're doing for points in Type
, and expecting each such points
to give you a new x
and y
. But that isn't going to happen. Types
is just two values, x
and y
, so first points
will be x
, and then points will be y
, and then you'll be done. So, again, you need to loop over each line and get the x
and y
values from each line, not loop over a single Types
from a single line.
So, everything has to go inside a loop over every line in the file, and do the split
into x
and y
once for each line. Like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getQuakeData()
As a side note, you really should close
the file, ideally with a with
statement, but I'll get to that at the end.
Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getQuakeData()
Or, a better way to write that might be:
def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getQuakeData()
Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.
The above error run the commend line\
please change the command $ node server it's working and server is started
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
If your system is in English, use @Rick answer:
If your system is in Brazilian Portuguese, use this:
Import:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>
HTML:
<input class="mask" type="text" />
JS:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});
Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.
It is it, I hope that it help someone. I spend a lot of time to understand it.
Try this!
package your.package;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
// Configuration configuration = new Configuration();
Configuration configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException he)
{
System.err.println("Error creating Session: " + he);
throw new ExceptionInInitializerError(he);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
You need to do this:
var scope = {
splitterStyle: {
height: 100
}
};
And then apply this styling to the required elements:
<div id="horizontal" style={splitterStyle}>
In your code you are doing this (which is incorrect):
<div id="horizontal" style={height}>
Where height = 100
.
You're almost there. Use the following regex (with multi-line option enabled)
\bObject Name:\s+(.*)$
The complete match would be
Object Name: D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
while the captured group one would contain
D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
If you want to capture the file path directly use
(?m)(?<=\bObject Name:).*$
Just in case you have a nullable property in your class object:
private static DataTable ConvertToDatatable<T>(List<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
else
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
This solution is not very different from those above, but for me it works very well and i think it's clean.
I suggest to base64 encode the file server side (base64_encode(), if you are using PHP) and send the base64 encoded data to the client
On the client you do this:
let blob = this.dataURItoBlob(THE_MIME_TYPE + "," + response.file);
let uri = URL.createObjectURL(blob);
let link = document.createElement("a");
link.download = THE_FILE_NAME,
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
This code puts the encoded data in a link and simulates a click on the link, then it removes it.
Using binary AND
with 0b1111
:
String element = "el5";
char c = element.charAt(2);
System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9
Import jquery first before bootstrap:
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
$(this).dialog('destroy').remove()
This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM
Also check to see if you are missing the www in the url which was on my case
i was testing on http://www.mywebsite.com and in the facebook app i had set http://mywebsite.com
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run
Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.
Then you can create an ssh batch script such as
ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.
SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF
REM ------------------------------
REM SSH Server details
REM ------------------------------
:WEB1
CLS
call ssh [email protected]
cmd /k
:WEB2
CLS
call ssh [email protected]
cmd /k
This problem happened because either u install new version of jdk so you have both 32bit version and 64bit
how to solve the problem is just go open computer & go to c then you will see
after that you probably use 32 bit so just chose C:\Program Files and there you will find folder called java
in it
so you have many different version of jdk so easily chose jre7 and to to bin and you will find javaw.exe in it like
now only just take that path copy and go to start type eclipse.ini you will see text file just open it and before -vmargs
write -vm enter path like photo
now just open eclipse again and have fun :D
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
It can be done, I found it elsewhere on the web...this is no way my work ! :)
Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Private Declare Function SetDlgItemText Lib "user32" _
Alias "SetDlgItemTextA" _
(ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal lpString As String) As Long
Private Declare Function SetWindowsHookEx Lib "user32" _
Alias "SetWindowsHookExA" _
(ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As Long) As Long
' Handle to the Hook procedure
Private hHook As Long
' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7
Public Sub MsgBoxSmile()
' Set Hook
hHook = SetWindowsHookEx(WH_CBT, _
AddressOf MsgBoxHookProc, _
0, _
GetCurrentThreadId)
' Run MessageBox
MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub
Private Function MsgBoxHookProc(ByVal lMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
If lMsg = HCBT_ACTIVATE Then
SetDlgItemText wParam, IDYES, "Yes :-)"
SetDlgItemText wParam, IDNO, "No :-("
' Release the Hook
UnhookWindowsHookEx hHook
End If
MsgBoxHookProc = False
End Function
FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {...
Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.
Cheers
Per the docs, replace
returns the new string - it does not modify the string you pass it.
var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);
{
"User":[
{
"FirstUser":{
"name":"John"
},
"Information":"XY",
"SecondUser":{
"name":"Tom"
}
}
]
}
If I create model using previous json Using this link [blog]: http://www.jsoncafe.com to generate Codable structure or Any Format
Model
import Foundation
struct RootClass : Codable {
let user : [Users]?
enum CodingKeys: String, CodingKey {
case user = "User"
}
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: CodingKeys.self)
user = try? values?.decodeIfPresent([Users].self, forKey: .user)
}
}
struct Users : Codable {
let firstUser : FirstUser?
let information : String?
let secondUser : SecondUser?
enum CodingKeys: String, CodingKey {
case firstUser = "FirstUser"
case information = "Information"
case secondUser = "SecondUser"
}
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: CodingKeys.self)
firstUser = try? FirstUser(from: decoder)
information = try? values?.decodeIfPresent(String.self, forKey: .information)
secondUser = try? SecondUser(from: decoder)
}
}
struct SecondUser : Codable {
let name : String?
enum CodingKeys: String, CodingKey {
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: CodingKeys.self)
name = try? values?.decodeIfPresent(String.self, forKey: .name)
}
}
struct FirstUser : Codable {
let name : String?
enum CodingKeys: String, CodingKey {
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: CodingKeys.self)
name = try? values?.decodeIfPresent(String.self, forKey: .name)
}
}
Parse
do {
let res = try JSONDecoder().decode(RootClass.self, from: data)
print(res?.user?.first?.firstUser?.name ?? "Yours optional value")
} catch {
print(error)
}
Thanks to @Cory's hint, i used this:
inputChangeHandler : function (event) {
var stateObject = function() {
returnObj = {};
returnObj[this.target.id] = this.target.value;
return returnObj;
}.bind(event)();
this.setState( stateObject );
},
If using ES6 or the Babel transpiler to transform your JSX code, you can accomplish this with computed property names, too:
inputChangeHandler : function (event) {
this.setState({ [event.target.id]: event.target.value });
// alternatively using template strings for strings
// this.setState({ [`key${event.target.id}`]: event.target.value });
}
This worked perfectly HTML
<ul id="top-list">
<li><a href="#">Home</a></li>
<li><a href="#">Process</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Team</a></li>
<li><a href="#">Contact</a></li>
</ul>
CSS
#top-list{
list-style-type: none;
list-style: none;}
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
Where you've written "OffenceBox.Text()", you need to replace this with "OffenceBox.Text". It's a property, not a method - the clue's in the error!
Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.
You need to rename your main class to Main
, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main
.
That's all.
<form action="product.php" method="post" name="frmProduct" id="frmProduct" enctype="multipart/form-data">
<input id="submit_value" type="button" name="submit_value" value="">
</form>
<script type="text/javascript">
document.getElementById("submit_value").onclick = submitAction;
function submitAction()
{
document.getElementById("frmProduct").submit();
return false;
}
</script>
EDIT: I accidentally swapped the id's around
Besides all cited above, there are jQuery plugins that may help too:
for individual checkboxes:
for tree-like behavior checkboxes:
EDIT Both libraries uses the 'indeterminate' checkbox attribute, since this attribute in Html5 is just for styling (https://www.w3.org/TR/2011/WD-html5-20110113/number-state.html#checkbox-state), the null value is never sent to the server (checkboxes can only have two values).
To be able to submit this value to the server, I've create hidden counterpart fields which are populated on form submission using some javascript. On the server side, you'd need to check those counterpart fields instead of original checkboxes, of course.
I've used the first library (standalone checkboxes) where it's important to:
Hope that helps.
you can do it with this
Cursor cursor = database.query(
TABLE_NAME,
YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");
Something that just happened to me and caused me some headaches:
I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).
The script had several of those "code" blocks:
rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.
Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.
... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:
rabbitmqctl change_password test test
(Another solution would have been to delete all users and then call the script again)
// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
... do something
}
Explanation:
document.documentMode
An IE only property, first available in IE8.
/Edge/
A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property
Update Mar 2020
@Jam comments that the latest version of Edge now reports Edg
as the user agent. So the check would be:
if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
... do something
}
This may be an older topic, but if you are using Windows Vista or 7, I have a solution that will work very well. I made a video of it here: http://www.youtube.com/watch?v=mk8uAa6PIFM
Pastebin for the batch file is here
The UUID is used for uniquely identifying information. It identifies a particular service provided by a Bluetooth device. The standard defines a basic BASE_UUID: 00000000-0000-1000-8000-00805F9B34FB
.
Devices such as healthcare sensors can provide a service, substituting the first eight digits with a predefined code. For example, a device that offers an RFCOMM connection uses the short code: 0x0003
So, an Android phone can connect to a device and then use the Service Discovery Protocol (SDP) to find out what services it provides (UUID).
In many cases, you don't need to use these fixed UUIDs. In the case your are creating a chat application, for example, one Android phone interacts with another Android phone that uses the same application and hence the same UUID.
So, you can set an arbitrary UUID for your application using, for example, one of the many random UUID generators on the web (for example).
Above error is because of the space in between two words.
Eg: Java located in C:\Program Files\Java --> Space in between Program and files would cause the above problem. If you remove the space, it would not show any error.
It took far too long but I finally found this document on Migrating MSBuild-Integrated solutions to Automatic Package Restore and I was able to resolve the issue using the methods described here.
'.nuget'
solution directory along from the solutionnuget.targets
from your .csproj
or .vbproj
files. Though not officially supported, the document links to a PowerShell script if you have a lot of projects which need to be cleaned up. I manually edited mine by hand so I can't give any feedback regarding my experience with it.When editing your files by hand, here's what you'll be looking for:
Solution File (.sln)
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Project File (.csproj / .vbproj)
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
Created a directive (ng-repeat with lazy loading)
which loads data when it reaches to bottom of the page and remove half of the previously loaded data and when it reaches to top of the div again previous data(depending upon on page number) will be loaded removing half of the current data So on DOM at a time only limited data is present which may leads to better performance instead of rendering whole data on load.
HTML CODE:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ListController">
<div class="row customScroll" id="customTable" datafilter pagenumber="pageNumber" data="rowData" searchdata="searchdata" itemsPerPage="{{itemsPerPage}}" totaldata="totalData" selectedrow="onRowSelected(row,row.index)" style="height:300px;overflow-y: auto;padding-top: 5px">
<!--<div class="col-md-12 col-xs-12 col-sm-12 assign-list" ng-repeat="row in CRGC.rowData track by $index | orderBy:sortField:sortReverse | filter:searchFish">-->
<div class="col-md-12 col-xs-12 col-sm-12 pdl0 assign-list" style="padding:10px" ng-repeat="row in rowData" ng-hide="row[CRGC.columns[0].id]=='' && row[CRGC.columns[1].id]==''">
<!--col1-->
<div ng-click ="onRowSelected(row,row.index)"> <span>{{row["sno"]}}</span> <span>{{row["id"]}}</span> <span>{{row["name"]}}</span></div>
<!-- <div class="border_opacity"></div> -->
</div>
</div>
</body>
</html>
Angular CODE:
var app = angular.module('plunker', []);
var x;
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];
function ListController($scope, $timeout, $q, $templateCache) {
$scope.itemsPerPage = 40;
$scope.lastPage = 0;
$scope.maxPage = 100;
$scope.data = [];
$scope.pageNumber = 0;
$scope.makeid = function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$scope.DataFormFunction = function() {
var arrayObj = [];
for (var i = 0; i < $scope.itemsPerPage*$scope.maxPage; i++) {
arrayObj.push({
sno: i + 1,
id: Math.random() * 100,
name: $scope.makeid()
});
}
$scope.totalData = arrayObj;
$scope.totalData = $scope.totalData.filter(function(a,i){ a.index = i; return true; })
$scope.rowData = $scope.totalData.slice(0, $scope.itemsperpage);
}
$scope.DataFormFunction();
$scope.onRowSelected = function(row,index){
console.log(row,index);
}
}
angular.module('plunker').controller('ListController', ListController).directive('datafilter', function($compile) {
return {
restrict: 'EAC',
scope: {
data: '=',
totalData: '=totaldata',
pageNumber: '=pagenumber',
searchdata: '=',
defaultinput: '=',
selectedrow: '&',
filterflag: '=',
totalFilterData: '='
},
link: function(scope, elem, attr) {
//scope.pageNumber = 0;
var tempData = angular.copy(scope.totalData);
scope.totalPageLength = Math.ceil(scope.totalData.length / +attr.itemsperpage);
console.log(scope.totalData);
scope.data = scope.totalData.slice(0, attr.itemsperpage);
elem.on('scroll', function(event) {
event.preventDefault();
// var scrollHeight = angular.element('#customTable').scrollTop();
var scrollHeight = document.getElementById("customTable").scrollTop
/*if(scope.filterflag && scope.pageNumber != 0){
scope.data = scope.totalFilterData;
scope.pageNumber = 0;
angular.element('#customTable').scrollTop(0);
}*/
if (scrollHeight < 100) {
if (!scope.filterflag) {
scope.scrollUp();
}
}
if (angular.element(this).scrollTop() + angular.element(this).innerHeight() >= angular.element(this)[0].scrollHeight) {
console.log("scroll bottom reached");
if (!scope.filterflag) {
scope.scrollDown();
}
}
scope.$apply(scope.data);
});
/*
* Scroll down data append function
*/
scope.scrollDown = function() {
if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
scope.totalDataCompare = scope.totalData;
} else {
scope.totalDataCompare = scope.totalFilterData;
}
scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
if (scope.pageNumber < scope.totalPageLength - 1) {
scope.pageNumber++;
scope.lastaddedData = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage, (+attr.itemsperpage) + (+scope.pageNumber * attr.itemsperpage));
scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
scope.data = scope.data.concat(scope.lastaddedData);
scope.$apply(scope.data);
if (scope.pageNumber < scope.totalPageLength) {
var divHeight = $('.assign-list').outerHeight();
if (!scope.moveToPositionFlag) {
angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
} else {
scope.moveToPositionFlag = false;
}
}
}
}
/*
* Scroll up data append function
*/
scope.scrollUp = function() {
if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
scope.totalDataCompare = scope.totalData;
} else {
scope.totalDataCompare = scope.totalFilterData;
}
scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
if (scope.pageNumber > 0) {
this.positionData = scope.data[0];
scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
var position = +attr.itemsperpage * scope.pageNumber - 1.5 * (+attr.itemsperpage);
if (position < 0) {
position = 0;
}
scope.TopAddData = scope.totalDataCompare.slice(position, (+attr.itemsperpage) + position);
scope.pageNumber--;
var divHeight = $('.assign-list').outerHeight();
if (position != 0) {
scope.data = scope.TopAddData.concat(scope.data);
scope.$apply(scope.data);
angular.element('#customTable').scrollTop(divHeight * 1 * (+attr.itemsperpage));
} else {
scope.data = scope.TopAddData;
scope.$apply(scope.data);
angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
}
}
}
}
};
});
Another Solution: If you using UI-grid in the project then same implementation is there in UI grid with infinite-scroll.
Depending upon height of the division it loads the data and upon scroll new data will be append and previous data will be removed.
HTML Code:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdn.rawgit.com/angular-ui/bower-ui-grid/master/ui-grid.min.css" type="text/css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ListController">
<div class="input-group" style="margin-bottom: 15px">
<div class="input-group-btn">
<button class='btn btn-primary' ng-click="resetList()">RESET</button>
</div>
<input class="form-control" ng-model="search" ng-change="abc()">
</div>
<div data-ui-grid="gridOptions" class="grid" ui-grid-selection data-ui-grid-infinite-scroll style="height :400px"></div>
<button ng-click="getProductList()">Submit</button>
</body>
</html>
Angular Code:
var app = angular.module('plunker', ['ui.grid', 'ui.grid.infiniteScroll', 'ui.grid.selection']);
var x;
angular.module('plunker').controller('ListController', ListController);
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];
function ListController($scope, $timeout, $q, $templateCache) {
$scope.itemsPerPage = 200;
$scope.lastPage = 0;
$scope.maxPage = 5;
$scope.data = [];
var request = {
"startAt": "1",
"noOfRecords": $scope.itemsPerPage
};
$templateCache.put('ui-grid/selectionRowHeaderButtons',
"<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"row.isSelected\" ng-click=\"row.isSelected=!row.isSelected;selectButtonClick(row, $event)\"> </div>"
);
$templateCache.put('ui-grid/selectionSelectAllButtons',
"<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-if=\"grid.options.enableSelectAll\"><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"grid.selection.selectAll\" ng-click=\"grid.selection.selectAll=!grid.selection.selectAll;headerButtonClick($event)\"></div>"
);
$scope.gridOptions = {
infiniteScrollDown: true,
enableSorting: false,
enableRowSelection: true,
enableSelectAll: true,
//enableFullRowSelection: true,
columnDefs: [{
field: 'sno',
name: 'sno'
}, {
field: 'id',
name: 'ID'
}, {
field: 'name',
name: 'My Name'
}],
data: 'data',
onRegisterApi: function(gridApi) {
gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.loadMoreData);
$scope.gridApi = gridApi;
}
};
$scope.gridOptions.multiSelect = true;
$scope.makeid = function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$scope.abc = function() {
var a = $scope.search;
x = $scope.searchData;
$scope.data = x.filter(function(arr, y) {
return arr.name.indexOf(a) > -1
})
console.log($scope.data);
if ($scope.gridApi.grid.selection.selectAll)
$timeout(function() {
$scope.gridApi.selection.selectAllRows();
}, 100);
}
$scope.loadMoreData = function() {
var promise = $q.defer();
if ($scope.lastPage < $scope.maxPage) {
$timeout(function() {
var arrayObj = [];
for (var i = 0; i < $scope.itemsPerPage; i++) {
arrayObj.push({
sno: i + 1,
id: Math.random() * 100,
name: $scope.makeid()
});
}
if (!$scope.search) {
$scope.lastPage++;
$scope.data = $scope.data.concat(arrayObj);
$scope.gridApi.infiniteScroll.dataLoaded();
console.log($scope.data);
$scope.searchData = $scope.data;
// $scope.data = $scope.searchData;
promise.resolve();
if ($scope.gridApi.grid.selection.selectAll)
$timeout(function() {
$scope.gridApi.selection.selectAllRows();
}, 100);
}
}, Math.random() * 1000);
} else {
$scope.gridApi.infiniteScroll.dataLoaded();
promise.resolve();
}
return promise.promise;
};
$scope.loadMoreData();
$scope.getProductList = function() {
if ($scope.gridApi.selection.getSelectedRows().length > 0) {
$scope.gridOptions.data = $scope.resultSimulatedData;
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows(); //<--Property undefined error here
console.log($scope.mySelectedRows);
//alert('Selected Row: ' + $scope.mySelectedRows[0].id + ', ' + $scope.mySelectedRows[0].name + '.');
} else {
alert('Select a row first');
}
}
$scope.getSelectedRows = function() {
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
}
$scope.headerButtonClick = function() {
$scope.selectAll = $scope.grid.selection.selectAll;
}
}
x = math.ceil(x * 100.0) / 100.0
You could use Jackson to do this. I have yet to find a simple Gson solution.
Where data_map.json
is a JSON (object) resource file
and data_list.json
is a JSON (array) resource file.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Based on:
*
* http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
*/
public class JsonLoader {
private static final ObjectMapper OBJ_MAPPER;
private static final TypeReference<Map<String,Object>> OBJ_MAP;
private static final TypeReference<List<Map<String,Object>>> OBJ_LIST;
static {
OBJ_MAPPER = new ObjectMapper();
OBJ_MAP = new TypeReference<Map<String,Object>>(){};
OBJ_LIST = new TypeReference<List<Map<String,Object>>>(){};
}
public static void main(String[] args) {
try {
System.out.println(jsonToString(parseJsonString(read("data_map.json", true))));
System.out.println(jsonToString(parseJsonString(read("data_array.json", true))));
} catch (IOException e) {
e.printStackTrace();
}
}
private static final Object parseJsonString(String jsonString) {
try {
if (jsonString.startsWith("{")) {
return readJsonObject(jsonString);
} else if (jsonString.startsWith("[")) {
return readJsonArray(jsonString);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String jsonToString(Object json) throws JsonProcessingException {
return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}
private static final Map<String,Object> readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP);
}
private static final List<Map<String,Object>> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST);
}
public static final Map<String,Object> loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP);
}
public static final List<Map<String,Object>> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST);
}
private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonLoader.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
protected static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
protected static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
public static String read(String path, boolean isResource) throws IOException {
return read(path, "UTF-8", isResource);
}
public static String read(String path, String charset, boolean isResource) throws IOException {
return read(pathToUrl(path, isResource), charset);
}
@SuppressWarnings("resource")
public static String read(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
}
Here is the complete code for Dheeraj Sachan's example.
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
public class JsonHandler {
private static ObjectMapper propertyMapper;
static {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
propertyMapper = new ObjectMapper();
propertyMapper.setDateFormat(df);
propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
private static class MyHashMap extends HashMap<String, List<Video>>{
private static final long serialVersionUID = 7023107716981734468L;
}
private static class Video implements Serializable {
private static final long serialVersionUID = -446275421030765463L;
private String dashUrl;
private String videoBitrate;
private String audioBitrate;
private int videoWidth;
private int videoHeight;
private long fileSize;
@Override
public String toString() {
return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate
+ ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]";
}
}
public static void main(String[] args) {
try {
HashMap<String, List<Video>> map = loadJson("sample.json", true);
Iterator<Entry<String, List<Video>>> lectures = map.entrySet().iterator();
while (lectures.hasNext()) {
Entry<String, List<Video>> lecture = lectures.next();
System.out.printf("Lecture #%s%n", lecture.getKey());
for (Video video : lecture.getValue()) {
System.out.println(video);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
try {
if (json == null) {
return null;
}
return propertyMapper.readValue(json, classOfT);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonHandler.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
public static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
public static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
@SuppressWarnings("resource")
public static String readFile(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
public static String loadJsonString(String path, boolean isResource) throws IOException {
return readFile(path, isResource, "UTF-8");
}
public static String readFile(String path, boolean isResource, String charset) throws IOException {
return readFile(pathToUrl(path, isResource), charset);
}
public static HashMap<String, List<Video>> loadJson(String jsonString) throws IOException {
return JsonHandler.parseUnderScoredResponse(jsonString, MyHashMap.class);
}
public static HashMap<String, List<Video>> loadJson(String path, boolean isResource) throws IOException {
return loadJson(loadJsonString(path, isResource));
}
}
Not calling Close
probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...
Close
has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing
and FormClosed
in order to react accordingly.
I'm not clear whether FormClosing
and/or FormClosed
are raised if you simply dispose the form but I'll leave that to you to experiment with.
As per the other posting here, the best solution is to use the CSS entry of
style="border:0;"
use default convertation class: Convert.ToDecimal(Double)
on the BlueStacks emulator worked for me the following solution
Go to ”Settings” -> “Applications” -> “Manage Applications” and select “All”
Go to “Google Play Services Framework” and select “Clear Data” & “Clear Cache” to remove all the data.
Go to “Google Play Store” and Select “Clear Data” & “Clear Cache” to remove all the data regarding Google Play Store.
Go to “Settings” -> “Accounts” -> “Google” -> Select “Your Account”
Go to “Menu” and Select “Remove Account”.
Now “Restart” your mobile device.
Go to “Menu” and “Add Your Account”.
and try to perform update or download.
Use pandas!
def isMonthEnd(date):
return date + pd.offsets.MonthEnd(0) == date
isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False
DataFrame.to_dict()
converts DataFrame to dictionary.
Example
>>> df = pd.DataFrame(
{'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
col1 col2
a 1 0.1
b 2 0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
See this Documentation for details
In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved
Probably too late for an answere but, try this one
Get-Content <filename> -tail <number of items wanted>
As well as making sure that you have first called $("#myForm").validate();
, make sure that your dynamic control has been added to the DOM before adding the validation rules.
Just backgrounding your script (./myscript &
) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so that SIGHUP
does not kill it. You can take a shortcut to make a script appear to act like a daemon;
nohup ./myscript 0<&- &>/dev/null &
will do the job. Or, to capture both stderr and stdout to a file:
nohup ./myscript 0<&- &> my.admin.log.file &
However, there may be further important aspects that you need to consider. For example:
chdir("/")
(or cd /
inside your script), and fork so that the parent exits, and thus the original descriptor is closed.umask 0
. You may not want to depend on the umask of the caller of the daemon.For an example of a script that takes all of these aspects into account, see Mike S' answer.
Acceptance testing is just testing carried out by the client, and includes other kinds of testing:
For functional testing vs non-functional testing (their subtypes) - see my answer to this SO question.
Vector
is a broken class that is not threadsafe, despite it being "synchronized" and is only used by students and other inexperienced programmers.
ArrayList
is the go-to List implementation used by professionals and experienced programmers.
Professionals wanting a threadsafe List implementation use a CopyOnWriteArrayList
.
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
In Certificates Panel, right click some certificate -> All tasks -> Manage private key -> Add IIS_IUSRS User with full control
In my case, I didnt't need to install my certificate with "Allow private key to be exported" option checked, like said in other answers.
You should try :
<?php
echo CI_VERSION;
?>
Or check the file system/core/CodeIgniter.php
This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd
( .
)
find . -size 0 | xargs rm
It's simply pointless to create variable variable names. Why?
exec
or globals()
exec/globals()
againUsing a list is much easier:
# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
print string
print string[6] # or pick any of them
Using the knitr package:
```{r, engine='bash', code_block_name} ...
E.g.:
```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```
You can also use:
engine='sh'
for shellengine='python'
for Pythonengine='perl'
, engine='haskell'
and a bunch of other C-like languages and even gawk
, AWK, etc.This is my script to rebuild docker container, stop and start it again
docker pull [registry]/[image]:latest
docker build --no-cache -t [localregistry]/[localimagename]:latest -f compose.yaml context/
docker ps --no-trunc | grep [localimagename] | awk '{print $1}' | xargs docker stop
docker run -d -p 8111:80 [localregistry]/[localimagename]:latest
note --no-trunc argument which shows the image name or other info in full lenght in the output
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
You can run your file in http-server.
1> Have Node.js installed in your system.
2> In CMD, run the command npm install http-server -g
3> Navigate to the specific path of your file folder in CMD and run the command http-server
4> Go to your browser and type localhost:8080. Your Application should run there.
Thanks:)
I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically
ex..
if (dt.Rows.Count > 0)
{
dataGridViewProjects.DataSource = dt;
dataGridViewProjects.Columns["Title"].Width = 300;
dataGridViewProjects.Columns["ID"].Visible = false;
}
I suggest to make an Extension of pull To Refresh to use in every class.
1) Make an empty swift file : File - New - File - Swift File.
2) Add the Following
// AppExtensions.swift
import Foundation
import UIKit
var tableRefreshControl:UIRefreshControl = UIRefreshControl()
//MARK:- VIEWCONTROLLER EXTENSION METHODS
public extension UIViewController
{
func makePullToRefreshToTableView(tableName: UITableView,triggerToMethodName: String){
tableRefreshControl.attributedTitle = NSAttributedString(string: "TEST: Pull to refresh")
tableRefreshControl.backgroundColor = UIColor.whiteColor()
tableRefreshControl.addTarget(self, action: Selector(triggerToMethodName), forControlEvents: UIControlEvents.ValueChanged)
tableName.addSubview(tableRefreshControl)
}
func makePullToRefreshEndRefreshing (tableName: String)
{
tableRefreshControl.endRefreshing()
//additional codes
}
}
3) In Your View Controller call these methods as :
override func viewWillAppear(animated: Bool) {
self.makePullToRefreshToTableView(bidderListTable, triggerToMethodName: "pullToRefreshBidderTable")
}
4) At some point you wanted to end refreshing:
func pullToRefreshBidderTable() {
self.makePullToRefreshEndRefreshing("bidderListTable")
//Code What to do here.
}
OR
self.makePullToRefreshEndRefreshing("bidderListTable")
After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.
Beyond that, googling PHP compiler
turns up a number of 3rd party solutions.
bcompiler_write_exe_footer()
manual)https://regex101.com/r/Jjc2xR/1
/(\w*\(Hex\): w*)(.*?)(?= |$)/gm
I'm sure this one works, it will capture de hexa serial in the badly structured text multilined bellow
Space Reservation: disabled
Serial Number: wCVt1]IlvQWv
Serial Number (Hex): 77435674315d496c76515776
Comment: new comment
I'm a eternal newbie in regex but I'll try explain this one
(\w*(Hex): w*) : Find text in line where string contains "Hex: "
(.*?) This is the second captured text and means everything after
(?= |$) create a limit that is the space between = and the |
So with the second group, you will have the value
I got the following error when using strict mode:
Node error: "Octal literals are not allowed in strict mode."
The following solution works (source):
process.stdout.write("received: " + bytesReceived + "\x1B[0G");
Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
Although I'm sure this won't be accepted as the answer to this very old question, I came here looking for a way to do this and this is how I solved the problem.
I created a demonstration here at codepen.io.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
The time is now: <span class="now"></span>, a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>
var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
$(".difference > span").text(moment().to(then));
$(".countdown").text(countdown(then).toString());
requestAnimationFrame(timerLoop);
})();
The time is now: 5:29:35 pm, a timer will go off in a minute at 5:30:35 pm
The timer is set to go off in a minute
1 minute
Note: 2nd line above updates as per momentjs and 3rd line above updates as per countdownjs and all of this is animated at about ~60FPS because of requestAnimationFrame()
Alternatively you can just look at this code snippet:
var now = moment(); // new Date().getTime();_x000D_
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);_x000D_
_x000D_
$(".now").text(moment(now).format('h:mm:ss a'));_x000D_
$(".then").text(moment(then).format('h:mm:ss a'));_x000D_
$(".duration").text(moment(now).to(then));_x000D_
(function timerLoop() {_x000D_
$(".difference > span").text(moment().to(then));_x000D_
$(".countdown").text(countdown(then).toString());_x000D_
requestAnimationFrame(timerLoop);_x000D_
})();_x000D_
_x000D_
// CountdownJS: http://countdownjs.org/_x000D_
// Rawgit: http://rawgit.com/_x000D_
// MomentJS: http://momentjs.com/_x000D_
// jQuery: https://jquery.com/_x000D_
// Light reading about the requestAnimationFrame pattern:_x000D_
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/_x000D_
// https://css-tricks.com/using-requestanimationframe/
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>_x000D_
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>_x000D_
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>_x000D_
<div>_x000D_
The time is now: <span class="now"></span>,_x000D_
</div>_x000D_
<div>_x000D_
a timer will go off <span class="duration"></span> at <span class="then"></span>_x000D_
</div>_x000D_
<div class="difference">The timer is set to go off <span></span></div>_x000D_
<div class="countdown"></div>
_x000D_
requestAnimationFrame()
- use this for animation rather than setInterval()
.Additionally here is some light reading about the requestAnimationFrame()
pattern:
I found the requestAnimationFrame()
pattern to be much a more elegant solution than the setInterval()
pattern.
If you are using pandas and have lots of RAM (enough to read the whole file into memory) try using pd.read_csv
with low_memory=False
, e.g.:
import pandas as pd
data = pd.read_csv('file.csv', low_memory=False)
We can use @SpringBootTest annotation which loads the yml file from src\main\java\com...hence when we execute the unit test, all of the properties are already there in the config properties class.
@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressFieldsTest {
@InjectMocks
AddressFieldsValidator addressFieldsValidator;
@Autowired
AddressFieldsConfig addressFieldsConfig;
...........
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(addressFieldsValidator,"addressFieldsConfig", addressFieldsConfig);
}
}
We can use @Value annotation if you have few configs or other wise we can use a config properties class. For e.g
@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "address.fields.regex")
public class AddressFieldsConfig {
private int firstName;
private int lastName;
.........
I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.
If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.
- Rich ToolTips rather than text
- WPF context menus and popups
- Command support and routed events
- Flexible data binding
- Rich balloon messages rather than the default messages provides by the OS
Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
kotlin minimalist version
fun getIpv4HostAddress(): String {
NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
networkInterface.inetAddresses?.toList()?.find {
!it.isLoopbackAddress && it is Inet4Address
}?.let { return it.hostAddress }
}
return ""
}
In the UIView
docs, have a read about this function for ios4+
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion
Say you want to remove the second object by it's field property.
With ES6 it's as easy as this.
myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)
java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.
Option 1: Go to Android SDK Folder --> Extra --> Intel and double click on HAXM installer and install it manually.
Option 2: If you do not have latest version of HAXM then you can open sdk manager in android studio and download it.
Option 3: Download HAXM intaller from Intel site. https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
This works fine for me. It allows value to be entered even after focus changed and retrieved back. For example: 123.00
, 12.12
, 0.01
, etc..
1.Integer.parseInt(getString(R.string.valuelength))
Specifies the length of the input digits.Values
accessed from string.xml
file.It is quiet easy to change values.
2.Integer.parseInt(getString(R.string.valuedecimal))
, this is for decimal places max limit.
private InputFilter[] valDecimalPlaces;
private ArrayList<EditText> edittextArray;
valDecimalPlaces = new InputFilter[] { new DecimalDigitsInputFilterNew(
Integer.parseInt(getString(R.string.valuelength)),
Integer.parseInt(getString(R.string.valuedecimal)))
};
Array of EditText
values that allows to perform action.
for (EditText etDecimalPlace : edittextArray) {
etDecimalPlace.setFilters(valDecimalPlaces);
I just used array of values that contain multiple edittext
Next DecimalDigitsInputFilterNew.class
file.
import android.text.InputFilter;
import android.text.Spanned;
public class DecimalDigitsInputFilterNew implements InputFilter {
private final int decimalDigits;
private final int before;
public DecimalDigitsInputFilterNew(int before ,int decimalDigits) {
this.decimalDigits = decimalDigits;
this.before = before;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches("(([0-9]{1})([0-9]{0,"+(before-1)+"})?)?(\\.[0-9]{0,"+decimalDigits+"})?")) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
}
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
Standard Unix exit codes are defined by sysexits.h, as another poster mentioned. The same exit codes are used by portable libraries such as Poco - here is a list of them:
http://pocoproject.org/docs/Poco.Util.Application.html#16218
A signal 11 is a SIGSEGV (segment violation) signal, which is different from a return code. This signal is generated by the kernel in response to a bad page access, which causes the program to terminate. A list of signals can be found in the signal man page (run "man signal").
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.
People would usually describe it as a "contract" for what must be available in the methods of the class.
It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
To read directory contents you can use readdir() and use a script, in my example download.php
, to download files
if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}
In download.php
you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php
$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
A kotlin version
fun openAppInPlayStore() {
val uri = Uri.parse("market://details?id=" + context.packageName)
val goToMarketIntent = Intent(Intent.ACTION_VIEW, uri)
var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
flags = if (Build.VERSION.SDK_INT >= 21) {
flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
} else {
flags or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
goToMarketIntent.addFlags(flags)
try {
startActivity(context, goToMarketIntent, null)
} catch (e: ActivityNotFoundException) {
val intent = Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))
startActivity(context, intent, null)
}
}
There is a tablePlugin for jspdf it expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.
To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:
Run the following javascript in the console. This will break into the debugger in 5 seconds.
setTimeout(function(){debugger;}, 5000)
Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.
Elements
tab in the Chrome Inspector, and you can look for your element there. Find Element
icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element
Note that this approach is a slight variation to this other great answer on this page.
Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:
Minor variation to user1850980's answer (for the question "How to initialize a list of empty dictionaries") using list constructor:
dictlistGOOD = list( {} for i in xrange(listsize) )
I found out to my chagrin, this does NOT work:
dictlistFAIL = [{}] * listsize # FAIL!
as it creates a list of references to the same empty dictionary, so that if you update one dictionary in the list, all the other references get updated too.
Try these updates to see the difference:
dictlistGOOD[0]["key"] = "value"
dictlistFAIL[0]["key"] = "value"
(I was actually looking for user1850980's answer to the question asked, so his/her answer was helpful.)
Correct way described in this answer: https://stackoverflow.com/a/52772444/2519714 Most popular answer at current moment is not totally correct.
This way https://stackoverflow.com/a/24838367/2519714 is not correct in some cases like: sub select has where bindings, then joining table to sub select, then other wheres added to all query. For example query:
select * from (select * from t1 where col1 = ?) join t2 on col1 = col2 and col3 = ? where t2.col4 = ?
To make this query you will write code like:
$subQuery = DB::query()->from('t1')->where('t1.col1', 'val1');
$query = DB::query()->from(DB::raw('('. $subQuery->toSql() . ') AS subquery'))
->mergeBindings($subQuery->getBindings());
$query->join('t2', function(JoinClause $join) {
$join->on('subquery.col1', 't2.col2');
$join->where('t2.col3', 'val3');
})->where('t2.col4', 'val4');
During executing this query, his method $query->getBindings()
will return bindings in incorrect order like ['val3', 'val1', 'val4']
in this case instead correct ['val1', 'val3', 'val4']
for raw sql described above.
One more time correct way to do this:
$subQuery = DB::query()->from('t1')->where('t1.col1', 'val1');
$query = DB::query()->fromSub($subQuery, 'subquery');
$query->join('t2', function(JoinClause $join) {
$join->on('subquery.col1', 't2.col2');
$join->where('t2.col3', 'val3');
})->where('t2.col4', 'val4');
Also bindings will be automatically and correctly merged to new query.
Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
For me the error message goes away if I unmount the old mount before mounting it again:
fusermount -u /mnt/point
If it's not already mounted you get a non-critical error:
$ fusermount -u /mnt/point
fusermount: entry for /mnt/point not found in /etc/mtab
So in my script I just put unmount it before mounting it.
// Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }
// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }
var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');
This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.
If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.
SHOW VARIABLES LIKE "%version%";
+-------------------------+------------------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------------------+
| protocol_version | 10 |
| version | 5.0.27-standard |
| version_comment | MySQL Community Edition - Standard (GPL) |
| version_compile_machine | i686 |
| version_compile_os | pc-linux-gnu |
+-------------------------+------------------------------------------+
5 rows in set (0.04 sec)
MySQL 5.0 Reference Manual (pdf) - Determining Your Current MySQL Version - page 42
To get the cell value, you need to read it directly from DataGridView1
using e.RowIndex
and e.ColumnIndex
properties.
Eg:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If IsDBNull(value) Then
TextBox1.Text = "" ' blank if dbnull values
Else
TextBox1.Text = CType(value, String)
End If
End Sub
This picture should give you the idea about the context in which the words breadth and depth are used.
Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.
It generally uses a Stack
to remember where it should go when it reaches a dead end.
Rules to follow: Push first vertex A on to the Stack
Java code:
public void searchDepthFirst() {
// Begin at vertex 0 (A)
vertexList[0].wasVisited = true;
displayVertex(0);
stack.push(0);
while (!stack.isEmpty()) {
int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
// If no such vertex
if (adjacentVertex == -1) {
stack.pop();
} else {
vertexList[adjacentVertex].wasVisited = true;
// Do something
stack.push(adjacentVertex);
}
}
// Stack is empty, so we're done, reset flags
for (int j = 0; j < nVerts; j++)
vertexList[j].wasVisited = false;
}
Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.
Queue
.Java code:
public void searchBreadthFirst() {
vertexList[0].wasVisited = true;
displayVertex(0);
queue.insert(0);
int v2;
while (!queue.isEmpty()) {
int v1 = queue.remove();
// Until it has no unvisited neighbors, get one
while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
vertexList[v2].wasVisited = true;
// Do something
queue.insert(v2);
}
}
// Queue is empty, so we're done, reset flags
for (int j = 0; j < nVerts; j++)
vertexList[j].wasVisited = false;
}
Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.
Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.
Depending on which event you actually want to use (textbox change
, or button click
), you can try this:
HTML:
<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>
JS:
function changeBackground(obj) {
document.getElementById("coltext").style.color = obj.value;
}
DEMO: http://jsfiddle.net/6pLUh/
One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange
allows you to change the color based on the input.
try put cd before the file path
example:
C:\Users\user>cd C:\Program Files\MongoDB\Server\4.4\bin
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
Understanding the language syntax is important when considering clarity of code. Consider copying a character string, for example with post-increment:
char a[256] = "Hello world!";
char b[256];
int i = 0;
do {
b[i] = a[i];
} while (a[i++]);
We want the loop to execute through encountering the zero character (which tests false) at the end of the string. That requires testing the value pre-increment and also incrementing the index. But not necessarily in that order - a way to code this with the pre-increment would be:
int i = -1;
do {
++i;
b[i] = a[i];
} while (a[i]);
It is a matter of taste which is clearer and if the machine has a handfull of registers both should have identical execution time, even if a[i] is a function that is expensive or has side-effects. A significant difference might be the exit value of the index.
I'm not sure at what level you're asking this question. It sounds as if you've found the formulas online, and are just trying to understand what it does. On that reading of your question I offer:
File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
.getLastPathSegment();
final String filePath = fullfileName.
substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);
fullfileName:
/mnt/sdcard/Download_Manager_Farsi/preview.png
filePath:
/mnt/sdcard/Download_Manager_Farsi
Riffing on a side question asked by the OP in a comment, i.e.:
what if I had a generator that yields the values from range(11) instead of a list. Would it be possible to replace values in the generator?
Sure, it's trivially easy...:
def replaceiniter(it, predicate, replacement=None):
for item in it:
if predicate(item): yield replacement
else: yield item
Just pass any iterable (including the result of calling a generator) as the first arg, the predicate to decide if a value must be replaced as the second arg, and let 'er rip.
For example:
>>> list(replaceiniter(xrange(11), lambda x: x%2))
[0, None, 2, None, 4, None, 6, None, 8, None, 10]
A reproducible example:
the_plot <- function()
{
x <- seq(0, 1, length.out = 100)
y <- pbeta(x, 1, 10)
plot(
x,
y,
xlab = "False Positive Rate",
ylab = "Average true positive rate",
type = "l"
)
}
James's suggestion of using pointsize
, in combination with the various cex
parameters, can produce reasonable results.
png(
"test.png",
width = 3.25,
height = 3.25,
units = "in",
res = 1200,
pointsize = 4
)
par(
mar = c(5, 5, 2, 2),
xaxs = "i",
yaxs = "i",
cex.axis = 2,
cex.lab = 2
)
the_plot()
dev.off()
Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,
library(ggplot2)
ggplot_alternative <- function()
{
the_data <- data.frame(
x <- seq(0, 1, length.out = 100),
y = pbeta(x, 1, 10)
)
ggplot(the_data, aes(x, y)) +
geom_line() +
xlab("False Positive Rate") +
ylab("Average true positive rate") +
coord_cartesian(0:1, 0:1)
}
ggsave(
"ggtest.png",
ggplot_alternative(),
width = 3.25,
height = 3.25,
dpi = 1200
)
You need to include angular-route.js
in your HTML:
<script src="angular-route.js">
You can also just do this:
<svg viewBox="0 0 32 32">
<path d="M11.333 13.173c0-2.51 2.185-4.506 4.794-4.506 2.67 0 4.539 2.053 4.539 4.506 0 2.111-0.928 3.879-3.836 4.392v0.628c0 0.628-0.496 1.141-1.163 1.141s-1.163-0.513-1.163-1.141v-1.654c0-0.628 0.751-1.141 1.419-1.141 1.335 0 2.571-1.027 2.571-2.224 0-1.255-1.092-2.224-2.367-2.224-1.335 0-2.367 1.027-2.367 2.224 0 0.628-0.546 1.141-1.214 1.141s-1.214-0.513-1.214-1.141zM15.333 23.333c-0.347 0-0.679-0.143-0.936-0.404s-0.398-0.597-0.398-0.949 0.141-0.689 0.398-0.949c0.481-0.488 1.39-0.488 1.871 0 0.257 0.26 0.398 0.597 0.398 0.949s-0.141 0.689-0.398 0.949c-0.256 0.26-0.588 0.404-0.935 0.404zM16 26.951c-6.040 0-10.951-4.911-10.951-10.951s4.911-10.951 10.951-10.951c6.040 0 10.951 4.911 10.951 10.951s-4.911 10.951-10.951 10.951zM16 3.333c-6.984 0-12.667 5.683-12.667 12.667s5.683 12.667 12.667 12.667c6.984 0 12.667-5.683 12.667-12.667s-5.683-12.667-12.667-12.667z"></path>
</svg>
_x000D_
Protected data members can be accessed by any classes that inherit from your class. Private data members, however, cannot. Let's say we have the following:
class MyClass {
private:
int myPrivateMember; // lol
protected:
int myProtectedMember;
};
From within your extension to this class, referencing this.myPrivateMember
won't work. However, this.myProtectedMember
will. The value is still encapsulated, so if we have an instantiation of this class called myObj
, then myObj.myProtectedMember
won't work, so it is similar in function to a private data member.
see how exceptions work by default if one vs more attributes are used (tracebacks omitted):
>>> raise Exception('bad thing happened')
Exception: bad thing happened
>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')
so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:
>>> nastyerr = NastyError('bad thing happened')
>>> raise nastyerr
NastyError: bad thing happened
>>> raise nastyerr()
NastyError: bad thing happened
>>> raise nastyerr('code is broken')
NastyError: ('bad thing happened', 'code is broken')
this can be done easily with this subclass
class ExceptionTemplate(Exception):
def __call__(self, *args):
return self.__class__(*(self.args + args))
# ...
class NastyError(ExceptionTemplate): pass
and if you don't like that default tuple-like representation, just add __str__
method to the ExceptionTemplate
class, like:
# ...
def __str__(self):
return ': '.join(self.args)
and you'll have
>>> raise nastyerr('code is broken')
NastyError: bad thing happened: code is broken
In any one of your js pages you are missing
module.exports = router;
Check and verify all your JS pages
As mentioned above, be sure that you don't set any id fields which are supposed to be auto-generated.
To cause this problem during testing, make sure that the db 'sees' aka flush this SQL, otherwise everything may seem fine when really its not.
I encountered this problem when inserting my parent with a child into the db:
The 3. statement failed. Indeed the entry with the autogenerated ID (by Hibernate) was not in the table as a trigger changed the ID upon each insertion, thus letting the update fail with no matching row found.
Since the table can be updated without any Hibernate I added a check whether the ID is null and only fill it in then to the trigger.
I don't know of anything out of the box that can just validate all of that for you, however the Path
class in .NET
can help you out tremendously.
For starters, it has:
char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters
or:
Path.GetPathRoot(string); // will return the root.
To ignore missing @param
and @return
tags, it's enough to disable the missing
doclint group. This way, the javadoc will still be checked for higher level and syntax issues:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<doclint>all,-missing</doclint>
</configuration>
</plugin>
Note that this is for plugin version 3.0 or newer.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
You can use show innodb status
(or show engine innodb status
for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.
You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.
Here's what you'd want to look for:
------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status
In this case, there's just one connection to the InnoDB engine right now (my login, running the show
query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594
.
<script type="text/javascript">
function printDiv(divId) {
var printContents = document.getElementById(divId).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = "<html><head><title></title></head><body>" + printContents + "</body>";
window.print();
document.body.innerHTML = originalContents;
}
</script>
To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
If you care for it to be in the same order as before you can use a common table expression for that:
;WITH CTE AS (
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
)
SELECT *
FROM CTE
ORDER BY MySortColumn
Just use
as.Date("2001-01-01") + 45
from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.
Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).
R> library(RcppBDT)
Loading required package: Rcpp
R>
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
and 42 methods, of which 31 are possibly relevant:
addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear,
getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian,
getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize,
setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R>
val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
// (left, top, right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)
I suggest creating an extension function on TextView (Button extends it) for easy reuse.
button.leftDrawable(R.drawable.my_icon, 25)
// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = context.resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
With jQuery library-
Use .width()
and .height()
.
More in jQuery width and jQuery heigth.
$(document).ready(function(){_x000D_
$("button").click(function()_x000D_
{_x000D_
alert("Width of image: " + $("#img_exmpl").width());_x000D_
alert("Height of image: " + $("#img_exmpl").height());_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
_x000D_
<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">_x000D_
<button>Display dimensions of img</button>
_x000D_
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
Using private calls is a bad idea as Apple no longer approve apps that do that. Maybe you could try this:
//Init Animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration: 0.50];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:YES];
//Create ViewController
MyViewController *myVC = [[MyViewController alloc] initWith...];
[self.navigationController pushViewController:myVC animated:NO];
[myVC release];
//Start Animation
[UIView commitAnimations];
You can use two s commands
$ echo "Here is a String" | sed 's/.*Here//; s/String.*//'
is a
Also works
$ echo "Here is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
is a
$ echo "Here is a StringHere is a StringHere is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
is a
I have added few lines in your code and now its working fine with progress bar.
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main );
// Makes Progress bar Visible
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
setTitle("Loading...");
setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");
Your current solution does not work because $time
is a string - it needs to be a Unix timestamp. You can do this instead:
$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:
<xsl:template match="class">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
And if you need the variable to have "global" scope then declare it outside of the template:
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:template match="class">
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
git clone <remote-url>
<=>
git init
// init new repositorygit remote add origin <remote-url>
// add remotegit fetch
// fetch all remote branchsgit switch <default_branch>
// switch to the default branchgit pull
<=>
git pull <remote> <branch>
<=>
It seems many regex given miss one thing or another. This has been working for me so far:
(?i)^\s*[+-]?(?:inf(inity)?|nan|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*$
It allows for infinity (or inf) with sign, nan, no digit before the
decimal, and leading/trailing spaces (if desired). The ^
and $
are
needed to keep from partially matching something like 1.2f-2
as 1.2
.
You could use [ed]
instead of just e
if you need to parse some files
where D
is used for double-precision scientific notation. You would
want to replace it afterward or just replace them before checking since
the float()
function won't allow it.
Adding to the other answers, please keep in mind that StringBuilder can be told an initial amount of memory to allocate.
The capacity parameter defines the maximum number of characters that can be stored in the memory allocated by the current instance. Its value is assigned to the Capacity property. If the number of characters to be stored in the current instance exceeds this capacity value, the StringBuilder object allocates additional memory to store them.
If capacity is zero, the implementation-specific default capacity is used.
Repeatedly appending to a StringBuilder that hasn't been pre-allocated can result in a lot of unnecessary allocations just like repeatedly concatenating regular strings.
If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.
If you can't make any kind of guess about the size, you're probably writing a utility function which should have its own optional argument for controlling pre-allocation.
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
I believe what you are looking for is assign_attributes
.
It's basically the same as update_attributes but it doesn't save the record:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, :as => :admin
end
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name # => "Bob"
user.is_admin? # => false
user.new_record? # => true
Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.
By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.
For example:
namespace OOP
{
class Program
{
static void Main(string[] args)
{
Child somechild = new Child();
somechild.DoHomeWork();
somechild.CheckingAround();
Console.ReadLine();
}
}
public class Father
{
public Father() { }
public void Work()
{
Console.WriteLine("working...");
}
public void Moonlight()
{
Console.WriteLine("moonlighting...");
}
}
public class Mother
{
public Mother() { }
public void Cook()
{
Console.WriteLine("cooking...");
}
public void Clean()
{
Console.WriteLine("cleaning...");
}
}
public class Child
{
public Father MyFather { get; set; }
public Mother MyMother { get; set; }
public Child()
{
MyFather = new Father();
MyMother = new Mother();
}
public void GoToSchool()
{
Console.WriteLine("go to school...");
}
public void DoHomeWork()
{
Console.WriteLine("doing homework...");
}
public void CheckingAround()
{
MyFather.Work();
MyMother.Cook();
}
}
}
with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.
From the API for InetAddress
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log()
arguments and doesn't give an access to the original function.
Here's my version:
(function (logger) {_x000D_
console.old = console.log;_x000D_
console.log = function () {_x000D_
var output = "", arg, i;_x000D_
_x000D_
for (i = 0; i < arguments.length; i++) {_x000D_
arg = arguments[i];_x000D_
output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
if (_x000D_
typeof arg === "object" &&_x000D_
typeof JSON === "object" &&_x000D_
typeof JSON.stringify === "function"_x000D_
) {_x000D_
output += JSON.stringify(arg); _x000D_
} else {_x000D_
output += arg; _x000D_
}_x000D_
_x000D_
output += "</span> ";_x000D_
}_x000D_
_x000D_
logger.innerHTML += output + "<br>";_x000D_
console.old.apply(undefined, arguments);_x000D_
};_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old()
.
Here's a minified version of the script above to paste inline, just for you:
<script>
!function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span> ";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
(document.body);
</script>
Replace document.body
in the parentheses with whatever element you wish to log into.
Here is a late answer, just for simplistic approach using Int()
and If
in case of 1-3 character columns:
Function outColLetterFromNumber(i As Integer) As String
If i < 27 Then 'one-letter
col = Chr(64 + i)
ElseIf i < 677 Then 'two-letter
col = Chr(64 + Int(i / 26)) & Chr(64 + i - (Int(i / 26) * 26))
Else 'three-letter
col = Chr(64 + Int(i / 676)) & Chr(64 + Int(i - Int(i / 676) * 676) / 26)) & Chr(64 + i - (Int(i - Int(i / 676) * 676) / 26) * 26))
End If
outColLetterFromNumber = col
End Function
You can use:
if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
//...
}
This works with any .NET version.
Another way to do this
while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done
Let's test it with 2 HTTP request using curl
In this example, 172.16.2.6 is the server IP Address.
Server Side
admin@server:~$ while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done
GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*
GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*
Client Side
user@client:~$ curl 172.16.2.6:8080
My website has date function
Tue Jun 13 18:00:19 UTC 2017
user@client:~$ curl 172.16.2.6:8080
My website has date function
Tue Jun 13 18:00:24 UTC 2017
user@client:~$
If you want to execute another command, feel free to replace $(date).
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:
if(one)
if(two)
foo();
else
bar();
From this:
if(one)
if(two)
foo();
else
bar();
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }
In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.
So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.
Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
To avoid this error you should follow the following steps:
1) You should make a new java class
2) Name that class
3) And a new java class is made
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
Worked liked a charm for me:
matplotlib.rcParams['figure.figsize'] = (20, 10)
You can save generated diagram for future use.
public class JSONConvector {
public static String toJSON(Object object) throws JSONException, IllegalAccessException {
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static String toJSON(List list ) throws JSONException, IllegalAccessException {
JSONArray jsonArray = new JSONArray();
for (Object i : list) {
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);
}
return jsonArray.toString();
}
}
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
I don't know about the runtime disadvantages about the following but you could run a regexp match on your string to make sure it is a number before trying to parse it, thus
cost.matches("-?\\d+\\.?\\d+")
for a float
and
cost.matches("-?\\d+")
for an integer
EDIT
please notices @Voo's comment about max int
If you do not like assets folder you can edit .angular-cli.json
and add other folders you need.
"assets": [
"assets",
"img",
"favicon.ico"
]
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
//This code worked for me
class CountOfLettersOfString
{
static void Main()
{
Console.WriteLine("Enter string to check count of letters");
string name = Console.ReadLine();
//Method1
char[] testedalphabets = new char[26];
int[] letterCount = new int[26];
int countTestesd = 0;
Console.WriteLine($"Given String is:{name}");
for (int i = 0; i < name.Length - 1; i++)
{
int countChar = 1;
bool isCharTested = false;
for (int j = 0; j < testedalphabets.Length - 1; j++)
{
if (name[i] == testedalphabets[j])
{
isCharTested = true;
break;
}
}
if (!isCharTested)
{
testedalphabets[countTestesd] = name[i];
for (int k = i + 1; k < name.Length - 1; k++)
{
if (name[i] == name[k])
{
countChar++;
}
}
letterCount[countTestesd] = countChar;
countTestesd++;
}
else
{
continue;
}
}
for (int i = 0; i < testedalphabets.Length - 1; i++)
{
if (!char.IsLetter(testedalphabets[i]))
{
continue;
}
Console.WriteLine($"{testedalphabets[i]}-{letterCount[i]}");
}
//Method2
var g = from c in name.ToLower().ToCharArray() // make sure that L and l are the same eg
group c by c into m
select new { Key = m.Key, Count = m.Count() };
foreach (var item in g)
{
Console.WriteLine(string.Format("Character:{0} Appears {1} times", item.Key.ToString(), item.Count));
}
Console.ReadLine();
}
}
I know this question is very old, but I came upon it because I needed something cross platform for linux, win32... I wrote the function below, it is a single function that can parse INI files, hopefully others will find it useful.
rules & caveats: buf to parse must be a NULL terminated string. Load your ini file into a char array string and call this function to parse it. section names must have [] brackets around them, such as this [MySection], also values and sections must begin on a line without leading spaces. It will parse files with Windows \r\n or with Linux \n line endings. Comments should use # or // and begin at the top of the file, no comments should be mixed with INI entry data. Quotes and ticks are trimmed from both ends of the return string. Spaces are only trimmed if they are outside of the quote. Strings are not required to have quotes, and whitespaces are trimmed if quotes are missing. You can also extract numbers or other data, for example if you have a float just perform a atof(ret) on the ret buffer.
// -----note: no escape is nessesary for inner quotes or ticks-----
// -----------------------------example----------------------------
// [Entry2]
// Alignment = 1
// LightLvl=128
// Library = 5555
// StrValA = Inner "quoted" or 'quoted' strings are ok to use
// StrValB = "This a "quoted" or 'quoted' String Value"
// StrValC = 'This a "tick" or 'tick' String Value'
// StrValD = "Missing quote at end will still work
// StrValE = This is another "quote" example
// StrValF = " Spaces inside the quote are preserved "
// StrValG = This works too and spaces are trimmed away
// StrValH =
// ----------------------------------------------------------------
//12oClocker super lean and mean INI file parser (with section support)
//set section to 0 to disable section support
//returns TRUE if we were able to extract a string into ret value
//NextSection is a char* pointer, will be set to zero if no next section is found
//will be set to pointer of next section if it was found.
//use it like this... char* NextSection = 0; GrabIniValue(X,X,X,X,X,&NextSection);
//buf is data to parse, ret is the user supplied return buffer
BOOL GrabIniValue(char* buf, const char* section, const char* valname, char* ret, int retbuflen, char** NextSection)
{
if(!buf){*ret=0; return FALSE;}
char* s = buf; //search starts at "s" pointer
char* e = 0; //end of section pointer
//find section
if(section)
{
int L = strlen(section);
SearchAgain1:
s = strstr(s,section); if(!s){*ret=0; return FALSE;} //find section
if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain1;} //section must be at begining of a line!
s+=L; //found section, skip past section name
while(*s!='\n'){s++;} s++; //spin until next line, s is now begining of section data
e = strstr(s,"\n["); //find begining of next section or end of file
if(e){*e=0;} //if we found begining of next section, null the \n so we don't search past section
if(NextSection) //user passed in a NextSection pointer
{ if(e){*NextSection=(e+1);}else{*NextSection=0;} } //set pointer to next section
}
//restore char at end of section, ret=empty_string, return FALSE
#define RESTORE_E if(e){*e='\n';}
#define SAFE_RETURN RESTORE_E; (*ret)=0; return FALSE
//find valname
int L = strlen(valname);
SearchAgain2:
s = strstr(s,valname); if(!s){SAFE_RETURN;} //find valname
if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain2;} //valname must be at begining of a line!
s+=L; //found valname match, skip past it
while(*s==' ' || *s == '\t'){s++;} //skip spaces and tabs
if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return
if(*s != '='){goto SearchAgain2;} //no equal sign found after valname, search again
s++; //skip past the equal sign
while(*s==' ' || *s=='\t'){s++;} //skip spaces and tabs
while(*s=='\"' || *s=='\''){s++;} //skip past quotes and ticks
if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return
char* E = s; //s is now the begining of the valname data
while(*E!='\r' && *E!='\n' && *E!=0){E++;} E--; //find end of line or end of string, then backup 1 char
while(E > s && (*E==' ' || *E=='\t')){E--;} //move backwards past spaces and tabs
while(E > s && (*E=='\"' || *E=='\'')){E--;} //move backwards past quotes and ticks
L = E-s+1; //length of string to extract NOT including NULL
if(L<1 || L+1 > retbuflen){SAFE_RETURN;} //empty string or buffer size too small
strncpy(ret,s,L); //copy the string
ret[L]=0; //null last char on return buffer
RESTORE_E;
return TRUE;
#undef RESTORE_E
#undef SAFE_RETURN
}
How to use... example....
char sFileData[] = "[MySection]\r\n"
"MyValue1 = 123\r\n"
"MyValue2 = 456\r\n"
"MyValue3 = 789\r\n"
"\r\n"
"[MySection]\r\n"
"MyValue1 = Hello1\r\n"
"MyValue2 = Hello2\r\n"
"MyValue3 = Hello3\r\n"
"\r\n";
char str[256];
char* sSec = sFileData;
char secName[] = "[MySection]"; //we support sections with same name
while(sSec)//while we have a valid sNextSec
{
//print values of the sections
char* next=0;//in case we dont have any sucessful grabs
if(GrabIniValue(sSec,secName,"MyValue1",str,sizeof(str),&next)) { printf("MyValue1 = [%s]\n",str); }
if(GrabIniValue(sSec,secName,"MyValue2",str,sizeof(str),0)) { printf("MyValue2 = [%s]\n",str); }
if(GrabIniValue(sSec,secName,"MyValue3",str,sizeof(str),0)) { printf("MyValue3 = [%s]\n",str); }
printf("\n");
sSec = next; //parse next section, next will be null if no more sections to parse
}
HDFS getmerge small file and spilt into property size.
This method will cause line break
split -b 125m compact.file -d -a 3 compact_prefix
I try to getmerge and split into about 128MB every file.
# split into 128m ,judge sizeunit is M or G ,please test before use.
begainsize=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $1}' `
sizeunit=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $2}' `
if [ $sizeunit = "G" ];then
res=$(printf "%.f" `echo "scale=5;$begainsize*8 "|bc`)
else
res=$(printf "%.f" `echo "scale=5;$begainsize/128 "|bc`) # celling ref http://blog.csdn.net/naiveloafer/article/details/8783518
fi
echo $res
# split into $res files with number suffix. ref http://blog.csdn.net/microzone/article/details/52839598
compact_file_name=$compact_file"_"
echo "compact_file_name :"$compact_file_name
split -n l/$res $basedir/$compact_file -d -a 3 $basedir/${compact_file_name}
Sometimes value stored in Database could contain spaces so running this could be fail
String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)
Solution to this problems is to remove space then convert its case then select like this
return db.UsersTBs.Where(x => x.title.ToString().ToLower().Replace(" ",string.Empty).Equals(customname.ToLower())).FirstOrDefault();
Note in this case
customname is value to match with Database value
UsersTBs is class
title is the Database column
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
Disable Windows Defender Service. Turning this off immediately caused all of my unit tests to show up in Test Explorer.
They both represent floating point numbers. A FLOAT
is for single-precision, while a DOUBLE
is for double-precision numbers.
MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
There is a big difference from floating point numbers and decimal (numeric) numbers, which you can use with the DECIMAL
data type. This is used to store exact numeric data values, unlike floating point numbers, where it is important to preserve exact precision, for example with monetary data.
You can achieve that using DATE_FORMAT() (click the link for more other formats)
SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY,
DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY
Apologies for not using your exact SQL
I used this query to overcome the Mysql warning.
SELECT count(*) AS cnt, `regions_id`
FROM regionables
WHERE `regionable_id` = '115' OR `regionable_id` = '714'
GROUP BY `regions_id`
HAVING cnt > 1
note the key for me being
count(*) AS cnt
SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.
However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.
Note: this is more or less a rework of the No. 2 of @oleksii's answer.
This works for .exe and .dll projects:
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
<TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
</Target>
This works for web projects:
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
<TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>
Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).
Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.
This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:
<Project>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
<TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
<TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>
You can't delete an File
array. As all of the other answers suggest, you must delete each individual file before deleting the folder...
final File[] files = outputFolder.listFiles();
for (File f: files) f.delete();
outputFolder.delete();
For ubuntu 16.04, there is firewall issue. You need to open 8080 port using following command:
sudo ufw allow 8080
Detailed steps are given here: https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-16-04
Sounds like you need to install the devel package for zlib, probably want to do something like sudo apt-get install zlib1g-dev
(I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, and configure
, make
, make install
. You'll want to at least set --prefix
to somewhere, so it'll get installed where you want.
./configure --prefix=/opt/python2.7 + other options
make
make install
You can check what configuration options are available with ./configure --help
and see what your system python was compiled with by doing:
python -c "import sysconfig; print sysconfig.get_config_var('CONFIG_ARGS')"
The key is to make sure you have the development packages installed for your system, so that Python will be able to build the zlib
, sqlite3
, etc modules. The python docs cover the build process in more detail: http://docs.python.org/using/unix.html#building-python.
Use btn-block
class on your button/element
Use input-block-level
class on your button/element
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
you can pass multiple params in url like
http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc
and in order to get this query fields , you can use map like
@RequestMapping(method = RequestMethod.GET, value = "/custom")
public String controllerMethod(@RequestParam Map<String, String> customQuery) {
System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
System.out.println("customQuery = price " + customQuery.containsKey("price"));
System.out.println("customQuery = other " + customQuery.containsKey("other"));
System.out.println("customQuery = sort " + customQuery.containsKey("sort"));
return customQuery.toString();
}
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
cmd /c pause | out-null
(It is not the PowerShell way, but it's so much more elegant.)
Save trees. Use one-liners.
On Python 3.4, the pathlib
module was added, and the following code will reliably open a file in the same directory as the current script:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
print(f.read())
You can also use parent.absolute()
to get directory value as a string if needed:
p = Path(__file__)
dir_abs = p.parent.absolute() # Will return the executable directory absolute path
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
Why don't you examine System.getProperty("os.arch")
value in your code?
Stating your time as HH
will give you 24h format, and hh
will give 12h format.
You can also find it here in the documentation :
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
The stream editor does modify multiple files “inplace” when invoked with the -i
switch, which takes a backup file ending as argument. So
sed -i.bak 's/foo/bar/g' *
replaces foo
with bar
in all files in this folder, but does not descend into subfolders. This will however generate a new .bak
file for every file in your directory.
To do this recursively for all files in this directory and all its subdirectories, you need a helper, like find
, to traverse the directory tree.
find ./ -print0 | xargs -0 sed -i.bak 's/foo/bar/g' *
find
allows you further restrictions on what files to modify, by specifying further arguments like find ./ -name '*.php' -or -name '*.html' -print0
, if necessary.
Note: GNU sed
does not require a file ending, sed -i 's/foo/bar/g' *
will work, as well; FreeBSD sed
demands an extension, but allows a space in between, so sed -i .bak s/foo/bar/g *
works.
I don't really see a way to do this as-is. I think you might need to remove the overflow:hidden
from div#1 and add another div within div#1 (ie as a sibling to div#2) to hold your unspecified 'content' and add the overflow:hidden
to that instead. I don't think that overflow can be (or should be able to be) over-ridden.
The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.
When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:
SET AND=IF
IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.
When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:
SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B
These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:
IF EXIST "somefile.txt" %THEN%
IF EXIST "someotherfile.txt" %THEN%
SET var="somefile.txt,someotherfile.txt"
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
IF EXIST "%~1" %THEN%
SET "result=%~1"
%ELSE%
SET "result="
%ENDIF%
I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.
The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.
It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>
Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.
select * from
(
select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
order by t1.ReceivedDate de
) t1
union
select * from
(
select top 2 t2.ID
from Table t2
where t2.Type = 'TYPE_2'
order by t2.ReceivedDate desc
) t2
or using CTE (SQL Server 2005+)
;with One as
(
select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
order by t1.ReceivedDate de
)
,Two as
(
select top 2 t2.ID
from Table t2
where t2.Type = 'TYPE_2'
order by t2.ReceivedDate desc
)
select * from One
union
select * from Two
Here is the perfect coding which checks whether the Combo Box Item is Selected or not
if (string.IsNullOrEmpty(comboBox1.Text))
{
MessageBox.Show("No Item is Selected");
}
else
{
MessageBox.Show("Item Selected is:" + comboBox1.Text);
}
No. Python's iterator protocol is very simple, and only provides one single method (.next()
or __next__()
), and no method to reset an iterator in general.
The common pattern is to instead create a new iterator using the same procedure again.
If you want to "save off" an iterator so that you can go back to its beginning, you may also fork the iterator by using itertools.tee
In Style.xml pre-define the style:
<style name="largeText">
<item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
<item name="android:textStyle">bold</item>
</style>
in code:
text.setTextAppearance(context, R.style.largeText);
You can try one of the following:
Method 1:
MyProject
go build
./MyProject
You can do both steps at once by typing go build && ./MyProject
. Go files of the package main
are compiled to an executable.
Method 2:
go run *.go
. It won't create any executable but it runs.Classes
Structs
Interfaces
Events
Properties
Delegates
Expressions
Statements
Attributes
Literals
Dispose in foreach
foreach over string specialization
C# 2 - Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Getter/setter separate accessibility
Method group conversions (delegates)
Static classes
Delegate inference
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expression
Expression trees
Partial methods
Dynamic binding
Named and optional arguments
Co- and Contra-variance for generic delegates and interfaces
Embedded interop types ("NoPIA")
Asynchronous methods
Caller info attributes
Draft Specification online
Compiler-as-a-service (Roslyn)
Import of static type members into namespace
Exception filters
Await in catch/finally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator (null-conditional operator, succinct null checking)
String interpolation
nameof operator
Dictionary initializer
Out variables
Pattern matching
Tuples
Deconstruction
Discards
Local Functions
Binary Literals
Digit Separators
Ref returns and locals
Generalized async return types
More expression-bodied members
Throw expressions
Async main
Default expressions
Reference assemblies
Inferred tuple element names
Pattern-matching with generics
Span and ref-like types
In parameters and readonly references
Ref conditional
Non-trailing named arguments
Private protected accessibility
Digit separator after base specifier
System.Enum, System.Delegate and unmanaged constraints.
Ref local re-assignment: Ref locals and ref parameters can now be reassigned with the ref assignment operator (= ref).
Stackalloc initializers: Stack-allocated arrays can now be initialized, e.g. Span<int> x = stackalloc[] { 1, 2, 3 };.
Indexing movable fixed buffers: Fixed buffers can be indexed into without first being pinned.
Custom fixed statement: Types that implement a suitable GetPinnableReference can be used in a fixed statement.
Improved overload candidates: Some overload resolution candidates can be ruled out early, thus reducing ambiguities.
Expression variables in initializers and queries: Expression variables like out var and pattern variables are allowed in field initializers, constructor initializers and LINQ queries.
Tuple comparison: Tuples can now be compared with == and !=.
Attributes on backing fields: Allows [field: …] attributes on an auto-implemented property to target its backing field.
Nullable reference types: express nullability intent on reference types with ?, notnull constraint and annotations attributes in APIs, the compiler will use those to try and detect possible null values being dereferenced or passed to unsuitable APIs.
Default interface members: interfaces can now have members with default implementations, as well as static/private/protected/internal members except for state (ie. no fields).
Recursive patterns: positional and property patterns allow testing deeper into an object, and switch expressions allow for testing multiple patterns and producing corresponding results in a compact fashion.
Async streams: await foreach and await using allow for asynchronous enumeration and disposal of IAsyncEnumerable<T> collections and IAsyncDisposable resources, and async-iterator methods allow convenient implementation of such asynchronous streams.
Enhanced using: a using declaration is added with an implicit scope and using statements and declarations allow disposal of ref structs using a pattern.
Ranges and indexes: the i..j syntax allows constructing System.Range instances, the ^k syntax allows constructing System.Index instances, and those can be used to index/slice collections.
Null-coalescing assignment: ??= allows conditionally assigning when the value is null.
Static local functions: local functions modified with static cannot capture this or local variables, and local function parameters now shadow locals in parent scopes.
Unmanaged generic structs: generic struct types that only have unmanaged fields are now considered unmanaged (ie. they satisfy the unmanaged constraint).
Readonly members: individual members can now be marked as readonly to indicate and enforce that they do not modify instance state.
Stackalloc in nested contexts: stackalloc expressions are now allowed in more expression contexts.
Alternative interpolated verbatim strings: @$"..." strings are recognized as interpolated verbatim strings just like $@"...".
Obsolete on property accessors: property accessors can now be individually marked as obsolete.
Permit t is null on unconstrained type parameter
[source] : https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md
autoscroll
will be defined and modified in the controller:
<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>
Add multiple classes based on condition by:
<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>
if you want to access a method :
1) while using an object of a class:
Myclass myclass;
myclass.DoSomething();
2) while using a pointer to an object of a class:
Myclass *myclass=&abc;
myclass->DoSomething();
This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
jquery makes it easier:
$(document).on('click','#btnPrepend',function(){//do something})
Here is an article about event delegation event delegation article
dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.
When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.
one of the good example:
SELECT *
FROM table1 tb1
LEFT JOIN (
SELECT *
FROM dblink('dbname=db2','SELECT id, code FROM table2')
AS tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;
Note: I am giving this information for future reference. Refrence
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
You are missing a closing h2 tag. It should be:
<h2><!-- Content --></h2>