foreach($array as $value=>$name)
{
if($value == $_GET['sel'])
{
echo "<option selected='selected' value='".$value."'>".$name."</option>";
}
else
{
echo "<option value='".$value."'>".$name."</option>";
}
}
#include <windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!\n";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/PCFreq;
}
int main()
{
StartCounter();
Sleep(1000);
cout << GetCounter() <<"\n";
return 0;
}
This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).
The StartCounter()
function records the number of ticks the performance counter has in the CounterStart
variable. The GetCounter()
function returns the number of milliseconds since StartCounter()
was last called as a double, so if GetCounter()
returns 0.001 then it has been about 1 microsecond since StartCounter()
was called.
If you want to have the timer use seconds instead then change
PCFreq = double(li.QuadPart)/1000.0;
to
PCFreq = double(li.QuadPart);
or if you want microseconds then use
PCFreq = double(li.QuadPart)/1000000.0;
But really it's about convenience since it returns a double.
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.
Another way to do this is described below.
First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation
. Then set maximum iterations to 1000.
After doing this, use the following formula.
=If(D55="","",IF(C55="",NOW(),C55))
Once anything is typed into cell D55
(for this example) then C55
populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.
This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.
This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";
; without synchronization you'll never know if you'll get HelloCiaoWorld
or HelloWorldCiao
or WorldHelloCiao
...
tie
lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;
).
You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.
I would recommend to use Bootstrap. http://getbootstrap.com/. This approach is very straight-forward and light weight.
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-fixed-top">
<li><a href="#home"> <br>BLINK</a></li>
<li><a href="#news"><br>ADVERTISING WITH BLINK</a></li>
<li><a href="#contact"><br>EDUCATING WITH BLINK</a></li>
<li><a href="#about"><br>ABOUT US</a></li>
</ul>
</div>
</div>
</div>
You need to include the Bootstrap into your project, which will include the necessary scripts and styles. Then just call the class 'navbar-fixed-top'. This will do the trick. See above example
The following should work and is my recommendation (parameterized query):
DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);
cmd.ExecuteNonQuery();
This solution worked for me
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(or height : 70% / bottom : 15%
height : 40% / bottom :30% ...)
You shouldn't change the npm registry using .bat
files.
Instead try to use modify the .npmrc
file which is the configuration for npm
.
The correct command for changing registry is
npm config set registry <registry url>
you can find more information with npm help config
command, also check for privileges when and if you are running .bat
files this way.
I did a bit of searching and found that if one is being pedantic then yes it might be considered useless...in particular situations...it depends on how time sensitive your requirements are...
Check out this quote from the Java Sun site:
The real-time clock and System.nanoTime() are both based on the same system call and thus the same clock.
With Java RTS, all time-based APIs (for example, Timers, Periodic Threads, Deadline Monitoring, and so forth) are based on the high-resolution timer. And, together with real-time priorities, they can ensure that the appropriate code will be executed at the right time for real-time constraints. In contrast, ordinary Java SE APIs offer just a few methods capable of handling high-resolution times, with no guarantee of execution at a given time. Using System.nanoTime() between various points in the code to perform elapsed time measurements should always be accurate.
Java also has a caveat for the nanoTime() method:
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292.3 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
It would seem that the only conclusion that can be drawn is that nanoTime() cannot be relied upon as an accurate value. As such, if you do not need to measure times that are mere nano seconds apart then this method is good enough even if the resulting returned value is negative. However, if you're needing higher precision, they appear to recommend that you use JAVA RTS.
So to answer your question...no nanoTime() is not useless....its just not the most prudent method to use in every situation.
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
It also occurs when you try to load()
an rds object instead of using
object <- readRDS("object.rds")
Suppose you have a python file hello.py
Create a file called job.sh
that contains
#!/bin/bash
python hello.py
mark it executable using
$ chmod +x job.sh
then run it
$ ./job.sh
Modify your script hello.py
and add this as the first line
#!/usr/bin/env python
mark it executable using
$ chmod +x hello.py
then run it
$ ./hello.py
First off I recommend you use the following constructor instead of the one you currently use:
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
Next, you really should remove this code:
// Wait 10 Seconds for data...
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(10);
Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console
}
And instead just loop until the user presses a key or something, like so:
namespace serialPortCollection
{ class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM10", 115200);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
// My Event Handler Method
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString());
}
Console.WriteLine();
}
}
}
Also, note the revisions to the data received event handler, it should actually print the buffer now.
UPDATE 1
I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34)
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Thread writeThread = new Thread(new ThreadStart(WriteThread));
SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
writeThread.Start();
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString() + " ");
}
Console.WriteLine();
}
private static void WriteThread()
{
SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One);
sp2.Open();
byte[] buf = new byte[100];
for (byte i = 0; i < 100; i++)
{
buf[i] = i;
}
sp2.Write(buf, 0, buf.Length);
sp2.Close();
}
}
}
UPDATE 2
Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding.
I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings.
Some tips on configuring the serial port:
Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device.
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here:
http://www.lammertbies.nl/comm/info/RS-232_flow_control.html
In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
alert( $( this ).html() );_x000D_
console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
This is specifically a special case because computers represent numbers in base 2. This is generalizable:
(number)base % basex
is equivilent to the last x digits of (number)base.
This happened if you change something in data set using native sql query but persisted object for same data set is present in session cache. Use session.evict(yourObject);
Well, base on your code, you would put onkeyup=sum() in each text box txt1 and txt2
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:
class A {
final Set<String> strings = new HashSet<>() {{
add("val1");
add("val2");
}};
// ...
if (strings.contains(str.toLowerCase())) {
}
// ...
}
It allows you to initialize you Set
in-place.
The BBC and meebo.com use CouchDB in production and so does one of my clients. Here is a list of other people using Couch: CouchDB in the wild
The major challenge is to know how to organize your documents and stop thinking in terms of relational data.
For t-SQL I use the following query for varchar columns (shows the collation and is_null properties):
SELECT
s.name
, o.name as table_name
, c.name as column_name
, t.name as type
, c.max_length
, c.collation_name
, c.is_nullable
FROM
sys.columns c
INNER JOIN sys.objects o ON (o.object_id = c.object_id)
INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
s.name = 'dbo'
AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
o.name, c.name
For my case, I initially tried with
git config --system --unset credential.helper
But I was getting error
error: could not lock config file C:/Program Files/Git/etc/gitconfig: Permission denied
Then tried with
git config --global --unset credential.helper
No error, but still got access denied error while git pulling.
Then went to Control Panel -> Credentials Manager > Windows Credential and deleted git account.
After that when I tried git pull again, it asked for the credentials and a new git account added in Credentails manager.
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
Not with pure HTML as far as I know.
But with JS or PHP or another scripting language such as JSP, you can do it very easily with a for loop.
Example in PHP:
<select>
<?php
for ($i=1; $i<=100; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
I know this is old but just wanted to mention that I tried this with PHP 7.2:
<?php
//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
{
$a[] = 100;
}
//Measure
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = count($a);
}
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = sizeof($a);
}
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");
?>
and the result was:
1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec
So just use count()
.
Another useful command would be git diff-tree <hash>
where hash can be also a hash range (denoted by <old>..<new>
notation). An output example:
$ git diff-tree HEAD
:040000 040000 8e09a be406 M myfile
The fields are:
source mode, dest mode, source hash, dest hash, status, filename
Statuses are the ones you would expect: D (deleted), A (added), M (modified) etc. See man page for full description.
i found a way to change format ,its a tricky way, i just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {_x000D_
color: #fff;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-year-field{_x000D_
position: absolute !important;_x000D_
border-left:1px solid #8c8c8c;_x000D_
padding: 2px;_x000D_
color:#000;_x000D_
left: 56px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-month-field{_x000D_
position: absolute !important;_x000D_
border-left:1px solid #8c8c8c;_x000D_
padding: 2px;_x000D_
color:#000;_x000D_
left: 26px;_x000D_
}_x000D_
_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-day-field{_x000D_
position: absolute !important;_x000D_
color:#000;_x000D_
padding: 2px;_x000D_
left: 4px;_x000D_
_x000D_
}
_x000D_
<input type="date" value="2019-12-07">
_x000D_
In below showToast() method you have to pass another parameter for context or application context by doing so you can try it.
public void showToast(String error, Context applicationContext){
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.custom_toast, (ViewGroup)
findViewById(R.id.toast_root));
TextView text = (TextView) findViewById(R.id.toast_error);
text.setText(error);
Toast toast = new Toast(applicationContext);
toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();
}
Your user.jsp:
<form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
---
---
</form:form>
In your controller class:
(make it as a meaning full method name..Hear i think you are insert record in DB.)
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String proffessionalDetails(
@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("PROFESSIONAL", professionalForm);
return "Your Professional Details Updated";
}
Java 7 introduced Files.readAllBytes()
, which can read a PDF into a byte[]
like so:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
Path pdfPath = Paths.get("/path/to/file.pdf");
byte[] pdf = Files.readAllBytes(pdfPath);
EDIT:
Thanks Farooque for pointing out: this will work for reading any kind of file, not just PDFs. All files are ultimately just a bunch of bytes, and as such can be read into a byte[]
.
Try this
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'form_params' => array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
)
);
LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%
Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
@echo off
setlocal enabledelayedexpansion
:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
set v1=%%i& set v2=%%j& set v3=%%k
if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
)
)
:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%
:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]
endlocal
pause
I hope this helps someone that deal with diferent languages.
Two of the most widely used parsers are Expat and libxml.
If you are okay with using C++, there's Xerces-C++ too.
Since my requirement is override the existing textView get from findViewById(getResources().getIdentifier("xxx", "id", "android"));
, so I can't simply try onDraw()
of other answer.
But I just figure out the correct steps to fixed my problem, here is the final result from Layout Inspector:
Since what I wanted is merely remove the top spaces, so I don't have to choose other font to remove bottom spaces.
Here is the critical code to fixed it:
Typeface mfont = Typeface.createFromAsset(getResources().getAssets(), "fonts/myCustomFont.otf");
myTextView.setTypeface(mfont);
myTextView.setPadding(0, 0, 0, 0);
myTextView.setIncludeFontPadding(false);
The first key is set custom font "fonts/myCustomFont.otf" which has the space on bottom but not on the top, you can easily figure out this by open otf file and click any font in android Studio:
As you can see, the cursor on the bottom has extra spacing but not on the top, so it fixed my problem.
The second key is you can't simply skip any of the code, otherwise it might not works. That's the reason you can found some people comment that an answer is working and some other people comment that it's not working.
Let's illustrated what will happen if I remove one of them.
Without setTypeface(mfont);
:
Without setPadding(0, 0, 0, 0);
:
Without setIncludeFontPadding(false);
:
Without 3 of them (i.e. the original):
You could do something like this:
grd.DataSource = getDataSource();
if (grd.ColumnCount > 1)
{
for (int i = 0; i < grd.ColumnCount-1; i++)
grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[grd.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
if (grd.ColumnCount==1)
grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
All columns will adapt to the content except the last one will fill the grid.
Same thing with IIS Express 10.0 after upgrading Windows 7 to Windows 10. Solution: go to IIS and enable all disabled websites and reinstall ASP.NET Core.
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
There is something wrong with your code.
position : absolute
makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll
This can be solved with position : fixed
This property will make the element position fixed and still relative to the scroll.
Or
You can check it out Here
I believe that if you run git branch --all
from Bash that the list of remote and local branches you see will reflect what your local Git "knows" about at the time you run the command. Because your Git is always up to date with regard to the local branches in your system, the list of local branches will always be accurate.
However, for remote branches this need not be the case. Your local Git only knows about remote branches which it has seen in the last fetch (or pull). So it is possible that you might run git branch --all
and not see a new remote branch which appeared after the last time you fetched or pulled.
To ensure that your local and remote branch list be up to date you can do a git fetch
before running git branch --all
.
For further information, the "remote" branches which appear when you run git branch --all
are not really remote at all; they are actually local. For example, suppose there be a branch on the remote called feature
which you have pulled at least once into your local Git. You will see origin/feature
listed as a branch when you run git branch --all
. But this branch is actually a local Git branch. When you do git fetch origin
, this tracking branch gets updated with any new changes from the remote. This is why your local state can get stale, because there may be new remote branches, or your tracking branches can become stale.
this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.
$query->withCount([
'activity AS paid_sum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
it returns
"paid_sum_count" => "320.00"
in Deals attribute.
This it now the sum which i wanted to get not the count.
I'm not an expert. But you can try
git fsck --full --no-reflogs | grep commit
to find the HEAD commit of deleted branch and get them back.
The best answer I have ever seen is How to run 32-bit applications on Ubuntu 64-bit?
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
sudo ./adb
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
In PostreSQL you can use SIMILAR TO operator (more):
-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';
I put this question to the IETF HTTP WG. The comment from Roy Fielding (author of http/1.1 document in 1998) was that
"... an implementation would be broken to do anything other than to parse and discard that body if received"
RFC 7213 (HTTPbis) states:
"A payload within a GET request message has no defined semantics;"
It seems clear now that the intention was that semantic meaning on GET request bodies is prohibited, which means that the request body can't be used to affect the result.
There are proxies out there that will definitely break your request in various ways if you include a body on GET.
So in summary, don't do it.
I am not sure that the issue is related to what header php is sending. Make sure that the buffering is enabled. The simple way is to create a proxy.conf file:
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 100m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
And a fascgi.conf file:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
fastcgi_buffers 128 4096k;
fastcgi_buffer_size 4096k;
fastcgi_index index.php;
fastcgi_param REDIRECT_STATUS 200;
Next you need to call them in your default config server this way:
http {
include /etc/nginx/mime.types;
include /etc/nginx/proxy.conf;
include /etc/nginx/fastcgi.conf;
index index.html index.htm index.php;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log /logs/access.log main;
sendfile on;
tcp_nopush on;
# ........
}
Authentication issue: I use TortoiseGit GUI tool, I need to tell tortoise the username and password so that it can access to work with Git/GitHub/Gitlab code base. To tell it, rt click inside any folder to get TortoiseGit menu. Here TortoseGit > Settings Window > Select Credentials in left nav tree Enter URL:Git url Helper: Select windows if your windows credentials are same as the ones for Git or 'manager' if they are different userName; Git User Name Save this settings ans try again. You will be prompted for password and then it worked.
right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition
then you can create a new or choose a different connection
Simplest form that worked for me.
import traceback
try:
print(4/0)
except ZeroDivisionError:
print(traceback.format_exc())
Output
Traceback (most recent call last):
File "/path/to/file.py", line 51, in <module>
print(4/0)
ZeroDivisionError: division by zero
Process finished with exit code 0
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
I'm using this simple code for this task:
CSS Code
.demo {
background: tomato;
color: white;
}
Javascript code
function myFunction() {
/* Assign element to x variable by id */
var x = document.getElementById('para);
if (x.hasAttribute('class') {
x.removeAttribute('class');
} else {
x.setAttribute('class', 'demo');
}
}
you may use yourArray.length
to findout number of elements in an array.
Make sure yourArray is not null before doing yourArray.length
, otherwise you will end up with NullPointerException
.
The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/
I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:
Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant
f.show
with f
.allowmultiselect = false
for each varfile in .selecteditems
msgbox varfile
next varfile
end with
Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
As pointed out in Mohsen's answer, in ES6 it's possible to extend errors using classes. It's a lot easier and their behavior is more consistent with native errors...but unfortunately it's not a simple matter to use this in the browser if you need to support pre-ES6 browsers. See below for some notes on how that might be implemented, but in the meantime I suggest a relatively simple approach that incorporates some of the best suggestions from other answers:
function CustomError(message) {
//This is for future compatibility with the ES6 version, which
//would display a similar message if invoked without the
//`new` operator.
if (!(this instanceof CustomError)) {
throw new TypeError("Constructor 'CustomError' cannot be invoked without 'new'");
}
this.message = message;
//Stack trace in V8
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
else this.stack = (new Error).stack;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.name = 'CustomError';
In ES6 it's as simple as:
class CustomError extends Error {}
...and you can detect support for ES6 classes with try {eval('class X{}')
, but you'll get a syntax error if you attempt to include the ES6 version in a script that's loaded by older browsers. So the only way to support all browsers would be to load a separate script dynamically (e.g. via AJAX or eval()
) for browsers that support ES6. A further complication is that eval()
isn't supported in all environments (due to Content Security Policies), which may or may not be a consideration for your project.
So for now, either the first approach above or simply using Error
directly without trying to extend it seems to be the best that can practically be done for code that needs to support non-ES6 browsers.
There is one other approach that some people might want to consider, which is to use Object.setPrototypeOf()
where available to create an error object that's an instance of your custom error type but which looks and behaves more like a native error in the console (thanks to Ben's answer for the recommendation). Here's my take on that approach: https://gist.github.com/mbrowne/fe45db61cea7858d11be933a998926a8. But given that one day we'll be able to just use ES6, personally I'm not sure the complexity of that approach is worth it.
Use the abc
module to create abstract classes. Use the abstractmethod
decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.
In Python 3.4 and above, you can inherit from ABC
. In earlier versions of Python, you need to specify your class's metaclass as ABCMeta
. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:
# Python 3.4+
from abc import ABC, abstractmethod
class Abstract(ABC):
@abstractmethod
def foo(self):
pass
# Python 3.0+
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
# Python 2
from abc import ABCMeta, abstractmethod
class Abstract:
__metaclass__ = ABCMeta
@abstractmethod
def foo(self):
pass
Whichever way you use, you won't be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods:
>>> Abstract()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstract with abstract methods foo
>>> class StillAbstract(Abstract):
... pass
...
>>> StillAbstract()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo
>>> class Concrete(Abstract):
... def foo(self):
... print('Hello, World')
...
>>> Concrete()
<__main__.Concrete object at 0x7fc935d28898>
Your code works for me. When does addSalespersonOption
get called? There may be a problem with that call.
Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:
<select id="salesperson">
<option value="">(select)</option>
</select>
instead of this:
<select id="salesperson" />
<option value"">(select)</option>
</select>
Edit: When does your options list get dynamically populated? Are you sure you are passing 'on'
for the defSales
value in your call to addSalespersonOption
? Try changing that code to this:
if (selected == "on") {
alert('setting default selected option to ' + text);
html = '<option value="'+value+'" selected="selected">'+text+'</option>';
}
and see if the alert happens and what is says if it does happen.
Edit: Working example of my testing (the error:undefined is from jsbin, not my code).
Detect most browsers with this:
var getBrowser = function(){
var navigatorObj = navigator.appName,
userAgentObj = navigator.userAgent,
matchVersion;
var match = userAgentObj.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
if( match && (matchVersion = userAgentObj.match(/version\/([\.\d]+)/i)) !== null) match[2] = matchVersion[1];
//mobile
if (navigator.userAgent.match(/iPhone|Android|webOS|iPad/i)) {
return match ? [match[1], match[2], mobile] : [navigatorObj, navigator.appVersion, mobile];
}
// web browser
return match ? [match[1], match[2]] : [navigatorObj, navigator.appVersion, '-?'];
};
I don't know how good of a solution this is it, but after following some of the other answer to this question without success, i resolved setting the connection user of the service MSSQLSERVER to "Local Service".
N.B: i'm using SQL Server 2017.
You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:
git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks
The result should be your master is now essentially seotweaks.
(-s ours
is short for --strategy=ours
)
From the docs about the 'ours' strategy:
This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.
Update from comments: If you get fatal: refusing to merge unrelated histories
, then change the second line to this: git merge --allow-unrelated-histories -s ours master
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
The option you're asking about is for the find
command though, not for bash. From your command line, you can man find
to see the options.
The one you're looking for is -o
for "or":
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.
$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp
The Bash FAQ has lots of other excellent tips about programming in bash.
You can also throw an exception:
For the sake of readability each step of stream should be listed in new line.
players.stream()
.filter(player -> player.getName().contains(name))
.findFirst()
.orElseThrow(MyCustomRuntimeException::new);
if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch
and throwing these exceptions are for very special cases that you expect them and can be handled properly.)
Try one of the following, depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
EDIT:
if you want to access the raw bytes that make up the UIImage, you could use this approach:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
This will give you the low-level representation of the image RGB pixels.
(Omit the CFBridgingRelease
bit if you are not using ARC).
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
Naïve approach:
a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]
Out[2]: 'A long string with a . in the middle ending with . -'
Aditya Sihag's answer with a single rfind
:
pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]
The simplest solution to run two Python processes concurrently is to run them from a bash file, and tell each process to go into the background with the &
shell operator.
python script1.py &
python script2.py &
For a more controlled way to run many processes in parallel, look into the Supervisor project, or use the multiprocessing module to orchestrate from inside Python.
My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.
Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.
There are many places where the COM port can be configured.
Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]
Windows > Start Menu > Arduino > Tools > Ports > [choose port]
Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".
C:\Users{user name}\AppData\Local\Arduino15\preferences.txt
target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75
programmer = arduino:avrispmkii
upload.using = bootloader
upload.verify = true
serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600
# I18 Preferences
# default chosen language (none for none)
editor.languages.current =
The user preferences.txt overrides this one:
C:\Users{user name}\Desktop\avrdude.conf
... search for "com" ... "com1" is the default
PATH=echo $PATH | sed 's/:/\n/g' | sort -u | sed ':a;N;$!ba;s/\n/:/g'
I am using texmaker as the editor. you have to compile it in terminal as following:
but sometimes, when you use \citep{}
, the names of the references don't show up. In this case, I had to open the references.bib
file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.
<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox
<div id="div1" style="display:none;">NOTICE</div>
<script type="text/javascript">
<!--
function showMe (box) {
var chboxs = document.getElementById("div1").style.display;
var vis = "none";
if(chboxs=="none"){
vis = "block"; }
if(chboxs=="block"){
vis = "none"; }
document.getElementById(box).style.display = vis;
}
//-->
</script>
When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)
$.ajax({
type: "POST",
url: url,
data: '{"name" :"sheo"}',
contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).done(function (Response) {
//do something when get response })
.fail(function (Response) {
//do something when any error occurs.
});
This is how you do a distinct count query. Note that you have to filter out the nulls.
var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).Distinct().Count();
If you combine this with into your current grouping code, I think you'll have your solution.
For test navegation on Express
:
const request = require('supertest');
const server = require('../bin/www');
describe('navegation', () => {
it('login page', function(done) {
this.timeout(4000);
const timeOut = setTimeout(done, 3500);
request(server)
.get('/login')
.expect(200)
.then(res => {
res.text.should.include('Login');
clearTimeout(timeOut);
done();
})
.catch(err => {
console.log(this.test.fullTitle(), err);
clearTimeout(timeOut);
done(err);
});
});
});
In the example the test time is 4000 (4s).
Note: setTimeout(done, 3500)
is minor for than done
is called within the time of the test but clearTimeout(timeOut)
it avoid than used all these time.
In latest version (1.0RC) of TypeScript, you can use enums like this:
enum States {
New,
Active,
Disabled
}
// this will show message '0' which is number representation of enum member
alert(States.Active);
// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);
Update 1
To get number value of enum member from string value, you can use this:
var str = "Active";
// this will show message '1'
alert(States[str]);
Update 2
In latest TypeScript 2.4, there was introduced string enums, like this:
enum ActionType {
AddUser = "ADD_USER",
DeleteUser = "DELETE_USER",
RenameUser = "RENAME_USER",
// Aliases
RemoveUser = DeleteUser,
}
For more info about TypeScript 2.4, read blog on MSDN.
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {_x000D_
_x000D_
var arr = dataurl.split(','),_x000D_
mime = arr[0].match(/:(.*?);/)[1],_x000D_
bstr = atob(arr[1]), _x000D_
n = bstr.length, _x000D_
u8arr = new Uint8Array(n);_x000D_
_x000D_
while(n--){_x000D_
u8arr[n] = bstr.charCodeAt(n);_x000D_
}_x000D_
_x000D_
return new File([u8arr], filename, {type:mime});_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');_x000D_
console.log(file);
_x000D_
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance_x000D_
function urltoFile(url, filename, mimeType){_x000D_
return (fetch(url)_x000D_
.then(function(res){return res.arrayBuffer();})_x000D_
.then(function(buf){return new File([buf], filename,{type:mimeType});})_x000D_
);_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')_x000D_
.then(function(file){ console.log(file);});
_x000D_
- compile
Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)
- provided
Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)
If you're using Spring Boot and the above suggestions don't work, you might want to look at the Eclipse Problems view (available at Window -> Show View -> Problems).
For example, you can get the same error (Error: Could not find or load main class groupId.Application) if one of your jar files is corrupted. Eclipse will complain that it can't find the Applications class, even though the bad jar is the root cause.
The Problems view, however, will identify the bad jar for you.
At any rate, I had to manually go to my local mvn repo (in .m2) and manually delete the corrupted jar, and update it (right click on the project in the Package Explorer), Maven --> Update Project... -> OK (assuming that the correct project is check-marked).
Here it is, You have to follow write a few methods here. #Swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? UITableViewHeaderFooterView
header?.textLabel?.font = UIFont.init(name: "Montserrat-Regular", size: 14)
header?.textLabel?.textColor = .greyishBrown
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 26
}
Have a good luck
The first response from App-Specific URL Schemes worked for me on iOS 10.3.
if let appSettings = URL(string: UIApplicationOpenSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
UIApplication.shared.open(appSettings)
}
}
Here is what worked for me.
Install the userspace USB programming library development files
sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h
The path should appear as (or similar)
/usr/include/libusb-1.0/libusb.h
Include the header to your C code
#include <libusb-1.0/libusb.h>
Compile your C file
gcc -o example example.c -lusb-1.0
I don't think you can do that this way. You should use :
void addEventListener(
in DOMString type,
in EventListener listener,
in boolean useCapture
);
Documentation right here.
Another solution as seen here:
find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +
In MySQL you can use:
SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")
The SOUNDEX
function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.
I love the fact that this sort of thing is fine in JavaScript:
var futureDate = new Date(2010,77,154);
alert(futureDate);
and results in a date 77 months and 154 days from the 0th day of 0th month of 2010 i.e. Nov 1st 2016
Similar to paxdiablo above. This code, inserted in a wider app, works fine with STM32 NUCLEO-F446RE.
#include <stdio.h>
#include <math.h>
#include <string.h>
void IntegFract(char *pcIntegStr, char *pcFractStr, double dbValue, int iPrecis);
main()
{
char acIntegStr[9], acFractStr[9], char counter_buff[30];
double seconds_passed = 123.0567;
IntegFract(acIntegStr, acFractStr, seconds_passed, 3);
sprintf(counter_buff, "Time: %s.%s Sec", acIntegStr, acFractStr);
}
void IntegFract(char *pcIntegStr, char *pcFractStr, double dbValue, int
iPrecis)
{
int iIntegValue = dbValue;
int iFractValue = (dbValue - iIntegValue) * pow(10, iPrecis);
itoa(iIntegValue, pcIntegStr, 10);
itoa(iFractValue, pcFractStr, 10);
size_t length = strlen(pcFractStr);
char acTemp[9] = "";
while (length < iPrecis)
{
strcat(acTemp, "0");
length++;
}
strcat(acTemp, pcFractStr);
strcpy(pcFractStr, acTemp);
}
counter_buff would contain 123.056 .
For some applications may be better:
string.Join(",", arr1) == string.Join(",", arr2)
Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.
If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.
If you use native sql, you can refer to my code, otherwise just ignore my answer.
SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text
bar_tags = "banana"
# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
Try using the following commands
//For make issues
sudo apt-get install build-essential
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash
//To uninstall a node version
nvm uninstall <current version>
nvm install 6.10.3
nvm use 6.10.3
//check with
node -v
Coop's answer is excellent.
However it depends on jQuery, here is a version that has no dependencies:
HTML
<div id="sticky" class="sticky"></div>
CSS
.sticky {
width: 100%
}
.fixed {
position: fixed;
top:0;
}
JS
(This uses eyelidlessness's answer for finding offsets in Vanilla JS.)
function findOffset(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
}
window.onload = function () {
var stickyHeader = document.getElementById('sticky');
var headerOffset = findOffset(stickyHeader);
window.onscroll = function() {
// body.scrollTop is deprecated and no longer available on Firefox
var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (bodyScrollTop > headerOffset.top) {
stickyHeader.classList.add('fixed');
} else {
stickyHeader.classList.remove('fixed');
}
};
};
Example
You can access the full uri/url with 'document.referrer'
Check https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer
To get parameters from URL with ngRoute
. It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.
The solution for the question:
// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
// configure the routing rules here
$routeProvider.when('/backend/:type/:id', {
controller: 'PagesCtrl'
});
// enable HTML5mode to disable hashbang urls
$locationProvider.html5Mode(true);
})
.controller('PagesCtrl', function ($routeParams) {
console.log($routeParams.id, $routeParams.type);
});
If you don't enable the $locationProvider.html5Mode(true);
. Urls will use hashbang(/#/
).
More information about routing can be found on official angular $route API documentation.
Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.
charAt
gets a character from a string, and you can switch on them since char
is an integer type.
So to switch on the first char
in the String
hello
,
switch (hello.charAt(0)) {
case 'a': ... break;
}
You should be aware though that Java char
s do not correspond one-to-one with code-points. See codePointAt
for a way to reliably get a single Unicode codepoints.
Unless you're running a production server, don't worry about this message. This is a library which is used to improve performance (on production systems). From Apache Portable Runtime (APR) based Native library for Tomcat:
Tomcat can use the Apache Portable Runtime to provide superior scalability, performance, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).
You can use npm install --save redux-form
Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.
import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
class LoginForm extends Component {
onSubmit(props) {
//do your submit stuff
}
render() {
const {fields: {email}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" placeholder="Email"
className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
{...email}
/>
<span className="text-help">
{email.touched ? email.error : ''}
</span>
<input type="submit"/>
</form>
);
}
}
function validation(values) {
const errors = {};
const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
if (!emailPattern.test(values.email)) {
errors.email = 'Enter a valid email';
}
return errors;
}
LoginForm = reduxForm({
form: 'LoginForm',
fields: ['email'],
validate: validation
}, null, null)(LoginForm);
export default LoginForm;
Here lot of good answer but i think this will help someone
select id from campaign where ( NOW() BETWEEN start_date AND end_date)
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
Here's an online ViewState decoder:
http://ignatu.co.uk/ViewStateDecoder.aspx
Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):
You cant do it on shared hosting , Add ticket to support of hosting for same ( otherwise you can look for dedicated server where you can manage anything )
You can use Target-specific Variable Values. Example:
CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2
all: executable
debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable
executable: CommandParser.tab.o CommandParser.yy.o Command.o
$(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl
CommandParser.yy.o: CommandParser.l
flex -o CommandParser.yy.c CommandParser.l
$(CC) -c CommandParser.yy.c
Remember to use $(CXX) or $(CC) in all your compile commands.
Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.
On a side note, you can make your Makefile a lot more concise like other posts had suggested.
To know the list of java running on the linux machine. ps -e | grep java
Use a 9-patch drawable or create a Shape drawable.
LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:
Returns the left part of a character string with the specified number of characters.
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse
LEFT ( character_expression , integer_expression )
Most web applications detects mobile devices based on the HTTP Headers.
If your web site also uses HTTP Headers to identify mobile device, you can do the following:
User-Agent
and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
Hope it helps!
Iterate through the string, and use charAt() to get the char. Then treat it as an int, and see if it has a unicode value (a superset of ASCII) which you like.
Break at the first you don't like.
Excel ColumnWidth from dataGridView:
foreach (DataGridViewColumn co in dataGridView1.Columns)
{ worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }
Maybe I'm missing something, but for me this one-liner works fine with a byte array that contains an image of a JPEG file.
Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray));
EDIT:
See here for an updated version of this answer: How to convert image in byte array
You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.
variable=abc,def,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
# call your procedure/other scripts here below
echo "$i"
done
Instead of the echo "$i"
call above, between the do
and done
inside the for loop, you can invoke your procedure proc "$i"
.
Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS
and then parse your variable.
Hope this helps.
I'm currently fighting with dropdowns and I'd like to share my experiences:
There are specific situations where <select>
can't be used and must be 'emulated' with dropdown.
For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select>
is not supported in input groups, it will not be rendered properly.
Or does anybody solved this already? I would be very interested on the solution.
And to make it even more complicated, you can't use so simply $(this).text()
to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example:
<li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li>
Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.
I found two possible solutions:
1)
Use $(this).html()
to get content of the selected <li>
element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a>
so you need to play with this to extract what you need.
2)
Use $(this).text()
and hide the text in element in hidden span:
<li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>
.
For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html()
result like in option 1) to get what you need.
I hope it's clear and can help somebody :-)
Probably I have found myself:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
I like the top voted answer; however, it has problems with list as shown.
>> a, b = ([0]*5,)*2
>> print b
[0, 0, 0, 0, 0]
>> a[0] = 1
>> print b
[1, 0, 0, 0, 0]
This is discussed in great details (here), but the gist is that a
and b
are the same object with a is b
returning True
(same for id(a) == id(b)
). Therefore if you change an index, you are changing the index of both a
and b
, since they are linked. To solve this you can do (source)
>> a, b = ([0]*5 for i in range(2))
>> print b
[0, 0, 0, 0, 0]
>> a[0] = 1
>> print b
[0, 0, 0, 0, 0]
This can then be used as a variant of the top answer, which has the "desired" intuitive results
>> a, b, c, d, e, g, h, i = (True for i in range(9))
>> f = (False for i in range(1)) #to be pedantic
One notable difference is that if you pass a .c
file to gcc it will compile as C.
The default behavior of g++ is to treat .c
files as C++ (unless -x c
is specified).
useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.
object and array spread or rest will not work inside useEffect.
React.useEffect(() => {
console.log("effect");
(async () => {
try {
let result = await fetch("/query/countries");
const res = await result.json();
let result1 = await fetch("/query/projects");
const res1 = await result1.json();
let result11 = await fetch("/query/regions");
const res11 = await result11.json();
setData({
countries: res,
projects: res1,
regions: res11
});
} catch {}
})(data)
}, [setData])
# or use this
useEffect(() => {
(async () => {
try {
await Promise.all([
fetch("/query/countries").then((response) => response.json()),
fetch("/query/projects").then((response) => response.json()),
fetch("/query/regions").then((response) => response.json())
]).then(([country, project, region]) => {
// console.log(country, project, region);
setData({
countries: country,
projects: project,
regions: region
});
})
} catch {
console.log("data fetch error")
}
})()
}, [setData]);
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
They're simply different schemes for representing Unicode characters.
Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.
UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.
For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.
See this page for more about UTF-8 and Unicode.
(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)
Adding my two cents to other answers.
Check if you haven't by any chance created your test class under src/main/java
instead of usual src/test/java
. The former is the default in Eclipse when you create a new test class for whatever reason and can be overlooked. It can be as simple as that.
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
You don't need to convert NumPy
array to Mat
because OpenCV cv2
module can accept NumPy
array.
The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy
array is equal to 255. So you should divide by 255 in your code, as shown below.
img = numpy.zeros([5,5,3])
img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0
cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()
it seems that you should set your command as an String[]
,for example:
String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);
it just like the style of main(String[] args)
.
I personally prefer automatic submit after end of typing. Here's how you can detect this event.
Declarations and initialization:
private Timer timer = new Timer();
private final long DELAY = 1000; // in ms
Listener in e.g. onCreate()
EditText editTextStop = (EditText) findViewById(R.id.editTextStopId);
editTextStop.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before,
int count) {
if(timer != null)
timer.cancel();
}
@Override
public void afterTextChanged(final Editable s) {
//avoid triggering event when text is too short
if (s.length() >= 3) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO: do what you need here (refresh list)
// you will probably need to use
// runOnUiThread(Runnable action) for some specific
// actions
serviceConnector.getStopPoints(s.toString());
}
}, DELAY);
}
}
});
So, when text is changed the timer is starting to wait for any next changes to happen. When they occure timer is cancelled and then started once again.
This would do the job:
Double.parseDouble(p.replace(',','.'));
In my case the status became 0 when i would forget to put the WWW in front of my domain. Because all my ajax requests were hardcoded http:/WWW.mydomain.com and the webpage loaded would just be http://mydomain.com it became a security issue because its a different domain. I ended up doing a redirect in my .htaccess file to always put www in front.
C:\\Users\\expoperialed\\Desktop\\Python
This syntax worked for me.
<!-- Binding settings for HTTPS endpoint -->
<binding name="yourServiceName">
<security mode="Transport">
<transport clientCredentialType="None" />
<!-- Don't use message -->
</security>
</binding>
Can also do more dynamic inits with fill, e.g.
Array.fill(10){scala.util.Random.nextInt(5)}
==>
Array[Int] = Array(0, 1, 0, 0, 3, 2, 4, 1, 4, 3)
I just added a gradle.properties
file with the following content:
org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_45
Alt + Shift + F10 will show the menu associated with the smart tag.
this configuration in app.js worked fine for me :
//production mode
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join((__dirname + "/client/build/index.html")));
});
}
//build mode
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/public/index.html"));
});
Unique Key :
Primary Key
Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke
method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke
.
Example:
static int GetAnswer() {
return 42;
}
...
Func<int> method = GetAnswer;
var res = method.BeginInvoke(null, null); // provide args as needed
var answer = method.EndInvoke(res);
GetAnswer
will execute on a thread pool thread and when completed you can retrieve the answer via EndInvoke
as shown.
Here I am going to export 3 tables from database named myDB in an sql file named table.sql
mysqldump -u root -p myDB table1 table2 table3 > table.sql
Actually, you're best off with the TextClock widget. It handles all of the complexity for you and will respect the user's 12/24hr preferences. http://developer.android.com/reference/android/widget/TextClock.html
The selector would be label[for=email]
, so in CSS:
label[for=email]
{
/* ...definitions here... */
}
...or in JavaScript using the DOM:
var element = document.querySelector("label[for=email]");
...or in JavaScript using jQuery:
var element = $("label[for=email]");
It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.
(I'm assuming that the template {t _your_email}
will fill in a field with id="email"
. If not, use a class instead.)
Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:
label[for="field[]"]
{
/* ...definitions here... */
}
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
According to Dangerously Set innerHTML,
Improper use of the
innerHTML
can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name
dangerouslySetInnerHTML
is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key
__html
and your sanitized data as the value. Here is an example using the JSX syntax:
function createMarkup() {
return {
__html: 'First · Second' };
};
<div dangerouslySetInnerHTML={createMarkup()} />
Read more about it using below link:
documentation: React DOM Elements - dangerouslySetInnerHTML.
UPDATE `salary_generation_tbl` SET
`modified_by` = IF(
LOCATE('$', `other_salary_string`) > 0,
SUBSTRING(`other_salary_string`, 1, LOCATE('$', `other_salary_string`) - 1),
`other_salary_string`
),
`other_salary` = IF(
LOCATE('$', `other_salary_string`) > 0,
SUBSTRING(`other_salary_string`, LOCATE('$', `other_salary_string`) + 1),
NULL
);
There are instructions on how to install sshpass here:
https://gist.github.com/arunoda/7790979
For Mac you will need to install xcode and command line tools then use the unofficial Homewbrew command:
brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.
If you don't know the variable names, just do a var_dump($blog);
within the loop to see them.
The simplest method - access $blog as an object directly:
Try (assuming those variables are correct):
<?php
foreach ($blogs as $blog) {
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
The alternative method - access $blog as an array:
Alternatively, you may be able to turn $blog
into an array with get_object_vars
(documentation):
<?php
foreach($blogs as &$blog) {
$blog = get_object_vars($blog);
$id = $blog['id'];
$title = $blog['title'];
$content = $blog['content'];
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog
object.
Better than either of the above - Inline PHP Syntax
Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:
<?php foreach($blogs as $blog): ?>
<h1><?php echo $blog->title; ?></h1>
<p><?php echo $blog->content; ?></p>
<?php endforeach; ?>
Hope this helped.
Crazy idea...
You could play around with some pseudo elements, and create up/down arrows of css content hex codes. The only challange will be to precise the positioning of the arrow, but it may work:
input[type="number"] {_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.number-wrapper {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:after {_x000D_
content: "\25B2";_x000D_
position: absolute;_x000D_
color: blue;_x000D_
left: 100%;_x000D_
margin-left: -17px;_x000D_
margin-top: 12%;_x000D_
font-size: 11px;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:before {_x000D_
content: "\25BC";_x000D_
position: absolute;_x000D_
color: blue;_x000D_
left: 100%;_x000D_
bottom: 0;_x000D_
margin-left: -17px;_x000D_
margin-bottom: -14%;_x000D_
font-size: 11px;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
<input type="number" />_x000D_
</span>
_x000D_
echo `date +%s`/86400 | bc
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference
package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml
like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
You could try:
.modal.modal-wide .modal-dialog {
width: 90%;
}
.modal-wide .modal-body {
overflow-y: auto;
}
Just add .modal-wide to your classes
NOTE: Not 100% Cross Browser
Check browser compatibility @ http://caniuse.com/#search=FileReader
as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..
The Fiddle: http://jsfiddle.net/d2atnbrt/3/
THE HTML CODE:
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
THE JS CODE:
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed
This is as basic as i could get it,
EDIT - Generating A Table
The Fiddle: http://jsfiddle.net/d2atnbrt/5/
This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..
One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least
Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls
This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
Since in Vue 2.0, no solution seems available, a clean solution that I found is to create a vue-id
attribute, and also set it on the template. Then on created
and beforeDestroy
lifecycle these instances are updated on the global object.
Basically:
created: function() {
this._id = generateUid();
globalRepo[this._id] = this;
},
beforeDestroy: function() {
delete globalRepo[this._id]
},
data: function() {
return {
vueId: this._id
}
}
As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.
Use the constructor that takes a File
and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true
. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
The function below will return the x86 Program Files
directory in all of these three Windows configurations:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
If you use kotlin:
In MainActivity1:
var intent=Intent(this,MainActivity2::class.java)
intent.putExtra("EXTRA_SESSION_ID",sessionId)
startActivity(intent)
In MainActivity2:
if (intent.hasExtra("EXTRA_SESSION_ID")){
var name:String=intent.extras.getString("sessionId")
}
Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector
's insertion operation on the validity of iterators and references with respect to reserve()
and capacity()
, which the most upvoted answer failed to notice.
C++ 03:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().
C++11:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().
So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)
" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()
". This is one thing that C++03 differs from C++11. In C++03, once an insert()
causes the size of the vector to reach the value specified in the previous reserve()
call (which could well be smaller than the current capacity()
since a reserve()
could result a bigger capacity()
than asked for), any subsequent insert()
could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity()
to know with certainty that the next reallocation won't take place before the size overpasses capacity()
.
In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve()
that you should check the size against, not the return value of a call to capacity()
, otherwise you may get yourself surprised at a "premature" reallocation.
You can use CSS3 transition
Some good links:
http://css-tricks.com/different-transitions-for-hover-on-hover-off/
http://www.alistapart.com/articles/understanding-css3-transitions/
Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation()
returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.
What you need to do is to modify the interface, so that it is asynchronous:
interface IIO
{
Task DoOperationAsync(); // note: no async here
}
class IOImplementation : IIO
{
public async Task DoOperationAsync()
{
// perform the operation here
}
}
This way, the user will see that the operation is async
and they will be able to await
it. This also pretty much forces the users of your code to switch to async
, but that's unavoidable.
Also, I assume using StartNew()
in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task()
is even worse, that won't even work, because you don't Start()
the Task
.)
As of .NET 4.7
the preferred method of overriding GetHashCode()
is shown below. If targeting older .NET versions, include the System.ValueTuple nuget package.
// C# 7.0+
public override int GetHashCode() => (FooId, FooName).GetHashCode();
In terms of performance, this method will outperform most composite hash code implementations. The ValueTuple is a struct
so there won't be any garbage, and the underlying algorithm is as fast as it gets.
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
My 5 cents here, using form.elements
which allows you to query each field by it's name
, not only by iteration:
const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;
Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want. using
val args = Bundle()
you can set your args.
You can now use args.putSomthing
to add you args which u give as a prameter in your newInstance function.
putString(key:String,str:String)
to add string for example and so on
Now to get the argument you can use
arguments.getSomthing(Key:String)
=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.
So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = array[i];
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);
This function can be called as many times as you want and each time, it will just add more images to the precache.
Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.
Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.
The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.
When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.
function preloadImages(array, waitForOtherResources, timeout) {
var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
if (!preloadImages.list) {
preloadImages.list = [];
}
if (!waitForOtherResources || document.readyState === 'complete') {
loadNow();
} else {
window.addEventListener("load", function() {
clearTimeout(timer);
loadNow();
});
// in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
// then preload the images anyway after some timeout time
timer = setTimeout(loadNow, t);
}
function loadNow() {
if (!loaded) {
loaded = true;
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
img.onload = img.onerror = img.onabort = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = imgs[i];
}
}
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);
rbind()
needs the two object names to be the same. For example, the first object names: ID Age
, the next object names: ID Gender
,if you want to use rbind()
, it will print out:
names do not match previous names
I have encountered this error with a stray quotation mark. I use mapping software which will put quotation marks around text items when exporting comma-delimited files. Text which uses quote marks (e.g. ' = feet and " = inches) can be problematic when then induce delimiter collisions. Consider this example which notes that a 5-inch well log print is poor:
UWI_key,Latitude,Longitude,Remark
US42051316890000,30.4386484,-96.4330734,"poor 5""
Using 5"
as shorthand for 5 inch
ends up throwing a wrench in the works. Excel will simply strip off the extra quote mark, but Pandas breaks down without the error_bad_lines=False
argument mentioned above.
use split
Split a file into fixed-size pieces, creates output files containing consecutive sections of INPUT (standard input if none is given or INPUT is `-')
Syntax
split [options] [INPUT [PREFIX]]
I use something like this...
#include <algorithm>
template <typename T>
const bool Contains( std::vector<T>& Vec, const T& Element )
{
if (std::find(Vec.begin(), Vec.end(), Element) != Vec.end())
return true;
return false;
}
if (Contains(vector,item))
blah
else
blah
...as that way it's actually clear and readable. (Obviously you can reuse the template in multiple places).
I combined two of the previous answers (jsfiddle).
input {
/* round the corners */
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
}
input:focus {
outline:none;
border: 1px solid #4195fc;
/* create a BIG glow */
box-shadow: 0px 0px 14px #4195fc;
-moz-box-shadow: 0px 0px 14px #4195fc;
-webkit-box-shadow: 0px 0px 14px #4195fc;
}?
The only sane way to update a table of 120M records is with a SELECT
statement that populates a second table. You have to take care when doing this. Instructions below.
Simple Case
For a table w/out a clustered index, during a time w/out concurrent DML:
SELECT *, new_col = 1 INTO clone.BaseTable FROM dbo.BaseTable
If you can't create a clone schema, a different table name in the same schema will do. Remember to rename all your constraints and triggers (if applicable) after the switch.
Non-simple Case
First, recreate your BaseTable
with the same name under a different schema, eg clone.BaseTable
. Using a separate schema will simplify the rename process later.
Then, test your insert w/ 1000 rows:
-- assuming an IDENTITY column in BaseTable
SET IDENTITY_INSERT clone.BaseTable ON
GO
INSERT clone.BaseTable WITH (TABLOCK) (Col1, Col2, Col3)
SELECT TOP 1000 Col1, Col2, Col3 = -1
FROM dbo.BaseTable
GO
SET IDENTITY_INSERT clone.BaseTable OFF
Examine the results. If everything appears in order:
This will take a while, but not nearly as long as an update. Once it completes, check the data in the clone table to make sure it everything is correct.
Then, recreate all non-clustered primary keys/unique constraints/indexes and foreign key constraints (in that order). Recreate default and check constraints, if applicable. Recreate all triggers. Recreate each constraint, index or trigger in a separate batch. eg:
ALTER TABLE clone.BaseTable ADD CONSTRAINT UQ_BaseTable UNIQUE (Col2)
GO
-- next constraint/index/trigger definition here
Finally, move dbo.BaseTable
to a backup schema and clone.BaseTable
to the dbo schema (or wherever your table is supposed to live).
-- -- perform first true-up operation here, if necessary
-- EXEC clone.BaseTable_TrueUp
-- GO
-- -- create a backup schema, if necessary
-- CREATE SCHEMA backup_20100914
-- GO
BEGIN TRY
BEGIN TRANSACTION
ALTER SCHEMA backup_20100914 TRANSFER dbo.BaseTable
-- -- perform second true-up operation here, if necessary
-- EXEC clone.BaseTable_TrueUp
ALTER SCHEMA dbo TRANSFER clone.BaseTable
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() -- add more info here if necessary
ROLLBACK TRANSACTION
END CATCH
GO
If you need to free-up disk space, you may drop your original table at this time, though it may be prudent to keep it around a while longer.
Needless to say, this is ideally an offline operation. If you have people modifying data while you perform this operation, you will have to perform a true-up operation with the schema switch. I recommend creating a trigger on dbo.BaseTable
to log all DML to a separate table. Enable this trigger before you start the insert. Then in the same transaction that you perform the schema transfer, use the log table to perform a true-up. Test this first on a subset of the data! Deltas are easy to screw up.
Note that reversing the whole string (either with the rbegin()
/rend()
range constructor or with std::reverse
) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
Install
npm i graph-fs
Use
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
const names = directory.children // <--
.filter(node => node.is.directory)
.map(directory => directory.name);
You can kill two birds with one regex stone:
>>> r = """
... \n\tName: John Smith
... \n\t Home: Anytown USA
... \n\t Phone: 555-555-555
... \n\t Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>>
I don't think you want an OrderedDict. It sounds like you'd prefer a SortedDict, that is a dict that maintains its keys in sorted order. The sortedcontainers module provides just such a data type. It's written in pure-Python, fast-as-C implementations, has 100% coverage and hours of stress.
Installation is easy with pip:
pip install sortedcontainers
Note that if you can't pip install
then you can simply pull the source files from the open-source repository.
Then you're code is simply:
from sortedcontainers import SortedDict
myDic = SortedDict({10: 'b', 3:'a', 5:'c'})
sorted_list = list(myDic.keys())
The sortedcontainers module also maintains a performance comparison with other popular implementations.
This comment syntax should work for you:
@* enter comments here *@
You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out
attribute to be the supplied PrintStream value.
There are analogous methods (setIn
and setErr
) for changing the standard input and error streams; refer to the java.lang.System
javadocs for details.
A more general version of the above is this:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append
is true
, the stream will append to an existing file instead of truncating it. If autoflush
is true
, the output buffer will be flushed whenever a byte array is written, one of the println
methods is called, or a \n
is written.
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not "logging" then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an out
stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out
.
Changing System.out
may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out
and System.err
, but you could be unlucky.)
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
Extract (refactor) your statements. And use the magic of and
and or
to decide when to short-circuit.
def a():
try: # a code
except: pass # or raise
else: return True
def b():
try: # b code
except: pass # or raise
else: return True
def c():
try: # c code
except: pass # or raise
else: return True
def d():
try: # d code
except: pass # or raise
else: return True
def main():
try:
a() and b() or c() or d()
except:
pass
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
This must be used with care because an override on the objects __sizeof__ might be misleading.
Using the bregman.suite, some tests with sys.getsizeof output a copy of an array object (data) in an object instance as being bigger than the object itself (mfcc).
>>> mfcc = MelFrequencyCepstrum(filepath, params)
>>> data = mfcc.X[:]
>>> sys.getsizeof(mfcc)
64
>>> sys.getsizeof(mfcc.X)
>>>80
>>> sys.getsizeof(data)
80
>>> mfcc
<bregman.features.MelFrequencyCepstrum object at 0x104ad3e90>
createdb
is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so:
create database [databasename];
Note: be sure to always end your SQL statements with ;
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
I have been working on Swagger equivalent documentation library called Springfox
nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer
has been implemented by class WebMvcConfigurationSupport
class which we can directly extend.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebConfig extends WebMvcConfigurationSupport { }
And this is how I have used it for setting my resource handling mechanism as follows -
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
How are you setting blob to DB? You should do:
//imagine u have a a prepared statement like:
PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
byte[] buff = blobString.getBytes();
myBlob.putBytes(1,buff);
ps.setBlob(1, myBlob);
ps.executeUpdate();
In mysqli_query(first parameter should be connection,your sql statement) so
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');
but best practice is
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);
Trailing backtick character, i.e.,
&"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
-verb:sync `
-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
-dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
White space matters. The required format is Space`Enter.
float
and double
are floating binary point types. In other words, they represent a number like this:
10001.10010110011
The binary number and the location of the binary point are both encoded within the value.
decimal
is a floating decimal point type. In other words, they represent a number like this:
12345.65789
Again, the number and the location of the decimal point are both encoded within the value – that's what makes decimal
still a floating point type instead of a fixed point type.
The important thing to note is that humans are used to representing non-integers in a decimal form, and expect exact results in decimal representations; not all decimal numbers are exactly representable in binary floating point – 0.1, for example – so if you use a binary floating point value you'll actually get an approximation to 0.1. You'll still get approximations when using a floating decimal point as well – the result of dividing 1 by 3 can't be exactly represented, for example.
As for what to use when:
For values which are "naturally exact decimals" it's good to use decimal
. This is usually suitable for any concepts invented by humans: financial values are the most obvious example, but there are others too. Consider the score given to divers or ice skaters, for example.
For values which are more artefacts of nature which can't really be measured exactly anyway, float
/double
are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy". Floating binary point types are much faster to work with than decimals.
#1- Run this to configure the region once and for all:
aws configure set region us-east-1 --profile admin
Change admin
next to the profile if it's different.
Change us-east-1
if your region is different.
#2- Run your command again:
aws ecs list-container-instances --cluster default
I have the same warning (it's make my app cannot build). When I add C function
in Objective-C's .m file
, But forgot to declared it at .h
file.
I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:
git fetch
which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.
Found the reason!! If Android Studio has a proxy server setting and can't reach the server then it takes a long time to build, probably its trying to reach the proxy server and waiting for a timeout. When I removed the proxy server setting its working fine.
Removing proxy: File > Settings > Appearance & Behavior > System settings > HTTP Proxy
Worth noting that on my Epic 4G Touch I had to set up the webview to use WebChromeClient before any of the javascript android calls worked.
webView.setWebChromeClient(new WebChromeClient());
When you've written something that isn't allowed by the language standard (and therefore can't really be well-defined behaviour, which is reason enough to not do it) but happens to map to some kind of executable if fed naïvely to the compiling engine, then -fpermissive
will do just that instead of stopping with this error message. In some cases, the program will then behave exactly as you originally intended, but you definitely shouldn't rely on it unless you have some very special reason not to use some other solution.
Depending on what you want to do with the list, you may not even need to cast it to a List<Customer>
. If you only want to add Customer
objects to the list, you could declare it as follows:
...
List<Object> list = getList();
return (List<? super Customer>) list;
This is legal (well, not just legal, but correct - the list is of "some supertype to Customer"), and if you're going to be passing it into a method that will merely be adding objects to the list then the above generic bounds are sufficient for this.
On the other hand, if you want to retrieve objects from the list and have them strongly typed as Customers - then you're out of luck, and rightly so. Because the list is a List<Object>
there's no guarantee that the contents are customers, so you'll have to provide your own casting on retrieval. (Or be really, absolutely, doubly sure that the list will only contain Customers
and use a double-cast from one of the other answers, but do realise that you're completely circumventing the compile-time type-safety you get from generics in this case).
Broadly speaking it's always good to consider the broadest possible generic bounds that would be acceptable when writing a method, doubly so if it's going to be used as a library method. If you're only going to read from a list, use List<? extends T>
instead of List<T>
, for example - this gives your callers much more scope in the arguments they can pass in and means they are less likely to run into avoidable issues similar to the one you're having here.
I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.
My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.
To create a function with a completion handler
func yourFunctionName(finished: () -> Void) {
print("Doing something!")
finished()
}
to use the function
override func viewDidLoad() {
yourFunctionName {
//do something here after running your function
print("Tada!!!!")
}
}
Your output will be
Doing something
Tada!!!
Hope this helps!
Your regexp seems to validate both the file name and the extension. Is that what you need? I'll assume it's just the extension and would use a regexp like this:
\.(jpg|gif|doc|pdf)$
And set the matching to be case insensitive.