Setting 'clang' as the compiler configure should use worked for me:
export CC=clang
pip install --no-clean pycrypto
A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access).
The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.
Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.
If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.
I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded
using System.Threading;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
I know this is late, but this is how I normally do it,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");
Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).
In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".
There are mainly two possible ways to achieve this:
Serialize the data in some way:
$postvalue = serialize($array); // Client side
$array = unserialize($_POST['result']; // Server side
And then you can unserialize the posted values with unserialize($postvalue)
. Further information on this is here in the PHP manuals.
Alternativeley you can use the json_encode()
and json_decode()
functions to get a JSON formatted serialized string. You could even shrink the transmitted data with gzcompress()
(note that this is performance intensive) and secure the transmitted data with base64_encode()
(to make your data survive in non-8 bit clean transport layers) This could look like this:
$postvalue = base64_encode(json_encode($array)); // Client side
$array = json_decode(base64_decode($_POST['result'])); // Server side
A not recommended way to serialize your data (but very cheap in performance) is to simply use implode()
on your array to get a string with all values separated by some specified character. On the server side you can retrieve the array with explode()
then. But note that you shouldn't use a character for separation that occurs in the array values (or then escape it) and that you cannot transmit the array keys with this method.
Use the properties of special named input elements:
$postvalue = "";
foreach ($array as $v) {
$postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
}
Like this you get your entire array in the $_POST['result']
variable if the form is sent. Note that this doesn't transmit array keys. However you can achieve this by using result[$key]
as name of each field.
Everyone of these methods got their own advantages and disadvantages. What you use is mainly depending on how large your array will be, since you should try to send a minimal amount of data with all of this methods.
Another way to achieve the same is to store the array in a server side session instead of transmitting it client side. Like this you can access the array over the $_SESSION
variable and don't have to transmit anything over the form. For this have a look at a basic usage example of sessions on php.net.
if you are using event.preventDefault() in your script then comment it out because IE doesn't likes it.
UPDATE 2020 => Reset Entity-Framework Migrations
Add-Migration Initial -Context ApplicationDbContext
ApplicationDbContext => Your context.
But if you need only update a identity schema existent, try it: https://stackoverflow.com/a/59966100/4654957
This what you need to do.
@Url.Action(action,controller, null, Request.Url.Scheme)
The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether. Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
For Using the session id in all the activities you can follow the following steps.
1-Define one STATIC VARIABLE session( which will hold the value of session id ) in the APPLICATION file of your app.
2-Now call the session variable with the class reference where you are fetching the session id value and assign it to static variable.
3-Now you can use this session id value anywhere by just calling the static variable by the
I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.
Here's the SSCCE:
import java.util.*;
import java.lang.management.ManagementFactory;
class main {
public static void main(final String[] args) {
System.out.println(fullVMArguments());
}
static String fullVMArguments() {
String name = javaVmName();
return (contains(name, "Server") ? "-server "
: contains(name, "Client") ? "-client " : "")
+ joinWithSpace(vmArguments());
}
static List<String> vmArguments() {
return ManagementFactory.getRuntimeMXBean().getInputArguments();
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static String javaVmName() {
return System.getProperty("java.vm.name");
}
static String joinWithSpace(Collection<String> c) {
return join(" ", c);
}
public static String join(String glue, Iterable<String> strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator<String> i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
}
Could be made shorter if you want the arguments in a List<String>
.
Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.
According to this post
You need to add the !important
css modifier to your height percentages.
Hope this helps.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
The show command may be what you want. Try
git show -s --format=%ci <commit>
Other formats for the date string are available as well. Check the manual page for details.
You can try using POSTMAN Chrome app for your request and you can generate node js code from there
You can use two methods for raising exception in the try catch block
@throw[NSException exceptionWithName];
or the second method
NSException e;
[e raise];
You can access any LayoutParams
from code using View.getLayoutParams
. You just have to be very aware of what LayoutParams
your accessing. This is normally achieved by checking the containing ViewGroup
if it has a LayoutParams
inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams
. You'll be using RelativeLayout.LayoutParams#addRule(int verb)
and RelativeLayout.LayoutParams#addRule(int verb, int anchor)
You can get to it via code:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update
issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).
Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.
Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.
...
:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice
:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done
:doonotsyncthefiles
echo Backup Complete!
...
You can have as many as you need of these blocks.
You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)
Explanation:
if ( str[4] === 'r' )
Check if the 5th character is a 'r'
str.slice(0, 4)
Slice the string to get everything before the 'r'
+ str.slice(5)
Add the rest of the string.
Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s
[37 bytes!]
DEMO:
function remove5thR (s) {_x000D_
s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;_x000D_
console.log(s); // log output_x000D_
}_x000D_
_x000D_
remove5thR('crt/r2002_2') // > 'crt/2002_2'_x000D_
remove5thR('crt|r2002_2') // > 'crt|2002_2'_x000D_
remove5thR('rrrrr') // > 'rrrr'_x000D_
remove5thR('RRRRR') // > 'RRRRR' (no change)
_x000D_
Here's another idea. Use SSH to do the port forwarding; this has the benefit of also working in OS X (and probably Windows) when your Docker host is a VM.
docker exec -it <containterid> ssh -R5432:localhost:5432 <user>@<hostip>
An easy approach is to leverage this code:
<a href="javascript:void(0);">Link Title</a>
This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.
For these reasons, the above solution is better than:
<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>
where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.
Here's my 2 cents:
import sys
sys.path.append('/Users/John/Desktop')
import mapping #mapping.py is the name of my module file
shipit = mapping.Shipment() #Shipment is the name of the class I need to use in the mapping module
from mapping import Mapping
shipit = Shipment() #Now you don't have to use the .notation
Try using
$("#mydialog").closest(".ui-dialog-titlebar").hide();
This will hide all dialogs titles
$(".ui-dialog-titlebar").hide();
None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...
String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string
str = str + '\r' + '\n'; // Add the required carriage return, optional line feed
byte str_len = str.length();
// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...
byte arrayPointer = 0;
while (str_len)
{
// I was outputting the digits to the TX buffer
if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
{
UDR0 = str[arrayPointer];
--str_len;
++arrayPointer;
}
}
sed 's/^.\{,5\}//' file.dat
this would help.. from google apis demos
private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
.title(title));
markerList.add(marker);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView!=null) {
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation") // We use the new method when supported
@SuppressLint("NewApi") // We check which build version we are using.
@Override
public void onGlobalLayout() {
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (Marker m : markerList) {
b.include(m.getPosition());
}
// also include current location to include in the view
b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));
LatLngBounds bounds = b.build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
for clear info look at this url. https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
This works for me:
First you need to create method, which will be returns your headers you want to add to request:
private Map<String, String> getCustomHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("YOURHEADER", "VALUE");
return headers;
}
Second you need to create WebViewClient:
private WebViewClient getWebViewClient()
{
return new WebViewClient()
{
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
view.loadUrl(request.getUrl().toString(), getCustomHeaders());
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url, getCustomHeaders());
return true;
}
};
}
Add WebViewClient to your WebView:
webView.setWebViewClient(getWebViewClient());
Hope this helps.
In a Spring Boot 2 application you can either exclude the service configuration from autoconfiguration:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
or if you just want to hide the message in the logs you can simply change the log level:
logging.level.org.springframework.boot.autoconfigure.security=WARN
Further information can be found here: https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-security.html
Or, you can use the Newtownsoft.Json library as follows:
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
Where T
is your object type that matches your JSON string.
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
You can use it
$params = request()->all();
without
import Illuminate\Http\Request
OR
use Illuminate\Support\Facades\Request
OR other.
A status of Private indicates that variables can only be accessed by objects of the same class. Protected status extends that access to include descendants of the class as well.
"from the above table we can see the deference between private and protected... am think both are same ....so what the need for that two separate command"
Check MSDN link for more information
One liner:
total_line_count = sum(1 for line in open("filename.txt"))
print(total_line_count)
Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.
More information: http://php.net/manual/en/language.operators.errorcontrol.php
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
@fsockopen();
As per bash - The Set Builtin manual, if -e
/errexit
is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.
By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail
option is enabled (it's disabled by default).
If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.
If you'd like to execute something on exit, try defining trap
, for example:
trap onexit EXIT
where onexit
is your function to do something on exit, like below which is printing the simple stack trace:
onexit(){ while caller $((n++)); do :; done; }
There is similar option -E
/errtrace
which would trap on ERR instead, e.g.:
trap onerr ERR
Zero status example:
$ true; echo $?
0
Non-zero status example:
$ false; echo $?
1
Negating status examples:
$ ! false; echo $?
0
$ false || true; echo $?
0
Test with pipefail
being disabled:
$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1
Test with pipefail
being enabled:
$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1
You can use gmtime
from time import gmtime
detailed_time = gmtime()
#returns a struct_time object for current time
year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min
Note: A time stamp can be passed to gmtime, default is current time as returned by time()
eg.
gmtime(1521174681)
See struct_time
If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):
if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi
Have a nice day
When explicitly dealing with a ByteArrayInputStream
then contrary to some of the comments on this page you can use the .available()
function to get the size. Just have to do it before you start reading from it.
From the JavaDocs:
Returns the number of remaining bytes that can be read (or skipped over) from this input stream. The value returned is count - pos, which is the number of bytes remaining to be read from the input buffer.
https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()
You could use :before
and content:
bearing in mind that this is not supported in IE 7 or below. If you're OK with that then this is your best solution. See the Can I Use or QuirksMode CSS compatibility tables for full details.
A slightly nastier solution that should work in older browsers is to use an image for the bullet point and just make the image look like a dash. See the W3C list-style-image
page for examples.
After years having the same issue and no permanent solution this is whats solved it for the past 3 weeks (which is a record in terms of error free operation)
set global wait_timeout=3600;
set global interactive_timeout=230400;
Don't forget to make this permanent if it works for you.
To add to the other answers, most array list implementations reserve extra capacity at the end of the list so that new elements can be added to the end of the list in O(1) time. When the capacity of an array list is exceeded, a new, larger array is allocated internally, and all the old elements are copied over. Usually, the new array is double the size of the old one. This means that on average, adding new elements to the end of an array list is an O(1) operation in these implementations. So even if you don't know the number of elements in advance, an array list may still be faster than a linked list for adding elements, as long as you are adding them at the end. Obviously, inserting new elements at arbitrary locations in an array list is still an O(n) operation.
Accessing elements in an array list is also faster than a linked list, even if the accesses are sequential. This is because array elements are stored in contiguous memory and can be cached easily. Linked list nodes can potentially be scattered over many different pages.
I would recommend only using a linked list if you know that you're going to be inserting or deleting items at arbitrary locations. Array lists will be faster for pretty much everything else.
You can follow the instruction mentioned on the official page to fix this issue. This issue occur on real device because the JS bundle is located on your development system and the app inside your real device is not aware of it's location.
Basically, when your FROM clause lists tables like so:
SELECT * FROM
tableA, tableB, tableC
the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id
which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id
and you should then get only those rows you are really interested in.
DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like
tableA.id = tableB.a_id
AND tableB.id = tableC.b_id
which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.
When remoted into a machine (target is Windows XP anyway; I am not sure about target Windows Vista), although Shutdown on the start menu is replaced by Disconnect Session or something like that, there should be one called 'Windows Security' which also does the same thing as Ctrl + Alt + End as pointed to by Owen.
Use boolalpha
to print bool to string.
std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
Use something like this in case you also want to output products details per date as JSON and the MySQL
version does not support JSON
functions.
SELECT `date`,
CONCAT('{',GROUP_CONCAT('{\"id\": \"',`product_id`,'\",\"name\": \"',`product_name`,'\"}'),'}') as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC
product_id product_name date
| 1 | azd | 2011-12-12 |
| 2 | xyz | 2011-12-12 |
| 3 | ase | 2011-12-11 |
| 4 | azwed | 2011-12-11 |
| 5 | wed | 2011-12-10 |
| 6 | cvg | 2011-12-10 |
| 7 | cvig | 2011-12-09 |
RESULT
date productsJSON
2011-12-12T00:00:00Z {{"id": "1","name": "azd"},{"id": "2","name": "xyz"}}
2011-12-11T00:00:00Z {{"id": "3","name": "ase"},{"id": "4","name": "azwed"}}
2011-12-10T00:00:00Z {{"id": "5","name": "wed"},{"id": "6","name": "cvg"}}
2011-12-09T00:00:00Z {{"id": "7","name": "cvig"}}
Try it out in SQL Fiddle
If you are using a MySQL
version that supports JSON
functions then the above query could be re-written:
SELECT `date`,JSON_OBJECTAGG(CONCAT('product-',`product_id`),JSON_OBJECT('id', `product_id`, 'name', `product_name`)) as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC;
Try both in DB Fiddle
In PhoneGap 3.4.0 you can call:
cordova build android --release
If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:
key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp
Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.
A general answer
select * from [dbo].[SplitString]('1,2',',') -- Will work
but
select [dbo].[SplitString]('1,2',',') -- will not work and throws this error
This is my solution. I Hide and then confirm check
onclick="return ConfirmSubmit(this);" />
function ConfirmSubmit(sender)
{
sender.disabled = true;
var displayValue = sender.style.
sender.style.display = 'none'
if (confirm('Seguro que desea entregar los paquetes?')) {
sender.disabled = false
return true;
}
sender.disabled = false;
sender.style.display = displayValue;
return false;
}
Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.
Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:
$ uname -a
armv7l
Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.
You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.
You can follow the GitHub issue for 64-bit support here, if you're interested.
For other readers, the error can come from the fact that there is no brackets wrapping the async function:
Considering the async function initData
async function initData() {
}
This code will lead to your error:
useEffect(() => initData(), []);
But this one, won't:
useEffect(() => { initData(); }, []);
(Notice the brackets around initData()
Following @JanKlimo example, on terminal all you have to do is:
to see all the Index:
$ curl -XGET 'http://127.0.0.1:9200/_cat/indices?v'
to see content of Index products_development_20160517164519304
:
$ curl -XGET 'http://127.0.0.1:9200/products_development_20160517164519304/_search?pretty=1'
I know you are specifically asking about the PHP timeout, but what no one else seems to have mentioned is that there can also be a timeout on the webserver and it can look very similar to the PHP timeout.
So if you have tried:
And you have checked with the phpinfo() function that max_execution_time has indeed be increased, then you might want to try adding this to .htaccess which will make sure Apache itself does not time out:
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]
More info here: https://www.antropy.co.uk/blog/php-script-keeps-timing-out-despite-ini-set/
Definitely avoid using eval
to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.
For example, if you were to use the eval
solutions proposed here, a nefarious user could send a link to their victim that looked like this:
http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}
And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.
So, make sure you never eval
untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:
// set up the possible functions:
var myFuncs = {
func1: function () { alert('Function 1'); },
func2: function () { alert('Function 2'); },
func3: function () { alert('Function 3'); },
func4: function () { alert('Function 4'); },
func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();
This will fail if the funcToRun
variable doesn't point to anything in the myFuncs
object, but it won't execute any code.
elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");
is equal
elem.classList.add("first","second","third");
Try Flowing codes on Spring project
ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();
Or on non spring project
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
InputStream inputStream = new FileInputStream(file);
In management studio:
Properties
, then Options
.Tasks
-> Shrink
-> Files
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
If you are catching a browser back/forward button and don't want to navigate away, you can use:
window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});
Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.
You'll want to install the sshpass program. Then:
sshpass -p YOUR_PASSWORD sftp -oBatchMode=no -b YOUR_COMMAND_FILE_PATH USER@HOST
Obviously, it's better to setup public key authentication. Only use this if that's impossible to do, for whatever reason.
Another use for bootstrap.yml is to load configuration from kubernetes configmap and secret resources. The application must import the spring-cloud-starter-kubernetes dependency.
As with the Spring Cloud Config, this has to take place during the bootstrap phrase.
From the docs :
spring:
application:
name: cloud-k8s-app
cloud:
kubernetes:
config:
name: default-name
namespace: default-namespace
sources:
# Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace
- name: c1
So properties stored in the configmap resource with meta.name default-name can be referenced just the same as properties in application.yml
And the same process applies to secrets :
spring:
application:
name: cloud-k8s-app
cloud:
kubernetes:
secrets:
name: default-name
namespace: default-namespace
sources:
# Spring Cloud Kubernetes looks up a Secret named s1 in namespace default-namespace
- name: s1
I tried to optimize solution by handling user input exceptions.
public class Solution {
private static Integer TERMINATION_VALUE = 0;
public static void main(String[] args) {
Integer value = null;
Integer minimum = Integer.MAX_VALUE;
Integer maximum = Integer.MIN_VALUE;
Scanner scanner = new Scanner(System.in);
while (value != TERMINATION_VALUE) {
Boolean inputValid = Boolean.TRUE;
try {
System.out.print("Enter a value: ");
value = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Value must be greater or equal to " + Integer.MIN_VALUE + " and less or equals to " + Integer.MAX_VALUE );
inputValid = Boolean.FALSE;
scanner.next();
}
if(Boolean.TRUE.equals(inputValid)){
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
}
if(TERMINATION_VALUE.equals(minimum) || TERMINATION_VALUE.equals(maximum)){
System.out.println("There is not any valid input.");
} else{
System.out.println("Minimum: " + minimum);
System.out.println("Maximum: " + maximum);
}
scanner.close();
}
}
Use [NSIndexPath indexPathForRow:inSection:]
to quickly create an index path.
Edit: In Swift 3:
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
Swift 5
IndexPath(row: 0, section: 0)
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.
Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.
Just a thought.
A simple solution is to use writeFile :
require("fs").writeFile(
somepath,
arr.map(function(v){ return v.join(', ') }).join('\n'),
function (err) { console.log(err ? 'Error :'+err : 'ok') }
);
By default ListView is scrollable. Do not put ScrollView to the ListView
Windows Solution
Windows-Key + R
putty.exe -ssh [username]@[hostname] -pw [password]
you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.
To configure bash aliases, it's the same as if you were on a Unix platform: put them in a .bashrc
in your home:
cd
echo alias ll=\'ls -l\' >> .bashrc
To have this change taken into account you should then either source this file (ie: run source .bashrc
) or restart your terminal
(In some cases* you can find equivalent for .bashrc
file in C:\Users\<username>\AppData\Local\GitHub\PortableGit_\etc\profile.d\aliases.sh.
And you should add aliases in aliases.sh.
)
(*this case is when you install Git for Windows GUI release from https://git-scm.com/download/win that contains GitBash)
After fiddling around with @journois's answer, I was able to get it to work using MultiIndex instead of Panel due to Panel's deprication.
First, create some dummy data:
df1 = pd.DataFrame({
'id': ['111', '222', '333', '444', '555'],
'let': ['a', 'b', 'c', 'd', 'e'],
'num': ['1', '2', '3', '4', '5']
})
df2 = pd.DataFrame({
'id': ['111', '222', '333', '444', '666'],
'let': ['a', 'b', 'c', 'D', 'f'],
'num': ['1', '2', 'Three', '4', '6'],
})
Then, define your diff function, in this case I'll use the one from his answer report_diff
stays the same:
def report_diff(x):
return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
Then, I'm going to concatenate the data into a MultiIndex dataframe:
df_all = pd.concat(
[df1.set_index('id'), df2.set_index('id')],
axis='columns',
keys=['df1', 'df2'],
join='outer'
)
df_all = df_all.swaplevel(axis='columns')[df1.columns[1:]]
And finally I'm going to apply the report_diff
down each column group:
df_final.groupby(level=0, axis=1).apply(lambda frame: frame.apply(report_diff, axis=1))
This outputs:
let num
111 a 1
222 b 2
333 c 3 | Three
444 d | D 4
555 e | nan 5 | nan
666 nan | f nan | 6
And that is all!
I found a much better way of doing the same, less code, much more efficient. Note that the """" is to quote the path in case it contains blanks in a folder name. Command line mkdir creates any intermediary folder if necessary to make the whole path exist.
If Dir(YourPath, vbDirectory) = "" Then
Shell ("cmd /c mkdir """ & YourPath & """")
End If
Here's a good way to think about the difference between value-types, passing-by-value, reference-types, and passing-by-reference:
A variable is a container.
A value-type variable contains an instance. A reference-type variable contains a pointer to an instance stored elsewhere.
Modifying a value-type variable mutates the instance that it contains. Modifying a reference-type variable mutates the instance that it points to.
Separate reference-type variables can point to the same instance. Therefore, the same instance can be mutated via any variable that points to it.
A passed-by-value argument is a new container with a new copy of the content. A passed-by-reference argument is the original container with its original content.
When a value-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument has no effect outside scope, because the instance is an independent copy.
When a reference-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument's content affects the external scope, because the copied pointer points to a shared instance.
When any argument is passed-by-reference: Reassigning the argument's content affects the external scope, because the container is shared. Modifying the argument's content affects the external scope, because the content is shared.
In conclusion:
A string variable is a reference-type variable. Therefore, it contains a pointer to an instance stored elsewhere. When passed-by-value, its pointer is copied, so modifying a string argument should affect the shared instance. However, a string instance has no mutable properties, so a string argument cannot be modified anyway. When passed-by-reference, the pointer's container is shared, so reassignment will still affect the external scope.
SELECT
DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo
If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.
It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.
The output of this example will be
[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]
Example: 5.August.2015
Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.
This might be useful https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
Basically it sounds like they act as OR
I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.
My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.
One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.
Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:
[CmdletBinding(PositionalBinding = $False)]
param
(
[Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
[Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
[Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)
This is how I would call this script from another script:
$params = @{
MyNamedParameter1 = $SomeValue
MyNamedParameter2 = $SomeOtherValue
}
If ($SomeCondition)
{
$params['MyNamedParameter3'] = $YetAnotherValue
}
$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1
$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
$args
} @params)")
Invoke-Command -ScriptBlock $sb
I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.
e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules
which contains a space character.
$params = @{
SourcePath = "$WorkingDirectory\Modules"
DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
}
Hope this helps!
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub
console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.
It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.
To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.
Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.
Solution suggested in the comments of the PHP manual entry for file_get_contents
function file_get_contents_utf8($fn) {
$content = file_get_contents($fn);
return mb_convert_encoding($content, 'UTF-8',
mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
You might also try your luck with http://php.net/manual/en/function.mb-internal-encoding.php
Well, If you want to update a node in XML, the XmlDocument
is fine - you needn't use XmlTextWriter
.
XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
Try with this code -
It is a totally dynamic solution:
var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");
var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
$(form).append($(input));
$(form).submit();
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except ValueError: # includes simplejson.decoder.JSONDecodeError
print 'Decoding JSON has failed'
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
You can run Postgres this way (map a port):
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port>
.So now your postgres is accessible from your public-server-ip:5432
To test: Run the postgres database (command above)
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05b3a3471f6f postgres "/docker-entrypoint.s" 1 seconds ago Up 1 seconds 0.0.0.0:5432->5432/tcp some-postgres
Go inside your container and create a database:
docker exec -it 05b3a3471f6f bash
root@05b3a3471f6f:/# psql -U postgres
postgres-# CREATE DATABASE mytest;
postgres-# \q
Go to your localhost (where you have some tool or the psql client).
psql -h public-ip-server -p 5432 -U postgres
(password mysecretpassword)
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
mytest | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres
So you're accessing the database (which is running in docker on a server) from your localhost.
In this post it's expained in detail.
I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.
This answer deals with your question but is not exactly an answer to it. =) It's an interesting library I found out recently and I want to share with you.
Project Lombok can generate common methods, such as getters, setters, equals()
and hashCode()
, toString()
, for your classes automatically. It replaces them with annotations reducing boilerplate code. To see a good example of code written using Lombok watch a video on the main page or read this article.
Android development with Lombok is easy and won't make your android application any 'heavier' because Lombok is a compile-time only library. It is important to configure your Android project properly.
Another example:
import lombok.Getter;
import lombok.Setter;
public class Profile {
@Getter @Setter
private String username;
@Getter @Setter
private String password;
}
Android development with Lombok is possible. Lombok should be a compile-time only dependency, as otherwise the entirety of Lombok will end up in your DEX files, wasting precious space. Gradle snippet:
dependencies {
compileOnly "org.projectlombok:lombok:1.16.18"
}
In addition you may want to add the Lombok IntelliJ plugin to support Lombok features in your IDE at development time. Also there is Hrisey library which is based on Lombok. Simply put, it's Lombok + Parcellable support.
SELECT DATENAME(DW,CONVERT(VARCHAR(20),GETDATE(),101))
It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get
will have to iterate over them calling equals
on each of them to find a match.
In the worst case, a HashMap
has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use.
In JDK 8, HashMap
has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course.
And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use.
var valArr = [101,102], // array of option values
i = 0, size = valArr.length, // index and array size declared here to avoid overhead
$options = $('#data option'); // options cached here to avoid overhead of fetching inside loop
// run the loop only for the given values
for(i; i < size; i++){
// filter the options with the specific value and select them
$options.filter('[value="'+valArr[i]+'"]').prop('selected', true);
}
If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31.
DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);
var RequestIds = rdc.request
.Where(r => lastMonth <= r.dteCreated)
.Where(r => r.dteCreated < thisMonth)
.Select(r => r.intRequestId);
As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.
df[cat]=df[cat].astype('category')
And then check df.dtypes and perform label encoding.
Your suggestion would work, but using a Do loop might be a little more readable.
This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.
Dim i
For i = 0 To 10
Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False
Next
As crush suggests, it looks a little better if you remove the extra indentation level.
Dim i
For i = 0 To 10: Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False: Next
Things has been a little bit changed due to the latest updates on Visual Studio Code. The following steps work for me.
Press Ctrl + Shift + P to open the Visual Studio Code command palate.
Type >preferences: Open Settings (JSON)
in the text area.
Add the following lines at the end of the JSON file which is displayed in your right hand pane.
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
Close and reopen your Visual Studio Code instance.
This is how you generate the samples on a modern C++ compiler.
#include <random>
...
std::mt19937 generator;
double mean = 0.0;
double stddev = 1.0;
std::normal_distribution<double> normal(mean, stddev);
cerr << "Normal: " << normal(generator) << endl;
!foo.dll
in .gitignore, or (every time!) git add -f foo.dll
public class PrintOddEven {
private static class PrinterThread extends Thread {
private static int current = 0;
private static final Object LOCK = new Object();
private PrinterThread(String name, int number) {
this.name = name;
this.number = number;
}
@Override
public void run() {
while (true) {
synchronized (LOCK) {
try {
LOCK.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (current < number) {
System.out.println(name + ++current);
} else {
break;
}
LOCK.notifyAll();
}
}
}
int number;
String name;
}
public static void main(String[] args) {
new PrinterThread("thread1 : ", 20).start();
new PrinterThread("thread2 : ", 20).start();
}
}
Using @Jarda's guide you can define this if you need to set the variable the same value for all tests:
@Before
public void setClientMapper() throws NoSuchFieldException, SecurityException{
FieldSetter.setField(client, client.getClass().getDeclaredField("mapper"), new Mapper());
}
But beware that setting private values to be different should be handled with care. If they are private are for some reason.
Example, I use it, for example, to change the wait time of a sleep in the unit tests. In real examples I want to sleep for 10 seconds but in unit-test I'm satisfied if it's immediate. In integration tests you should test the real value.
Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.
from datetime import datetime
datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)
This will output: 0:05:00.518000
Copied over from comment by @sloth
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Example:
var viewModel = new CustomerDetailsViewModel
{
MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
};
you can make use of the following code:
from __future__ import division, unicode_literals
import codecs
from bs4 import BeautifulSoup
f=codecs.open("test.html", 'r', 'utf-8')
document= BeautifulSoup(f.read()).get_text()
print document
If you want to delete all the blank lines in between and get all the words as a string (also avoid special characters, numbers) then also include:
import nltk
from nltk.tokenize import word_tokenize
docwords=word_tokenize(document)
for line in docwords:
line = (line.rstrip())
if line:
if re.match("^[A-Za-z]*$",line):
if (line not in stop and len(line)>1):
st=st+" "+line
print st
*define st
as a string
initially, like st=""
Getting HTML code from a website. You can use code like this.
string urlAddress = "http://google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (String.IsNullOrWhiteSpace(response.CharacterSet))
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code
The full list of possible fields in the html based email-creating form:
<form action="mailto:[email protected]" method="GET">
<input name="subject" type="text" /></br>
<input name="cc" type="email" /><br />
<input name="bcc" type="email" /><br />
<textarea name="body"></textarea><br />
<input type="submit" value="Send" />
</form>
If it's similar to the window location problem at window.location.href can't be changed in tests. #890, you could try (adjusted):
delete global.window.open;
global.window = Object.create(window);
global.window.open = jest.fn();
Gosha Arinich is right, you should return your <li>
element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Each child in an array or iterator should have a unique "key" prop.
so, you need to add "key" to your list:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log()
and do a beautiful oneliner, using es6 arrow functions:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id
if id
already there, or just generate unique ids for it.
Thread.sleep()
is simple for the beginners and may be appropriate for unit tests and proofs of concept.
But please DO NOT use sleep()
for production code. Eventually sleep()
may bite you badly.
Best practice for multithreaded/multicore java applications to use the "thread wait" concept. Wait releases all the locks and monitors held by the thread, which allows other threads to acquire those monitors and proceed while your thread is sleeping peacefully.
Code below demonstrates that technique:
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
DelayUtil
implementation:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* @param durationInMillis the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* @param duration the time duration in the given {@code sourceUnit}
* @param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
Note that if you are using cMake version 3.12 or later, variable PythonInterp
and PythonLibs
has been changed into Python
.
So we use:
find_package(Python ${PY_VERSION} REQUIRED)
instead of:
find_package(PythonInterp ${PY_VERSION} REQUIRED)
find_package(PythonLibs ${PY_VERSION} REQUIRED)
see https://cmake.org/cmake/help/v3.12/module/FindPython.html for details.
In Notepad++ :
<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D
Find what: (.*)(>)(.)
Replace with: \3
Replace All
A
B
C
D
See Converting unix timestamp to excel date-time forum thread.
Play Store Rating
btn_rate_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}
});
$variable[0] != "_"
In PHP you can get particular character of a string with array index notation. $variable[0]
is the first character of a string (if $variable is a string).
Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.
If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.
alternative way:
mail -N
d *
quit
-N
Inhibits the initial display of message headers when reading mail or editing a mail folder.
d *
delete all mails
Fixed position elements are positioned relative to the browser window, so the parent element is basically irrelevant.
To get the effect you want, where the overflow
on the parent clips the child, use position: absolute
instead: http://jsfiddle.net/DBHUv/1/
In my case, simply using the uxterm
command instead of xterm
solved the problem. It's available in /opt/X11/bin/uxterm
by installing the XQuartz package provided by Apple.
lots of big companies dont even use your expiration date anymore because it causes auto-renewal of payments to be lost when cards are issued with new expiration dates and the same account number. This has been a huge problem in the service industry, so these companies have cornered the card issuers into processing payments w/o expiration dates to avoid this pitfall. Not many people know about this yet, so not all companies use this practice.
Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.
You can do this 2 ways, via js or html (easist)
$('.carousel').carousel({
interval: false,
});
That will make the auto sliding stop because there no Milliseconds added and will never slider next.
data-interval="false"
and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
becomes:
<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">
updated based on @webMan's comment
I also got this error (within the Eclipse-based STM32CubeIDE on Windows).
After double-clicking on the "multiple target patterns" error it showed a path to a .ld
file. It turns out to be another "illegal character" problem. The offending character was the (wait for it): =
Heuristic of the week: use only [a..z] in your paths, as there are bound to be other illegal characters </vomit>.
The GNU make manual doesn't explicitly document this.
A simple solution for a delayed auto submit:
<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
<form action="https://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
From the designer, you can set the onClick
property of the listItem to a method defined with a single parameter. I have an example method defined below. The method getAdapterPosition will give you the index of the selected listItem.
public void exampleOnClickMethod(View view){
myRecyclerView.getChildViewHolder(view).getAdapterPosition());
}
For information on setting up a RecyclerView, see the documentation here: https://developer.android.com/guide/topics/ui/layout/recyclerview
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
If you want to check selected option through javascript
Simplest method is add onchange attribute in that tag and define a function in js file see example if your html file has options something like this
<select onchange="subjects(this.value)">
<option>Select subject</option>
<option value="Computer science">Computer science</option>
<option value="Information Technolgy">Information Technolgy</option>
<option value="Electronic Engineering">Electronic Engineering</option>
<option value="Electrical Engineering">Electrical Engineering</option>
</select>
And now add function in js file
function subjects(str){
console.log(`selected option is ${str}`);
}
If you want to check selected option in php file
Simply give name attribute in your tag and access it php file global variables /array ($_GET or $_POST) see example if your html file is something like this
<form action="validation.php" method="POST">
Subject:<br>
<select name="subject">
<option>Select subject</option>
<option value="Computer science">Computer science</option>
<option value="Information Technolgy">Information Technolgy</option>
<option value="Electronic Engineering">Electronic Engineering</option>
<option value="Electrical Engineering">Electrical Engineering</option>
</select><br>
</form>
And in your php file validation.php you can access like this
$subject = $_POST['subject'];
echo "selected option is $subject";
You could use a .before with a content with a unicode symbol for a circle (25CF).
.circle:before {_x000D_
content: ' \25CF';_x000D_
font-size: 200px;_x000D_
}
_x000D_
<span class="circle"></span>
_x000D_
I suggest this as border-radius won't work in IE8 and below (I recognize the fact that the suggestion is a bit mental).
k-a-f's answer works for selecting one column, if selecting multiple column, we can.
DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";
SELECT id, name from table into a,b;
Then we just need to check a,b for values.
Just push to the branch that the pull request references. As long as the pull request is still open, it should get updated with any added commits automatically.
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
Why does it work in Chrome and not Firefox?
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS
requests returning a status of 401 still send the subsequent request.
Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS
request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.
How can I get the OPTIONS
request to send and respond consistently?
Simply have the server (API in this example) respond to OPTIONS
requests without requiring authentication.
Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.
Yes. Thanks
Ctrl + F11 for Portrait
and
Ctrl + F12 for Landscape
You can use the Unix-style -l
switch – typically terse and cryptic – or the equivalent --files-with-matches
– longer and more readable.
The output of grep --help
is not easy to read, but it's there:
-l, --files-with-matches print only names of FILEs containing matches
It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.
The way to handle this for anything other than kill -9
would be to register a shutdown hook. If you can use (SIGTERM) kill -15
the shutdown hook will work. (SIGINT) kill -2
DOES cause the program to gracefully exit and run the shutdown hooks.
Registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
- The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
I tried the following test program on OSX 10.6.3 and on kill -9
it did NOT run the shutdown hook, as expected. On a kill -15
it DOES run the shutdown hook every time.
public class TestShutdownHook
{
public static void main(String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
while (true)
{
Thread.sleep(1000);
}
}
}
There isn't any way to really gracefully handle a kill -9
in any program.
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.
The only real option to handle a kill -9
is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps
command looking for your program in the list and act accordingly when it disappeared.
#!/usr/bin/env bash
java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"
There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO
However it does not work quite the same as 'ON DUPLICATE UPDATE'
It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key
You can't reference the values in the old rows so you can't do an equivalent of
INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4)
ON DUPLICATE KEY UPDATE
id=1, a=2, b=3, c=c + 1;
I'd like to use the work around to get the ID to!
That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.
However as I said, if you actually use that primary key in other tables, REPLACE INTO
probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.
Someone else suggested before you can reduce some typing by doing:
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);
You can use []
to extract values from a QueryDict
object like you would any ordinary dictionary.
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]
# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]
# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]
I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):
// Create delegates for the different return types needed.
private delegate void VoidDelegate();
private delegate Boolean ReturnBooleanDelegate();
private delegate Hashtable ReturnHashtableDelegate();
// Now use the delegates and the delegate() keyword to create
// an anonymous method as required
// Here a case where there's no value returned:
public void SetTitle(string title)
{
myWindow.Invoke(new VoidDelegate(delegate()
{
myWindow.Text = title;
}));
}
// Here's an example of a value being returned
public Hashtable CurrentlyLoadedDocs()
{
return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
{
return myWindow.CurrentlyLoadedDocs;
}));
}
Have you tried Tools > Formula Auditing?
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
In my case, this error was due to the Network connection error that i was noticed in log.
If you want to make transformation your app setting from web config file to web.Release.config,you have to do the following steps. Let your web.config app setting file is this-
<appSettings>
<add key ="K1" value="Debendra Dash"/>
</appSettings>
Now here is the web.Release.config for the transformation.
<appSettings>
<add key="K1" value="value dynamicly from Realease"
xdt:Transform="SetAttributes"
xdt:Locator="Match(key)"
/>
</appSettings>
This will transform the value of K1 to the new value in realese Mode.
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
Check if it is integer parseable
public boolean isInteger(String string) {
try {
Integer.valueOf(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
or use Scanner
Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
Double doubleValue = scanner.nextDouble();
} else {
String stringValue = scanner.next();
}
}
or use Regular Expression like
private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");
public boolean isDouble(String string) {
return doublePattern.matcher(string).matches();
}
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";
$scope.toggleRightDelayed = function(){
var myInterval = $interval(function(){
$scope.toggleRight();
},1000,1)
.then(function(){
$interval.cancel(myInterval);
});
};
Please see $RANDOM
:
$RANDOM
is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. It should not be used to generate an encryption key.
Do not use findDOMNode
class MyComponent extends Component {
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
scrollToBottom() {
this.el.scrollIntoView({ behavior: 'smooth' });
}
render() {
return <div ref={el => { this.el = el; }} />
}
}
import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
const divRref = useRef(null);
useEffect(() => {
divRef.current.scrollIntoView({ behavior: 'smooth' });
});
return <div ref={divRef} />;
}
Go to %appdata%\Notepad++ folder.
The macro definitions are held in shortcuts.xml inside the <Macros>
tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.
Try this code it works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
MsgBox(CustomeDate.ToString)
con.Open()
dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)
ds = New System.Data.DataSet
dadap.Fill(ds)
Dgview.DataSource = ds.Tables(0)
con.Close()
Note : if u use dd
for date representation it will return nothing while selecting 1 to 9 so use d
for selection
'Date time format
'MMM Three-letter month.
'ddd Three-letter day of the week.
'd Day of the month.
'HH Two-digit hours on 24-hour scale.
'mm Two-digit minutes.
'yyyy Four-digit year.
The documentation contains a full list of the date formats.
Update June 2017 (from VSCode 1.14)
The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch
" command.
And PR 27405 added handling the diff3-style merge correctly.
Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers
From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.
Original answer 2016:
The Version Control doc does not mention merge commands, only merge status and conflict support.
Even the latest 1.3 June release does not bring anything new to the VCS front.
This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool
, because:
Is this feature being included in the next iteration, by any chance?
Probably not, this is a big endeavour, since a merge UI needs to be implemented.
That leaves the actual merge to be initiated from command line only.
Try to use this with single quotes in data:
insert into table test_hive values ('1','puneet');
Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6. You'll get a lot more precision.
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
double m[][]
declares an array of arrays, so called multidimensional array.
m[0]
points to an array in the size of four, containing 0*0,1*0,2*0,3*0.
Simple math shows the values are actually 0,0,0,0.
Second line is also array in the size of four, containing 0,1,2,3.
And so on...
I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.
y = pow(x, -1, p)
Maybe someone will find this useful (from wikibooks):
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
Use attr
instead.
$('#link').attr('value', 'new value');
You should use jquery validation because if you use type="number"
then you can also enter "E" character in input type, which is not correct.
Solution:
HTML
<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" >
JQuery
//integer value validation
$('input.floatNumber').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
Has anyone been able to solve this problem? I am using Jscp to scp files using public key authentication (i dont want to use password authentication). Help will be appreciated!!!
This stackoverflow entry is about the host-key checking, and there is no relation to the public key authentication.
As for the public key authentication, try the following sample with your plain(non ciphered) private key,
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n
if value is less than 10
.
In Laravel 5 simply:
$table->timestamps(); //Adds created_at and updated_at columns.
Documentation: http://laravel.com/docs/5.1/migrations#creating-columns
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
My best answer for this is to simply use format painter. This might be a bit of a pain, but it works rather well as the problem you are facing is that Gridlines are covered by fill and other effects that are layered on top. Imagine putting a piece of white paper on top of your grid, the grid lines are present underneath, but they just don't show.
So try:
From my experience this is the easiest way to do this quickly. Especially when pasting things in and out of excel.
Again this is not the programmatic way of solving this problem.
After compiling it you can jar it.
java -jar AppName.jar
http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html
In addition to the nested approach above, you can accomplish the application of theLIMIT
using JOIN
on the same table:
UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'
In my experience the mysql query optimizer is happier with this structure.
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
I succeeded by using a form control. This is my html code :
<md-input-container>
<input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
<md-error>Please enter a value between 0 and 100</md-error>
</md-input-container>
And in my Typescript code, I have :
this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])
So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.
What you're checking
if(isset($_POST['submit']))
but there's no variable name called "submit".
well i want you to understand why it doesn't works.
lets imagine if you give your submit button name delete
<input type="submit" value="Submit" name="delete" />
and check if(isset($_POST['delete']))
then it works in this code you didn't give any name to submit button and checking its exist or not with isset();
function so php didn't find any variable like "submit" so its not working now try this :
<input type="submit" name="submit" value="Submit" />
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
Try this solution:
https://serverfault.com/questions/38222/iis-7-5-windows-7-http-error-401-3-unauthorized
Also check if the user running the IIS AppPool has read access to that folder/file.
Have a look at this:
http://www.iis.net/learn/manage/configuring-security/application-pool-identities
Also have a look at this:
I got this error when loading '|' separated CSV file although there were no '"' characters in my input file. It turned out that I forgot to specify FORMAT:
COPY ... FROM ... WITH (FORMAT CSV, DELIMITER '|').
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
If table_2
is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2
already contains the itemid
values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.
You can check it out at http://craig.is/killing/mice
For the sake of really easy to read, maintainable code I share this:
function getMaxOcurrences(arr = []) {
let item = arr[0];
let ocurrencesMap = {};
for (let i in arr) {
const current = arr[i];
if (ocurrencesMap[current]) ocurrencesMap[current]++;
else ocurrencesMap[current] = 1;
if (ocurrencesMap[item] < ocurrencesMap[current]) item = current;
}
return {
item: item,
ocurrences: ocurrencesMap[item]
};
}
Hope it helps someone ;)!
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
Try to use edithidden: true and also do
editoptions: { dataInit: function(element) { $(element).attr("readonly", "readonly"); } }
Or see jqGrid wiki for custom editing, you can setup any input type, even label I think.
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.
Shape *shape = new Triangle();
cout << shape->getName();
In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.
The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.
Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?
To rename an image, you give it a new tag, and then remove the old tag using the ‘rmi’ command:
$ docker tag $ docker rmi
This second step is scary, as ‘rmi’ means “remove image”. However, docker won’t actually remove the image if it has any other tags. That is, if you were to immediately follow this with: docker rmi , then it would actually remove the image (assuming there are no other tags assigned to the image)
In "References", import DAO 3.6 object reference.
private sub showTableData
dim db as dao.database
dim rs as dao.recordset
set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously
'populate the table
rs.movelast
rs.movefirst
do while not rs.EOF
debug.print(rs!myField) 'myField is a field name in table myTable
rs.movenext 'press Ctrl+G to see debuG window beneath
loop
msgbox("End of Table")
end sub
You can interate data objects like queries and filtered tables in different ways:
Trhough query:
private sub showQueryData
dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string
sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"
set db = currentDb
set rs = db.openRecordset(sqlStr)
rs.movefirst
do while not rs.EOF
debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
rs.movenext
loop
msgbox("End of customers from Brazil")
end sub
You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.
I hope I've helped.
TL;DR:
cd Downloads
sudo tar xf ideaIC-2017.2.5.tar.gz -C /opt/
cd /opt/idea-IC-172.4343.14/bin
idea.sh
from the bin subdirectory. [EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).
When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.
Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.
In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.
With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.
There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use ===
but just this one time you have a good reason to use ==
. But even then, with ESLint you have the option to specify eslint-disable
around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)
[ORIGINAL ANSWER FOLLOWS]
By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.
Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.
Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.
I use ruamel.yaml. Details & debate here.
from ruamel import yaml
with open(filename, 'r') as fp:
read_data = yaml.load(fp)
Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use
from ruamel import yaml
instead of
import yaml
and it will fix most of your problems.
EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.
Well, you want to split, right?
String animals = "dog, cat, bear, elephant, giraffe";
String[] animalsArray = animals.split(",");
If you want to additionally get rid of whitespaces around items:
String[] animalsArray = animals.split("\\s*,\\s*");
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
You use and
and or
to perform logical operations like in C, C++. Like literally and
is &&
and or
is ||
.
Say you want to build Logic Gates in Python:
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
Now try calling them:
print AND(False, False)
print OR(True, False)
False
True
Hope this helps!
You may use this command for listing the files for your own debuggable apk:
adb shell run-as com.corp.appName ls /data/data/com.corp.appName/cache
And this script for pulling from cache:
#!/bin/sh
adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"
Then you can pull a file from cache like this:
./pull.sh cache/someCachedData.txt
Root is not required.
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id
is an IDENTITY
column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON
). If employee_id
is an IDENTITY
column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES()
- e.g. you may have to revisit your code and define a proper, explicit column list.
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
To have a good follow-up about all this, Twitter - one of the pioneers of hashbang URL's and single-page-interface - admitted that the hashbang system was slow in the long run and that they have actually started reversing the decision and returning to old-school links.
The whole idea behind Parallel.ForEach()
is that you have a set of threads and each thread processes part of the collection. As you noticed, this doesn't work with async
-await
, where you want to release the thread for the duration of the async call.
You could “fix” that by blocking the ForEach()
threads, but that defeats the whole point of async
-await
.
What you could do is to use TPL Dataflow instead of Parallel.ForEach()
, which supports asynchronous Task
s well.
Specifically, your code could be written using a TransformBlock
that transforms each id into a Customer
using the async
lambda. This block can be configured to execute in parallel. You would link that block to an ActionBlock
that writes each Customer
to the console.
After you set up the block network, you can Post()
each id to the TransformBlock
.
In code:
var ids = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var getCustomerBlock = new TransformBlock<string, Customer>(
async i =>
{
ICustomerRepo repo = new CustomerRepo();
return await repo.GetCustomer(i);
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});
var writeCustomerBlock = new ActionBlock<Customer>(c => Console.WriteLine(c.ID));
getCustomerBlock.LinkTo(
writeCustomerBlock, new DataflowLinkOptions
{
PropagateCompletion = true
});
foreach (var id in ids)
getCustomerBlock.Post(id);
getCustomerBlock.Complete();
writeCustomerBlock.Completion.Wait();
Although you probably want to limit the parallelism of the TransformBlock
to some small constant. Also, you could limit the capacity of the TransformBlock
and add the items to it asynchronously using SendAsync()
, for example if the collection is too big.
As an added benefit when compared to your code (if it worked) is that the writing will start as soon as a single item is finished, and not wait until all of the processing is finished.
The same may be achieved with the stringi package:
library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap" "b"
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
You can use this to find the index of an element:
Array.prototype.indexOf.call(yourUl, yourLi)
This for example logs all indices:
var lis = yourList.getElementsByTagName('li');
for(var i = 0; i < lis.length; i++) {
console.log(Array.prototype.indexOf.call(lis, lis[i]));
}?
Delete the public keys and generate new ones from the private keys. Keep them in separate directories, or use a naming convention to keep them straight.
If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY
environment variable, and stop xvfb after all.