I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --
df <- df [(!(df$A=="no") & !(df$A=="unknown")),]
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
Python 2.6 added a new strftime/strptime macro %f
, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
Edit: I never really work with the time
module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using datetime
, like this:
>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000
In my case I copied a ssl config from another machine and had the wrong IP in <VirtualHost wrong.ip.addr.here:443>
. Changed IP to what it should be, restarted httpd and the site loaded over SSL as expected.
Please try to remove the preceeding spaces before EOF
:-
/var/mail -s "$SUBJECT" "$EMAIL" <<-EOF
Using <tab>
instead of <spaces>
for ident AND using <<-EOF works fine.
The "-"
removes the <tabs>
, not <spaces>
, but at least this works.
try this
echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";
It's not an exact duplicate (so far as I can find), but this is a common problem.
display:block
is what you need. but you should read the spec to understand why.
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName
as @Slogmeister Extraordinaire Quoted is correct.
One need to have 1> File already present with columns 2> One need to have Office installed
Errors faced
Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"."
Msg 15281, Level 16, State 1, Line 1 SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', search for 'Ad Hoc Distributed Queries' in SQL Server Books Online.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 0
RECONFIGURE
GO
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
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;
proxy_set_header X-Forwarded-Host $server_name;
}
}
I had the same trouble finding out the correct path for sessions on a Mac. All in all, I found out that the CLI PHP has a different temporary directory than the Apache module: Apache used /var/tmp
, while CLI used something like /var/folders/kf/hk_dyn7s2z9bh7y_j59cmb3m0000gn/T
. But both ways, sys_get_temp_dir()
got me the right path when session.save_path
is empty. Using PHP 5.5.4.
The char is a fixed-length character data type, the varchar is a variable-length character data type.
Because char is a fixed-length data type, the storage size of the char value is equal to the maximum size for this column. Because varchar is a variable-length data type, the storage size of the varchar value is the actual length of the data entered, not the maximum size for this column.
You can use char when the data entries in a column are expected to be the same size. You can use varchar when the data entries in a column are expected to vary considerably in size.
With openssl
:
openssl x509 -enddate -noout -in file.pem
The output is on the form:
notAfter=Nov 3 22:23:50 2014 GMT
Also see MikeW's answer for how to easily check whether the certificate has expired or not, or whether it will within a certain time period, without having to parse the date above.
<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
print( set( first_list + second_list ) )
Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ?
and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.
For example:
wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"
will download into a file named, ?source=typ_redirect
.
As you can see, knowing a thing or two about URLs helps to understand wget
.
I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:
wget "(source url)" -O (directory where HD was mounted)/isofile.iso"
One could figure the correct URL by finding at what point wget
downloads into a file named index.html
(the default file), and has the correct size/other attributes of the file you need shown by the following command:
wget "(source url)"
Once that URL and source file is correct and it is downloading into index.html
, you can stop the download (ctrl + z) and change the output file by using:
-O "<specified download directory>/filename.extension"
after the source url.
In my case this results in downloading an ISO and storing it as a binary file under isofile.iso
, which hopefully mounts.
Yes, it is possible and you have answered it! About good practises, I think it is better to launch commands from files and not directly from your code. So you have to make Java execute the list of commands (or one command) in an existing .bat
, .sh
, .ksh
... files.
Here is an example of executing a list of commands in a file MyFile.sh
:
String[] cmd = { "sh", "MyFile.sh", "\pathOfTheFile"};
Runtime.getRuntime().exec(cmd);
In addition to the answers above, there's the shorthand way to do it:
ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist";
-q
is quiet mode, it will suppress warnings and messages.
As @Mat mentioned, one advantage of testing like this is that you can easily swap out the -f
for any test operator you like: -nt
, -d
, -s
etc...
Test Operators: http://tldp.org/LDP/abs/html/fto.html
For MS SQL Server, you can use:
where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)
This fixed it for me:
.navbar-wrapper {
z-index: 11;
}
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
By using new version of jquery (1.8.2), I amend the current code like in this links http://jsfiddle.net/q5EXG/97/
By using the same code, I just change from jQuery to '$'
<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
$('#send-thoughts').click(function()
{ var thought = $('#message').val();
alert(thought);
});
Try this:
@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b
:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
Revision
To have it perform the unzip on each zip file creating a folder for each use:
@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b
If you don't want it to create a folder for each zip, change
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
to
Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"
React makes this even easier for you. Instead of defining selected
on each option, you can (and should) simply write value={optionsState}
on the select tag itself:
<select value={optionsState}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
For more info, see the React select tag doc.
Also, React automatically understands booleans for this purpose, so you can simply write (note: not recommended)
<option value={option.value} selected={optionsState == option.value}>{option.label}</option>
and it will output 'selected' appropriately.
The following solution does not use inline blocks. However, it requires two helper divs:
.ca-outer {_x000D_
overflow: hidden;_x000D_
background: #FFC;_x000D_
}_x000D_
.ca-inner {_x000D_
float: left;_x000D_
position: relative;_x000D_
left: 50%;_x000D_
background: #FDD;_x000D_
}_x000D_
.content {_x000D_
float: left;_x000D_
position: relative;_x000D_
left: -50%;_x000D_
background: #080;_x000D_
}_x000D_
/* examples */_x000D_
div.content > div {_x000D_
float: left;_x000D_
margin: 10px;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #FFF;_x000D_
}_x000D_
ul.content {_x000D_
padding: 0;_x000D_
list-style-type: none;_x000D_
}_x000D_
ul.content > li {_x000D_
margin: 10px;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="ca-outer">_x000D_
<div class="ca-inner">_x000D_
<div class="content">_x000D_
<div>Box 1</div>_x000D_
<div>Box 2</div>_x000D_
<div>Box 3</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="ca-outer">_x000D_
<div class="ca-inner">_x000D_
<ul class="content">_x000D_
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>_x000D_
<li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>_x000D_
<li>Suspendisse iaculis risus ut dapibus cursus.</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
My solution is inspired from the last comment. This is the code of invisible.html
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>
The clear code of invisible_debut.js is:
$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});
Notice that at the end I'm removing the created script. invisible.js is:
$(document).ready(function(){
alert('try to find in the source the js script which did this alert!');
document.write('It disappeared, my dear!');});
invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.
Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.
You just need to toggle the value of "isReplyFormOpen" on ng-click event
<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-show="isReplyFormOpen" id="replyForm">
</div>
I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:
In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.
I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.
As others noted, for Nexus 4, you can also try this fix.
The other answers here are great references on using proguard. However, I haven't seen an issue discussed that I ran into that was a mind bender. After you generate a signed release .apk, it's put in the /release
folder in your app but my app had an apk that wasn't in the /release
folder. Hence, I spent hours decompiling the wrong apk wondering why my proguard changes were having no affect. Hope this helps someone!
To change color of the font colour, first select attributed instead of plain like in the image below
You then need to select the text in the attributed field and then select the color button on the right-hand side of the alignments. This will change the color.
I had a similar, quite complex problem with a fluid layout, where the right column had a fixed width and the left one had a flexible width. My fixed container should have the same width as the flexible column. Here is my solution:
HTML
<div id="wrapper">
<div id="col1">
<div id="fixed-outer">
<div id="fixed-inner">inner</div>
</div>
COL1<br />Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</div>
<div id="col2">COL2</div>
</div>
CSS
#wrapper {
padding-left: 20px;
}
#col1 {
background-color: grey;
float: left;
margin-right: -200px; /* #col2 width */
width: 100%;
}
#col2 {
background-color: #ddd;
float: left;
height: 400px;
width: 200px;
}
#fixed-outer {
background: yellow;
border-right: 2px solid red;
height: 30px;
margin-left: -420px; /* 2x #col2 width + #wrapper padding-left */
overflow: hidden;
padding-right: 200px; /* #col2 width */
position: fixed;
width: 100%;
}
#fixed-inner {
background: orange;
border-left: 2px solid blue;
border-top: 2px solid blue;
height: 30px;
margin-left: 420px; /* 2x #col2 width + #wrapper padding-left */
position: absolute;
width: 100%;
}
Live Demo: http://jsfiddle.net/hWCub/
following code will serialize sqlalchemy result to json.
import json
from collections import OrderedDict
def asdict(self):
result = OrderedDict()
for key in self.__mapper__.c.keys():
if getattr(self, key) is not None:
result[key] = str(getattr(self, key))
else:
result[key] = getattr(self, key)
return result
def to_array(all_vendors):
v = [ ven.asdict() for ven in all_vendors ]
return json.dumps(v)
Calling fun,
def all_products():
all_products = Products.query.all()
return to_array(all_products)
Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage :
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
When converting a dictionary into a pandas dataframe where you want the keys to be the columns of said dataframe and the values to be the row values, you can do simply put brackets around the dictionary like this:
>>> dict_ = {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
>>> pd.DataFrame([dict_])
key 1 key 2 key 3
0 value 1 value 2 value 3
It's saved me some headaches so I hope it helps someone out there!
EDIT: In the pandas docs one option for the data
parameter in the DataFrame constructor is a list of dictionaries. Here we're passing a list with one dictionary in it.
An expression of non-boolean type specified in a context where a condition is expected
I also got this error when I forgot to add ON condition when specifying my join clause.
If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave
because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct
in documentation that says
Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.
so I changed the hdfs-site.xml
into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml
:
<configuration>
<property>
<name>dfs.safemode.threshold.pct</name>
<value>0</value>
</property>
</configuration>
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
This is pretty much as close as you'll get if you want to use the ActionBar
APIs. I'm not sure you can place a colorstrip above the ActionBar
without doing some weird Window
hacking, it's not worth the trouble. As far as changing the MenuItems
goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.
<style name="MyTheme" parent="android:Theme.Holo.Light">
<item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>
<style name="MyActionButtonStyle" parent="Widget.ActionButton">
<item name="android:minWidth">28dip</item>
</style>
Here's how to inflate and add the custom layout to your ActionBar
.
// Inflate your custom layout
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.action_bar,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
// You customization
final int actionBarColor = getResources().getColor(R.color.action_bar);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));
final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
actionBarTitle.setText("Index(2)");
final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
actionBarSent.setText("Sent");
final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
actionBarStaff.setText("Staff");
final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
actionBarLocations.setText("HIPPA Locations");
Here's the custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:orientation="horizontal"
android:paddingEnd="8dip" >
<Button
android:id="@+id/action_bar_title"
style="@style/ActionBarButtonWhite" />
<Button
android:id="@+id/action_bar_sent"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_staff"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_locations"
style="@style/ActionBarButtonOffWhite" />
</LinearLayout>
Here's the color strip layout: To use it, just use merge
in whatever layout you inflate in setContentView
.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/colorstrip"
android:background="@android:color/holo_blue_dark" />
Here are the Button
styles:
<style name="ActionBarButton">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@null</item>
<item name="android:ellipsize">end</item>
<item name="android:singleLine">true</item>
<item name="android:textSize">@dimen/text_size_small</item>
</style>
<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/white</item>
</style>
<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/off_white</item>
</style>
Here are the colors and dimensions I used:
<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>
<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>
<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>
If you want to customize it more than this, you may consider not using the ActionBar
at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.
If you choose to forgo the ActionBar
and use your own layout instead, you should be sure to add action-able Toasts
when users long press your "MenuItems". This can be easily achieved using this Gist.
SELECT ID
FROM A
WHERE NOT EXISTS( SELECT 1
FROM B
WHERE B.ID = A.ID
)
I think it is important question and it is not answered yet (the OP seems to already know about shift operators). Let me try to answer, the >> operator in your example is used for two different purposes. In c++ terms this operator is overloaded. In the first example it is used as bitwise operator (left shift), while in the second scenario it is merely used as output redirection. i.e.
2 << 5 # shift to left by 5 bits
2 >> 5 # shift to right by 5 bits
print >> obj, "Hello world" # redirect the output to obj,
with open('foo.txt', 'w') as obj:
print >> obj, "Hello world" # hello world now saved in foo.txt
In python 3 it is possible to give the file argument directly as follows:
print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt
Just an alternative to the code by rkosegi,
BEGIN
.. Declare statements ..
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
.. set any flags etc eg. SET @flag = 0; ..
ROLLBACK;
END;
START TRANSACTION;
.. Query 1 ..
.. Query 2 ..
.. Query 3 ..
COMMIT;
.. eg. SET @flag = 1; ..
END
It's really surprising to me that the redirection methods in ProcessBuilder
don't accept an OutputStream
, only File
. Yet another proof of forced boilerplate code that Java forces you to write.
That said, let's look at a list of comprehensive options:
inheritIO
will do the job.redirect*(file)
.InputStream
in a separate thread. See the answers that use a Runnable
or CompletableFuture
. You can also adapt the code below to do this.PrintWriter
, that may or may not be the stdout (very useful for testing), you can do the following:static int execute(List<String> args, PrintWriter out) {
ProcessBuilder builder = new ProcessBuilder()
.command(args)
.redirectErrorStream(true);
Process process = null;
boolean complete = false;
try {
process = builder.start();
redirectOut(process.getInputStream(), out)
.orTimeout(TIMEOUT, TimeUnit.SECONDS);
complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
LOG.warn("Thread was interrupted", e);
} finally {
if (process != null && !complete) {
LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
process = process.destroyForcibly();
}
}
return process != null ? process.exitValue() : 1;
}
private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
return CompletableFuture.runAsync(() -> {
try (
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
) {
bufferedReader.lines()
.forEach(out::println);
} catch (IOException e) {
LOG.error("Failed to redirect process output", e);
}
});
}
Advantages of the code above over the other answers thus far:
redirectErrorStream(true)
redirects the error stream to the output stream, so that we only have to bother with one.CompletableFuture.runAsync
runs from the ForkJoinPool
. Note that this code doesn't block by calling get
or join
on the CompletableFuture
but sets a timeout instead on its completion (Java 9+). There's no need for CompletableFuture.supplyAsync
because there's nothing really to return from the method redirectOut
.BufferedReader.lines
is simpler than using a while
loop.@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion
So here it is
.andExpect(content().string("\"Username already taken - please try with different username\""));
Of course my assertion fail:
java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">
because:
MockHttpServletResponse:
Body = "Something gone wrong"
So this is proof that it works!
Maybe a bit late, but I found this answer looking over the internet. It could help others with the same problem.
$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q
Now you should be able to log in as root in phpmyadmin.
(Found here.)
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
I have used an html template. In this template's custom.js file, there was a function like this:
jQuery(document).ready(function($) {
$(window).on('load', function() {
//...
});
});
But this function was not working when I go to back after go to other page.
So, I tried this and it has worked:
jQuery(document).ready(function($) {
//...
});
//Window Load Start
window.addEventListener('load', function() {
jQuery(document).ready(function($) {
//...
});
});
Now, I have 2 "ready" function but it doesn't give any error and the page is working very well.
Nevertheless, I have to declare that it has tested on Windows 10 - Opera v53 and Edge v42 but no other browsers. Keep in mind this...
Note: jquery version was 3.3.1 and migrate version was 3.0.0
Languages which allow multiple returns usually just convert the multiple values into a data structure.
For example, in Python you can return multiple values. However, they're actually just being returned as one tuple.
So you can return multiple values in PHP by just creating a simple array and returning that.
Below mechanism helps in redirecting multiple lines to file. Keep complete string under "
so that we can redirect values of the variable.
#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt
Content of a.txt
is
line 1, 2.6.39
line 2,
Content of b.txt
is
line 2, ${kernel}
line 2,
Now for the missing class problem.
I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.
This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.
Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:
NOTE
Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.
What you've done here accomplishes two things:
See your auto-generated Fragment
created by Android Studio. When you created the new Fragment
, Studio stubbed a bunch of code for you. At the bottom of the auto-generated template there is an inner interface definition called OnFragmentInteractionListener
. Your Activity
needs to implement this interface. This is the recommended pattern for your Fragment
to notify your Activity
of events so it can then take appropriate action, such as load another Fragment
. See this page for details, look for the "Creating event callbacks for the Activity" section: http://developer.android.com/guide/components/fragments.html
This is from : Script to change password on linux servers over ssh
The script below will need to be saved as a file (eg ./passwdWrapper
) and made executable (chmod u+x ./passwdWrapper)
#!/usr/bin/expect -f
#wrapper to make passwd(1) be non-interactive
#username is passed as 1st arg, passwd as 2nd
set username [lindex $argv 0]
set password [lindex $argv 1]
set serverid [lindex $argv 2]
set newpassword [lindex $argv 3]
spawn ssh $serverid passwd
expect "assword:"
send "$password\r"
expect "UNIX password:"
send "$password\r"
expect "password:"
send "$newpassword\r"
expect "password:"
send "$newpassword\r"
expect eof
Then you can run ./passwdWrapper $user $password $server $newpassword
which will actually change the password.
Note: This requires that you install expect
on the machine from which you will be running the command. (sudo apt-get install expect
) The script works on CentOS 5/6 and Ubuntu 14.04, but if the prompts in passwd
change, you may have to tweak the expect
lines.
I find I rarely have need to use getCanonicalPath()
but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdir
System property returns, then this method will return the "full" filename.
This is what I use
args = {
'batch_size': 32,
'workers': 4,
'train_dir': 'train',
'val_dir': 'val',
'lr': 1e-3,
'momentum': 0.9,
'weight_decay': 1e-4
}
args = namedtuple('Args', ' '.join(list(args.keys())))(**args)
print (args.lr)
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
Update for laravel 5.4 ----
All answers have have used the HTML class for laravel but I guess it has been depreciated now in laravel 5.4, so Put your css and js files in public->css/js And reference them in your html using
<link href="css/css.common.css" rel="stylesheet" >
What about Console.Readline();
?
You might be better off using os.walk()
for this.
os.listdir()
doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using os.walk()
to recursively remove a directory here, and hints on how to adapt it to your circumstances.
I had the same issue during building my app in AppVeyor.
c:\php
echo extension=php_openssl.dll >> c:\php\php.ini
echo curl.cainfo=c:\php\cacert.pem >> c:\php\php.ini
How I do it in Windows 10
Go to your folder directory you want to open in git bash like so
After you have reached the folder simply type git bash
in the top navigation area like so and hit enter.
A git bash for the destined folder will open for you.
Hope that helps.
#outerDiv{_x000D_
width: 500px;_x000D_
height: 500px;_x000D_
position:relative;_x000D_
background:grey;_x000D_
display:flex;_x000D_
justify-content:center;_x000D_
align-items:center;_x000D_
}_x000D_
_x000D_
#innerDiv{_x000D_
background:cyan;_x000D_
width: 284px;_x000D_
height: 290px;_x000D_
_x000D_
_x000D_
}
_x000D_
<div id="outerDiv">_x000D_
<div id="innerDiv">Inner Div_x000D_
</div>_x000D_
</div>
_x000D_
you can do it by simply adding css style mentioned above. All the best. For any query please comment
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
You can try a simple kernel and the filter2D function, e.g. in Python:
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
im = cv2.filter2D(im, -1, kernel)
Wikipedia has a good overview of kernels with some more examples here - https://en.wikipedia.org/wiki/Kernel_(image_processing)
In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.
According to the sqlite docs about table creation, using the create table as select produces a new table without constraints and without primary key.
However, the documentation also says that primary keys and unique indexes are logically equivalent (see constraints section):
In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database. (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the following schemas are logically equivalent:
CREATE TABLE t1(a, b UNIQUE); CREATE TABLE t1(a, b PRIMARY KEY); CREATE TABLE t1(a, b); CREATE UNIQUE INDEX t1b ON t1(b);
So, even if you cannot alter your table definition through SQL alter syntax, you can get the same primary key effect through the use an unique index.
Also, any table (except those created without the rowid syntax) have an inner integer column known as "rowid". According to the docs, you can use this inner column to retrieve/modify record tables.
Just remove the width from both divs.
A div
is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.
I have added an example with a textarea
on jsfiddle.
Updated example with an input.
Think of it like this: the List
interface has methods like add(int index, E element)
, set(int index, E element)
. The contract is that once you added an element at position X you will find it there unless you add or remove elements before it.
If any list implementation would store elements in some order other than based on the index, the above list methods would make no sense.
For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:
new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());
...or here's an easier to read version:
new org.hibernate.jdbc.util.BasicFormatterImpl().format(
(new org.hibernate.loader.criteria.CriteriaJoinWalker(
(org.hibernate.persister.entity.OuterJoinLoadable)
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
new org.hibernate.loader.criteria.CriteriaQueryTranslator(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
((org.hibernate.impl.CriteriaImpl)crit),
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
(org.hibernate.impl.CriteriaImpl)crit,
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
)
).getSQLString()
);
Notes:
crit
. If named differently, do a search and replace.getEnabledFilters
rather than getLoadQueryInfluencers()
for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)You need to use a SimpleDateFormat
(dd-MM-yyyy
will be the format) to parse the 2 input strings to Date
objects and then use the Date#before(otherDate)
(or) Date#after(otherDate)
to compare them.
Try to implement the code yourself.
The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.
I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.
See sync-request: https://github.com/ForbesLindesay/sync-request
Example:
var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());
You can try my answer https://github.com/SCENEE/FloatingPanel. It provides a container view controller to display a "bottom sheet" interface.
It's easy to use and you don't mind any gesture recognizer handling! Also you can track a scroll view's(or the sibling view) in a bottom sheet if needed.
This is a simple example. Please note that you need to prepare a view controller to display your content in a bottom sheet.
import UIKit
import FloatingPanel
class ViewController: UIViewController {
var fpc: FloatingPanelController!
override func viewDidLoad() {
super.viewDidLoad()
fpc = FloatingPanelController()
// Add "bottom sheet" in self.view.
fpc.add(toParent: self)
// Add a view controller to display your contents in "bottom sheet".
let contentVC = ContentViewController()
fpc.set(contentViewController: contentVC)
// Track a scroll view in "bottom sheet" content if needed.
fpc.track(scrollView: contentVC.tableView)
}
...
}
Here is another example code to display a bottom sheet to search a location like Apple Maps.
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
Based on your requirement that you want to put a border around an arbitrary block of MxN cells there really is no easier way of doing it without using Javascript. If your cells are fixed with you can use floats but this is problematic for other reasons. what you're doing may be tedious but it's fine.
Ok, if you're interested in a Javascript solution, using jQuery (my preferred approach), you end up with this fairly scary piece of code:
<html>
<head>
<style type="text/css">
td.top { border-top: thin solid black; }
td.bottom { border-bottom: thin solid black; }
td.left { border-left: thin solid black; }
td.right { border-right: thin solid black; }
</style>
<script type="text/javascript" src="jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
box(2, 1, 2, 2);
});
function box(row, col, height, width) {
if (typeof height == 'undefined') {
height = 1;
}
if (typeof width == 'undefined') {
width = 1;
}
$("table").each(function() {
$("tr:nth-child(" + row + ")", this).children().slice(col - 1, col + width - 1).addClass("top");
$("tr:nth-child(" + (row + height - 1) + ")", this).children().slice(col - 1, col + width - 1).addClass("bottom");
$("tr", this).slice(row - 1, row + height - 1).each(function() {
$(":nth-child(" + col + ")", this).addClass("left");
$(":nth-child(" + (col + width - 1) + ")", this).addClass("right");
});
});
}
</script>
</head>
<body>
<table cellspacing="0">
<tr>
<td>no border</td>
<td>no border here either</td>
</tr>
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
<tr>
<td colspan="2">once again no borders</td>
</tr>
</tfoot>
</table>
</html>
I'll happily take suggestions on easier ways to do this...
example 1
class TestClass{
public function __call($name,$arg){
call_user_func($name,$arg);
}
}
class test {
public function newTest(){
function bigTest(){
echo 'Big Test Here';
}
function smallTest(){
echo 'Small Test Here';
}
$obj=new TestClass;
return $obj;
}
}
$rentry=new test;
$rentry->newTest()->bigTest();
example2
class test {
public function newTest($method_name){
function bigTest(){
echo 'Big Test Here';
}
function smallTest(){
echo 'Small Test Here';
}
if(function_exists( $method_name)){
call_user_func($method_name);
}
else{
echo 'method not exists';
}
}
}
$obj=new test;
$obj->newTest('bigTest')
This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.
If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.
Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception
Cheers,
Use "-Dspring-boot.run.profiles=foo,local" in Intellij IDEA. It's working. Its sets 2 profiles "foo and local".
Verified with boot version "2.3.2.RELEASE" & Intellij IDEA CE 2019.3.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
For leading and trailing whitespace:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
It seems that your Java code is using IPv6 instead of IPv4. Please try to use 127.0.0.1
instead of localhost
. Ex.: Your connection string should be
jdbc:mysql://127.0.0.1:3306/expeditor?zeroDateTimeBehavior=convertToNull&user=root&password=onelife
P.S.: Please update the URL connection string.
Using border-collapse: separate; didn't work for me, because I only need a margin in-between the table cells not on the sides of the table.
I came up with the next solution:
-CSS
.tableDiv{
display: table;
}
.cellSeperator {
display: table-cell;
width: 20px;
}
.cell1 {
display: table-cell;
width: 200px;
}
.cell2 {
display: table-cell;
width: 50px;
}
-HTML
<div class="tableDiv">
<div class="cell1"></div>
<div class="cellSeperator"></div>
<div class="cell2"></div>
</div>
After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.
It's incorrect to use zeros in date or in datetime, just put null instead of zeros.
Immediately after your execute statement you can have an if statement. For example
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
Thank You All! I am able to to load Select List as per MVC now My Working Code is below:
HTML+MVC Code in View:-
<tr>
<th>@Html.Label("Country")</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
</tr>
<tr>
<th>@Html.LabelFor(x=>x.Province)</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
</tr>
Created a Controller under "UTIL" folder: Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedAvail.Applications.MedProvision.Web.Util
{
public class SelectListItemHelper
{
public static IEnumerable<SelectListItem> GetProvincesList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "California", Value = "B"},
new SelectListItem{Text = "Alaska", Value = "B"},
new SelectListItem{Text = "Illinois", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
public static IEnumerable<SelectListItem> GetCountryList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "United States", Value = "B"},
new SelectListItem{Text = "Canada", Value = "B"},
new SelectListItem{Text = "United Kingdom", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
}
}
And its working COOL now :-)
Thank you!!
You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:
{
command1
command2
command3
command4
} > file1
{
command5
command6
command7
command8
} > file2
Make sure you are in the project directory before running bundle install
. For example, after running rails new myproject
, you will want to cd myproject
before running bundle install
.
x = float(raw_input("enter number between 0 and 1: "))
p = 0
while ((2**p)*x) %1 != 0:
p += 1
# print p
num = int (x * (2 ** p))
# print num
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num / 2
for i in range (p - len(result)):
result = '0' + result
result = result[0:-p] + '.' + result[-p:]
print result #this will print result for the decimal portion
For versions previous to FreeMarker 2.3.7
You can not use ??
to handle missing values, the old syntax is:
<#if userName?exists>
Hi ${userName}, How are you?
</#if>
You can also use an exit variable if you want your code to be a bit more readable:
DECLARE @Flag int = 0
DECLARE @Done bit = 0
WHILE @Done = 0 BEGIN
SET @Flag = @Flag + 1
PRINT @Flag
IF @Flag >= 5 SET @Done = 1
END
This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.
In Bootstrap 5, the class btn-block
doesn't work anymore. But instead, you can add the class w-100
to the button to make it as wide as its container.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="row"><div class=" col-5 ">
<a class="btn btn-outline-primary w-100 " href="# "><span>Button 1</span></a>
</div><div class="col-5 ">
<a class=" btn btn-primary w-100 weiss " href="# "><span>Button 2</span></a>
</div></div>
_x000D_
This is a case that could have possibly occurred and what solved my error:
In the https://developers.facebook.com/quickstarts after you run
OSX/Linux:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
Windows:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
When Enter keystore password:
is asked you may have accidentally typed a wrong password, the default password is "android". Typing any other password will give you a different/wrong hash key. Paste the correct hash key in the Key Hashes
field on your app page
This solved my problem, hope this helps whoever made this particular error that I made
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
You forgot to use setState
. Example:
removePeople(e){
var array = this.state.people;
var index = array.indexOf(e.target.value); // Let's say it's Bob.
delete array[index];
this.setState({
people: array
})
},
But it's better to use filter
because it does not mutate array.
Example:
removePeople(e){
var array = this.state.people.filter(function(item) {
return item !== e.target.value
});
this.setState({
people: array
})
},
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
colorbox has such amazing features..loving it. Also like this one http://www.webappers.com/2008/03/05/galleria-simple-but-nice-jquery-image-gallery/
function function_one() {_x000D_
function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).
You can follow this answer to see many different ways to process CSV in C++.
In your case, the last call to getline
is actually putting the last field of the first line and then all of the remaining lines into the variable genero
. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:
getline(file, genero, file.widen('\n'));
or more succinctly:
getline(file, genero);
In addition, your check for file.good()
is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline()
call for ID
. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while
test to be based on the getline()
call for ID
itself (assuming each line is well formed).
while (getline(file, ID, ',')) {
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero);
cout << "Sexo: " << genero<< " " ;
}
For better error checking, you should check the result of each call to getline()
.
I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:
compile 'platforms:android:android-support-v4:23.1.1'
so I changed it to:
compile 'com.android.support:support-v4:23.1.1'
And it started working.
Sometimes you have to npm install package_name -g
for it to work.
Yes! You can definitely use onclick
or you can also use addEventListener
to listen a click event. In this code sample the onclick
event is in action(use).
HTML code:
<div class="container">
<p><output id="output">0</output></p>
<p><button type="button" id="btn">Increment</button></p>
</div>
Javascript code:
(function() {
var button = document.getElementById("btn")
var output = document.getElementById("output")
var number
var counter
function init() {
// Convert string to primitve number using parseInt()
number = parseInt(output.innerText)
/**
* Start counter by adding any number to start counting.
* In this case the output starts from 0 so to immediately
* invoke the button to increment the counter add 1 to start
* counting in natural number (counting numbers).
*/ counter = number + 1
function increment() {
// Increment counter
value = counter++
output.innerText = value
}
// Output the increment value for every click
button.onclick = increment
}
window.onload = init
})()
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
For updating multiple rows in a single query, you can try this
UPDATE table_name
SET
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end
if you don't need additional condition then remove and
part of this query
' Trying to find the amount of "." in the text
' if txtName looks like "hi...hi" then intdots will = 3
Dim test As String = txtName.Text
Dim intdots As Integer = 0
For i = 1 To test.Length
Dim inta As Integer = 0 + 1
Dim stra As String = test.Substring(inta)
If stra = "." Then
intdots = intdots + 1
End If
Next
txttest.text = intdots
You can use double splat operator which is available since Ruby 2.0:
h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}
Adding comment for anyone using Plesk having issues with any of the above as it was driving me crazy, setting session.gc_maxlifetime from your PHP script wont work as Plesk has it's own garbage collection script run from cron.
I used the solution posted on the link below of moving the cron job from hourly to daily to avoid this issue, then the top answer above should work:
mv /etc/cron.hourly/plesk-php-cleanuper /etc/cron.daily/
https://websavers.ca/plesk-php-sessions-timing-earlier-expected
There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
Server Error in '/' Application.
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:
{ SqlCommand cmd = new SqlCommand("select * from tblemployee",con); con.Open(); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind();
Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23
if your error is same like mine..just do this
right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..
For image data, I find it simpler to use canvas.toBlob
(asynchronous)
function b64toBlob(b64, onsuccess, onerror) {
var img = new Image();
img.onerror = onerror;
img.onload = function onload() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob(onsuccess);
};
img.src = b64;
}
var base64Data = 'data:image/jpg;base64,/9j/4AAQSkZJRgABAQA...';
b64toBlob(base64Data,
function(blob) {
var url = window.URL.createObjectURL(blob);
// do something with url
}, function(error) {
// handle error
});
Code used basic nav bootstrap
<!--MENU CENTER`enter code here` RESPONSIVE -->_x000D_
_x000D_
<div class="container-fluid">_x000D_
<div class="container logo"><h1>LOGO</h1></div>_x000D_
<nav class="navbar navbar-default menu">_x000D_
<div class="container-fluid">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar2"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="defaultNavbar2">_x000D_
<ul class="nav nav-justified" >_x000D_
<li><a href="#">Home</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container-fluid -->_x000D_
</nav>_x000D_
</div>_x000D_
<!-- END MENU-->
_x000D_
For formatting the price in another currency than the current one:
Mage::app()->getLocale()->currency('EUR')->toCurrency($price);
I've had a similar issue with one of my phones. I was unable to connect and use usb debugging on any of my computers. In the end, I had to restart the usb debugging on the phone manually [doing so using the Developer menu was not enough].
There's only one command you have to run on your phone [I did it using Terminal Emulator
app]:
adb usb
And that was it.
Hope this helps someone in the future.
Regarding the disabled color when piping:
Use --color
to avoid that coloring is disabled.
git diff --color | less -R
Or configure it forced on (in e.g. .gitconfig):
[color]
ui = on
git diff | less -R
For non-color tools, then use:
git diff --no-color | some-primitive-tool
Exporting environment variable LESS=-R
(in e.g. .bashrc) turns on color support by default in "less":
git diff | less
Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.
Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code if the update is considered binary compatible with the original version.
Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load).
Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular).
import datetime
monthinteger = 4
month = datetime.date(1900, monthinteger, 1).strftime('%B')
print month
April
Using unzip
unzip -c whatever.war META-INF/MANIFEST.MF
It will print the output in terminal.
And for extracting all the files,
unzip whatever.war
Using jar
jar xvf test.war
Note! The jar
command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).
If you can comment out code and your program still works, then yes, that code was optional.
.strip()
with no arguments (or None
as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.
For example, by using .strip()
, the following two lines in a file would lead to the same end result:
foo\tbar \n
foo\tbar\n
I'd say leave it in.
I dislike "Don't" answers, but... don't.
make
's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.
In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.
Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.
result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]);
for f in result.collect():
print (f.col_name)
Very simple way from PowerShell:
(Get-CimInstance -Class Win32_OperatingSystem).InstallDate
Extracted from: https://www.sysadmit.com/2019/10/windows-cuando-fue-instalado.html
its tempting say as white space or integer 0 as per below proof
char c1 = '\u0000';
System.out.println("*"+c1+"*");
System.out.println((int)c1);
but i wouldn't say so because, it might differ it different platforms or in future. What i really care is i ll never use this default value, so before using any char just check it is \u0000 or not, then use it to avoid misconceptions in programs. Its as simple as that.
Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.
.gitattributes
file in the root of your git repository:
* text=auto eol=lf
Add and commit it.
Afterwards, you can do following to steps and all files are normalized now:
git rm --cached -r . # Remove every file from git's index.
git reset --hard # Rewrite git's index to pick up all the new line endings.
Source: Answer by kenorb.
Although Time Complexity of selection sort and insertion sort is the same, that is n(n - 1)/2. The average performance insertion sort is better. Tested on my i5 cpu with random 30000 integers, selection sort took 1.5s in average, while insertion sort take 0.6s in average.
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.
As iOS does not use Java like Android, your options are quite limited:
1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).
2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.
3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.
The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.
Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.
As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.
There's a JS QrCode scanner, that works on mobile sites with a camera:
https://github.com/LazarSoft/jsqrcode
I have worked with it for one of my project and it works pretty good !
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
String#toLowerCase and String#toUpperCase are the methods you need.
Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:
pd.DataFrame({'email':sf.index, 'list':sf.values})
There are lots of ways to construct a df, see the docs
You can also specify the exact values for each gr
0 2,10,12,14,16,18,20 * * *
It stands for 2h00, 10h00, 12h00 and so on, till 20h00.
From the above answer, we have:
The comma, ",", means "and". If you are confused by the above line, remember that spaces are the field separators, not commas.
And from (Wikipedia page):
* * * * * command to be executed
- - - - -
¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ ¦ +----- day of week (0 - 7) (0 or 7 are Sunday, or use names)
¦ ¦ ¦ +---------- month (1 - 12)
¦ ¦ +--------------- day of month (1 - 31)
¦ +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)
Hope it helps :)
--
EDIT:
This can be done in three simple steps:
1) Add item id with url
tag:
{% for item in post %}
<tr>
<th>{{ item.id }}</th>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>
<a href={% url 'edit' id=item.id %}>Edit</a>
<a href={% url 'delete' id=item.id %}>Delete</a>
</td>
</tr>
{% endfor %}
2) Add path to urls.py:
path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')
3) Use the id on views.py:
def delete(request, id):
obj = post.objects.get(id=id)
obj.delete()
return redirect('dashboard')
You will also need to shrink the individual data files.
It is however not a good idea to shrink the databases. For example see here
int x = thisObject.compareTo(anotherObject);
The compareTo()
method returns an int with the following characteristics:
If thisObject < anotherObject
If thisObject == anotherObject
If thisObject > anotherObject
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
read = com.ExecuteReader()
SqlDataReader
has a function Read()
that reads the next row from your query's results and returns a bool
whether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read()
got). Or preferably make a loop while(read.Read())
if your query returns multiple rows.
If adding pypi.python.org as a trusted host does not work, you try adding files.pythonhosted.org. For example
python -m pip install --upgrade --trusted-host files.pythonhosted.org <package-name>
You can do it without dealing with encoding by using BlockCopy:
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);
select * from SomeTable where null is null
or
select * from SomeTable where null is not null
maybe this is the best performance?
You need the /g for global matching
replace(/\n/g, "<br />");
This works for me for \n
- see this answer if you might have \r\n
NOTE: The dupe is the most complete answer for any combination of \r\n
, \r
or \n
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
Line 1_x000D_
_x000D_
_x000D_
Line 2_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Line 3_x000D_
</textarea>
_x000D_
UPDATE
It seems some visitors of this question have text with the breaklines escaped as
some text\r\nover more than one line"
In that case you need to escape the slashes:
replace(/\\r\\n/g, "<br />");
NOTE: All browsers will ignore \r
in a string when rendering.
What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts.
Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts"
.
Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.
It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U
(unmerged
) flag for the files.
So now, when you do a git pull
, git is throwing up the error, because you have some version of the file, which is not correctly resolved.
To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull
.
# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test
First, let us create the repository structure
test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
Now we are in repo_clone, and if you do a git pull
, it will throw up conflicts
repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
* branch master -> FETCH_HEAD
24d5b2e..1a1aa70 master -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
If we ignore the conflicts in the clone, and make more commits in the original repo now,
repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
And then we do a git pull
, we get
repo_clone $ git pull
U file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.
Note that the file
now is in an unmerged state and if we do a git status
, we can clearly see the same:
repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file
So, to resolve this, we first need to resolve the merge conflict we ignored earlier
repo_clone $ vi file
and set its contents to
text2
text1
text1
and then add it and commit the changes
repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts
By using (
,)
, you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "a b c d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']
However there is no need for regex, str.split
without any delimiter specified will split this by whitespace for you. This would be the best way in this case.
>>> str1.split()
['a', 'b', 'c', 'd']
If you really wanted regex you can use this ('\s'
represents whitespace and it's clearer):
>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']
or you can find all non-whitespace characters
>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']
Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).
Hope this helps:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");
pictureBox1.ContextMenu = cm;
I was a bit surprised by the behavior of the css though.
var cssEllipsis =
{ "width": "100%","display": "inline-block",
"vertical-align": "middle", "white-space": "nowrap",
"overflow": "hidden", "text-overflow": "ellipsis"
};
Unless I provided the width to the control to which i needed to bind the ellipsis didn't suppost my cause. Is width a must property to be added ??? Please put your thoughts.
Look at this method to see which fields are supported. You will find for LocalDateTime
:
•NANO_OF_SECOND
•NANO_OF_DAY
•MICRO_OF_SECOND
•MICRO_OF_DAY
•MILLI_OF_SECOND
•MILLI_OF_DAY
•SECOND_OF_MINUTE
•SECOND_OF_DAY
•MINUTE_OF_HOUR
•MINUTE_OF_DAY
•HOUR_OF_AMPM
•CLOCK_HOUR_OF_AMPM
•HOUR_OF_DAY
•CLOCK_HOUR_OF_DAY
•AMPM_OF_DAY
•DAY_OF_WEEK
•ALIGNED_DAY_OF_WEEK_IN_MONTH
•ALIGNED_DAY_OF_WEEK_IN_YEAR
•DAY_OF_MONTH
•DAY_OF_YEAR
•EPOCH_DAY
•ALIGNED_WEEK_OF_MONTH
•ALIGNED_WEEK_OF_YEAR
•MONTH_OF_YEAR
•PROLEPTIC_MONTH
•YEAR_OF_ERA
•YEAR
•ERA
The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime
cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate
(with even less supported fields).
If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.
Coming back to your question and the numbers in your code:
The result 1605 is correct
=> (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1
16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).
UPDATE after given timezone info:
local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861
As JSR-310-code with two equivalent approaches:
long secondsSinceUnixEpoch1 =
LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();
long secondsSinceUnixEpoch2 =
LocalDate
.of(2014, 2, 4)
.atTime(19, 51, 1)
.atZone(ZoneId.of("Europe/Oslo"))
.toEpochSecond();
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.
While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.
Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.
Swift 3 compatible
// MARK: - UIDevice Extension -
private let DeviceList = [
/* iPod 5 */ "iPod5,1": "iPod Touch 5",
/* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */ "iPhone4,1": "iPhone 4S",
/* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */ "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */ "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus",
/* iPhone SE */ "iPhone8,4": "iPhone SE",
/* iPhone 7 */ "iPhone9,1": "iPhone 7",
/* iPhone 7 */ "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */ "iPhone9,2": "iPhone 7 Plus",
/* iPhone 7 Plus */ "iPhone9,4": "iPhone 7 Plus",
/* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3",
/* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */ "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */ "iPad2,5": "iPad Mini 1", "iPad2,6": "iPad Mini 1", "iPad2,7": "iPad Mini 1",
/* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Pro 12.9 */ "iPad6,7": "iPad Pro 12.9", "iPad6,8": "iPad Pro 12.9",
/* iPad Pro 9.7 */ "iPad6,3": "iPad Pro 9.7", "iPad6,4": "iPad Pro 9.7",
/* Simulator */ "x86_64": "Simulator", "i386": "Simulator"
]
extension UIDevice {
static var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8, value != 0 {
identifier += String(UnicodeScalar(UInt8(value)))
}
}
return DeviceList[identifier] ?? identifier
}
static var isIphone4: Bool {
return modelName == "iPhone 5" || modelName == "iPhone 5C" || modelName == "iPhone 5S" || UIDevice.isSimulatorIPhone4
}
static var isIphone5: Bool {
return modelName == "iPhone 4S" || modelName == "iPhone 4" || UIDevice.isSimulatorIPhone5
}
static var isIphone6: Bool {
return modelName == "iPhone 6" || UIDevice.isSimulatorIPhone6
}
static var isIphone6Plus: Bool {
return modelName == "iPhone 6 Plus" || UIDevice.isSimulatorIPhone6Plus
}
static var isIpad: Bool {
if UIDevice.current.model.contains("iPad") {
return true
}
return false
}
static var isIphone: Bool {
return !self.isIpad
}
/// Check if current device is iPhone4S (and earlier) relying on screen heigth
static var isSimulatorIPhone4: Bool {
return UIDevice.isSimulatorWithScreenHeigth(480)
}
/// Check if current device is iPhone5 relying on screen heigth
static var isSimulatorIPhone5: Bool {
return UIDevice.isSimulatorWithScreenHeigth(568)
}
/// Check if current device is iPhone6 relying on screen heigth
static var isSimulatorIPhone6: Bool {
return UIDevice.isSimulatorWithScreenHeigth(667)
}
/// Check if current device is iPhone6 Plus relying on screen heigth
static var isSimulatorIPhone6Plus: Bool {
return UIDevice.isSimulatorWithScreenHeigth(736)
}
private static func isSimulatorWithScreenHeigth(_ heigth: CGFloat) -> Bool {
let screenSize: CGRect = UIScreen.main.bounds
return modelName == "Simulator" && screenSize.height == heigth
}
}
This problem I solved with the following detail, somehow the android SDK manage installed all the dependencies and necessary files, but forget this `templates`
files where is found templates> gradle> wrapper. This set of files is missing.
Path in mac
/Users/giogio/Library/Android/sdk/tools/templates
first, extract ids from the collection where condition
List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();
second, use "compare" estament to select ids diffent to the selection
List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();
Obviously you can use x.key != "TEST", but is only a example
I tweaked the accepted answer to perform the operation for multiple dataframes on different suffix
parameters using reduce
and i guess it can be extended to different on
parameters as well.
from functools import reduce
dfs_with_suffixes = [(df2,suffix2), (df3,suffix3),
(df4,suffix4)]
merge_one = lambda x,y,sfx:pd.merge(x,y,on=['col1','col2'..], suffixes=sfx)
merged = reduce(lambda left,right:merge_one(left,*right), dfs_with_suffixes, df1)
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
document.getElementById('capitalizeInput').addEventListener("keyup", () => {_x000D_
var inputValue = document.getElementById('capitalizeInput')['value']; _x000D_
if (inputValue[0] === ' ') {_x000D_
inputValue = '';_x000D_
} else if (inputValue) {_x000D_
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);_x000D_
}_x000D_
document.getElementById('capitalizeInput')['value'] = inputValue;_x000D_
});
_x000D_
<input type="text" id="capitalizeInput" autocomplete="off" />
_x000D_
You could wrap your VLOOKUP() in an IFERROR()
Edit: before Excel 2007, use =IF(ISERROR()...)
Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:
var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
if (item != null)
{
TheValue = item.Value;
}
This is the correct code
function sum()
{
var txtFirstNumberValue = document.getElementById('total_fees').value;
var txtSecondNumberValue = document.getElementById('advance_payement').value;
var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
if(txtFirstNumberValue=="" ||txtSecondNumberValue=="")
{
document.getElementById('balance_payement').value = 0;
}
if (!isNaN(result))
{
document.getElementById('balance_payement').value = result;
}
}
Here is my working solution with search and clear icon for Angularjs\Bootstrap with CSS.
<div class="form-group has-feedback has-clear">
<input type="search" class="form-control removeXicon" ng-model="filter" style="max-width:100%" placeholder="Search..." />
<div ng-switch on="!!filter">
<div ng-switch-when="false">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
<div ng-switch-when="true">
<span class="glyphicon glyphicon-remove-sign form-control-feedback" ng-click="$parent.filter = ''" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></span>
</div>
</div>
</div>
------
CSS
/* hide the built-in IE10+ clear field icon */
.removeXicon::-ms-clear {
display: none;
}
/* hide the built-in chrome clear field icon */
.removeXicon::-webkit-search-decoration,
.removeXicon::-webkit-search-cancel-button,
.removeXicon::-webkit-search-results-button,
.removeXicon::-webkit-search-results-decoration {
display: none;
}
If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:
git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
--no-merges
omits the merge commits from the listold-tag^
refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).Just the same as what should be but change the button component to be label like so
<form id='uploadForm'
action='http://localhost:8000/upload'
method='post'
encType="multipart/form-data">
<input type="file" id="sampleFile" style="display: none;" />
<Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button>
</form>
As others have correctly pointed out, the first part of the ternary needs to return true
or false
and in your question the return value is a jQuery object.
The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.
So with the CSS:
#blackbox {
background:pink;
width:10px;
height:10px;
}
The following jQuery will flip the colour:
var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));
#import <QuickLook/QuickLook.h>
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
QLPreviewController *preview = [[QLPreviewController alloc] init];
preview.dataSource = self;
[self addChildViewController:preview];
[self.view addSubview:preview.view];
}
#pragma mark - QLPreviewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController
{
return 1;
}
- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myanimated.gif" ofType:nil]];
return fileURL;
}
@end
There seem to be many opinions about what functional programs and what imperative programs are.
I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.
In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.
Imperative: Shipping the computer around
Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.
Functional: Shipping recipes around
The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.
This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.
When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.
// helper function, to illustrate the point
function unwrap(val) {
while (typeof val === "function") val = val();
return val;
}
function inc(val) {
return function() { unwrap(val) + 1 };
}
function dec(val) {
return function() { unwrap(val) - 1 };
}
function add(val1, val2) {
return function() { unwrap(val1) + unwrap(val2) }
}
// lets "calculate" something
let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))
// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13
// lets compose a new function
let doubler = function(val) {
return add(val, val);
}
// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)
// another function
let doublerMinusOne = (val) => dec(add(val, val));
// Will this be calculating anything?
let twentyFive = doubler(thirteen)
// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26
The unwrap function will evaluate all the functions to the point of having a scalar value.
Language Design Consequences
Some nice features in imperative languages, are impossible in functional languages. For example the value++
expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.
On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.
Functional languages have great difficulty with unary operators like for example ++
to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".
Implementing a unary operator would have to be implemented something like this:
let value = 10;
function increment_operator(value) {
return function() {
unwrap(value) + 1;
}
}
value++ // would "under the hood" become value = increment_operator(value)
Note that the unwrap
function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.
It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.
The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.
Under the hood, it boils down to two different approaches to come up with an output when provided with an input.
Below, I'll try to make an illustration of a city with the following items:
Task: Calculate the 3rd fibonacci number. Steps:
Put The Computer into a box and mark it with a sticky note:
Field | Value |
---|---|
Mail Address | The Fibonaccis |
Return Address | Your Home |
Parameters | 3 |
Return Value | undefined |
and send off the computer.
The Fibonaccis will upon receiving the box do as they always do:
Is the parameter < 2?
Yes: Change the sticky note, and return the computer to the post office:
Field | Value |
---|---|
Mail Address | The Fibonaccis |
Return Address | Your Home |
Parameters | 3 |
Return Value | 0 or 1 (returning the parameter) |
and return to sender.
Otherwise:
Put a new sticky note on top of the old one:
Field | Value |
---|---|
Mail Address | The Fibonaccis |
Return Address | Otherwise, step 2, c/o The Fibonaccis |
Parameters | 2 (passing parameter-1) |
Return Value | undefined |
and send it.
Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:
Field | Value |
---|---|
Mail Address | The Fibonaccis |
Return Address | Otherwise, done, c/o The Fibonaccis |
Parameters | 2 (passing parameter-2) |
Return Value | undefined |
By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.
Field | Value |
---|---|
Mail Address | The Fibonaccis |
Return Address | Your Home |
Parameters | 3 |
Return Value | 2 (returnValue1 + returnValue2) |
and return to sender.
As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.
The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.
Task: Calculate the 3rd fibonacci number. Steps:
Write the following down on a sticky note:
Field | Value |
---|---|
Instructions | The Fibonaccis |
Parameters | 3 |
That's essentially it. That sticky note now represents the computation result of fib(3)
.
We have attached the parameter 3 to the recipe named The Fibonaccis
. The computer does not have to perform any calculations, unless somebody needs the scalar value.
I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.
fib: (n) => if (
n < 2 // test
n // when true
fib(n-1) + fib(n-2) // when false
)
print(fib(4));
This code can be compiled both into imperative and functional "bytecode".
The imperative javascript version would be:
let fib = (n) =>
n < 2 ?
n :
fib(n-1) + fib(n-2);
The HALF functional javascript version would be:
let fib = (n) => () =>
n < 2 ?
n :
fib(n-1) + fib(n-2);
The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.
let unwrap = ($) =>
typeof $ !== "function" ? $ : unwrap($());
let $if = ($test, $whenTrue, $whenFalse) => () =>
unwrap($test) ? $whenTrue : $whenFalse;
let $lessThen = (a, b) => () =>
unwrap(a) < unwrap(b);
let $add = ($value, $amount) => () =>
unwrap($value) + unwrap($amount);
let $sub = ($value, $amount) => () =>
unwrap($value) - unwrap($amount);
let $fib = ($n) => () =>
$if(
$lessThen($n, 2),
$n,
$add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
);
I'll manually "compile" it into javascript code:
"use strict";
// Library of functions:
/**
* Function that resolves the output of a function.
*/
let $$ = (val) => {
while (typeof val === "function") {
val = val();
}
return val;
}
/**
* Functional if
*
* The $ suffix is a convention I use to show that it is "functional"
* style, and I need to use $$() to "unwrap" the value when I need it.
*/
let if$ = (test, whenTrue, otherwise) => () =>
$$(test) ? whenTrue : otherwise;
/**
* Functional lt (less then)
*/
let lt$ = (leftSide, rightSide) => () =>
$$(leftSide) < $$(rightSide)
/**
* Functional add (+)
*/
let add$ = (leftSide, rightSide) => () =>
$$(leftSide) + $$(rightSide)
// My hand compiled Charm script:
/**
* Functional fib compiled
*/
let fib$ = (n) => if$( // fib: (n) => if(
lt$(n, 2), // n < 2
() => n, // n
() => add$(fib$(n-2), fib$(n-1)) // fib(n-1) + fib(n-2)
) // )
// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));
// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))
// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable
Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.
To understand clearly, see the below simple example:
class Student
{
int sno,sage;
String sname,dept;
Student()
{
dept="CSE";
}
public static void main(String a[])
{
Student s1=new Student();
s1.sno=101;
s1.sage=33;
s1.sname="John";
Student s2=new Student();
s2.sno=102;
s2.sage=99;
s2.sname="Peter";
Student s3=new Student();
s3.sno=102;
s3.sage=99;
s3.sname="Peter";
System.out.println("The details of student1 are");
System.out.println("The student no is:"+s1.sno);
System.out.println("The student age is:"+s1.sage);
System.out.println("The student name is:"+s1.sname);
System.out.println("The student dept is:"+s1.dept);
System.out.println("The details of student2 are");`enter code here`
System.out.println("The student no is:"+s2.sno);
System.out.println("The student age is:"+s2.sage);
System.out.println("The student name is:"+s2.sname);
System.out.println("The student dept is:"+s2.dept);
System.out.println("The details of student2 are");
System.out.println("The student no is:"+s3.sno);
System.out.println("The student age is:"+s3.sage);
System.out.println("The student name is:"+s3.sname);
System.out.println("The student dept is:"+s3.dept);
}
}
Output:
The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
Yes, that's possible, albeit not literally the <td>
, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).
As already explained, this isn't semantically correct. An a
element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:
<td>
<a href="http://example.com">
<div style="height:100%;width:100%">
hello world
</div>
</a>
</td>
PS: it's actually neater to change a
in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)
If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.
<table>
<tr>
<a href="http://example.com"><td width="200">hello world</td></a>
</tr>
</table>
Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?
One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:
<?php
$loader = require 'vendor/autoload.php';
$loader->add('AppName', __DIR__.'/../src/');
I think this should help you.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
Tell me if it works.
P/s: here is some media query for standard devices. http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
You can do it using jsPDF
HTML:
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
JavaScript:
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
By turning them into integers instead:
percent = (int(pyc) / int(tpy)) * 100;
In python 3, the input()
function returns a string. Always. This is a change from Python 2; the raw_input()
function was renamed to input()
.
i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.
A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >=
and <=
:
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
Checkout Portfoliojs jQuery plugin: http://portfoliojs.com
This plugin supports Touch Devices, Desktops and Mobile Browsers. Also, It has pre-loading feature.
I faced similar problem. Akilesh awasthi's answer helped me fix it. My problem was a little different. I was using places_ic_search icon from com.google.android.gms:play-services-location The latest version com.google.android.gms:play-services-location:15.0.0 does not provide the icon places_ic_search. Because of this there was a problem in the layout.xml files.That led to build failure AAPT2 error: check logs for details as the message. Android studio should be showing cannot find drawable places_ic_search as the message instead.
I ended up using a lower version of com.google.android.gms:play-services-location temporarily. Hope this helps someone in future.
It can be done without using the sys library if we look at the print()
function
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here is my code:
def update(n):
for i in range(n):
print("i:",i,sep='',end="\r",flush=True)
#time.sleep(1)
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.
Here is the right way to do imports in Java.
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.
Use Selenium for webbased unit tests. There's a Firefox plugin called Selenium IDE which can record actions on the webpage and export to JUnit testcases which uses Selenium RC to run the test server.
In Ubuntu I found the theme at /snap/code/55/usr/share/code/resources/app/extensions/theme-defaults/themes/dark_plus.json
A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).
If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
Asynchronous is there for a reason! Throws stone at @mihai
Otherwise, here is the code he used with the asynchronous version:
// Declare variables
var fs = require('fs'),
obj
// Read the file and send to the callback
fs.readFile('path/to/file', handleFile)
// Write the callback function
function handleFile(err, data) {
if (err) throw err
obj = JSON.parse(data)
// You can now play with your datas
}
@qbzenker provided the most idiomatic method IMO
Here are a few alternatives:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
That occasionally occurs to me while using emulator. I just plug in a device and run the app. The Logcat gets back to work and so it does when I get back to the emulator. I guess that just switching two devices and/or emulators does the trick as well.
I was looking for a more direct implementation like avijendr suggested.
I had a little trouble with his/her syntax, but I got this to work:
if ($('.user-forms input[id*="chkPrint"]:not(:checked)').length > 0)
In my case, I had a table with a class user-forms
, and I was checking if any of the checkboxes that had the string checkPrint
in their id
were unchecked.
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
If you don't want to deal with interactive mode then do this:
Update your last pushed commit
git commit --amend -m "New commit message."
Push your new commit message (this will replace the old last commit message to this new one)
git push origin --force **branch-name**
More on this - https://linuxize.com/post/change-git-commit-message/
I prefer to use other variant for accessing.
From parent you can have a access to variable in child iframe.
$
is a variable too and you can receive access to its just call
window.iframe_id.$
For example, window.view.$('div').hide()
- hide all divs in iframe with id 'view'
But, it doesn't work in FF. For better compatibility you should use
$('#iframe_id')[0].contentWindow.$
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
I recommend my solution. My situation: g++(cygwin) on win10
My solution: Write a .bat batch file and execute compiler in that batch. compileCpp.bat
@echo off
set PATH=%PATH%;C:\cygwin64\bin\
rm %~n1.exe
c++.exe -g %~dpnx1 -o %~dpn1.exe
%~n1.exe
Console:
NPP_EXEC: "runCpp"
NPP_SAVE: E:\hw.cpp
CD: E:\
Current directory: E:\
cmd /c C:\cygwin64\bin\compileCpp.bat "hw.cpp"
Process started >>>
Hello World<<< Process finished. (Exit code 0)
================ READY ================
The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.
var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
See this jsFiddle for code and demonstration.
See How to reset file input with JavaScript for more information.
You need to create your own custom button template to have full control over the appearance in all states. Here's a tutorial.
I wrote a short C program that returns the environment variables passed from nginx to the fastCGI application.
#include <stdlib.h>
#include <fcgi_stdio.h>
extern char **environ;
int main(int argc, char **argv) {
char *envvar;
int i;
int count = 0;
while(FCGI_Accept() >= 0) {
printf("Content-type: text/html\n\n"
"<html><head><title>FastCGI Call Debug Tool</title></head>\n"
"<body><h1>FastCGI Call Debugging Tool</h1>\n"
"<p>Request number %d running on host <i>%s</i></p>\n"
"<h2>Environment Variables</h2><p>\n",
++count, getenv("SERVER_NAME"));
i = 0;
envvar = environ[i];
while (envvar != NULL) {
printf("%s<br/>",envvar);
envvar = environ[++i];
}
printf("</p></body></html>\n");
}
return 0;
}
Save this to a file, e.g. fcgi_debug.c
To compile it, first install gcc
and libfcgi-dev
, then run:
gcc -o fcgi_debug fcgi_debug.c -lfcgi
To run it, install spawn-fcgi
, then run:
spawn-fcgi -p 3000 -f /path/to/fcgi_debug
Then, change your nginx fcgi config to point to the debug program:
fastcgi_pass 127.0.0.1:3000;
Restart nginx, refresh the page, and you should see all the parameters appear in your browser for you to debug! :-)
I had the same problem, this is the solution i came up with, which is much easier!
Make a little 1px x 1px transparent image and save it as a .png file.
In the CSS for your DIV, use this code:
background:transparent url('/images/trans-bg.png') repeat center top;
Remember to change the file path to your transparent image.
I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.
I have the same problem with MySQL and I solve by using XAMPP to connect with MySQL and stop the services in windows for MySQL (control panel - Administrative Tools - Services), and in the folder db.js (that responsible for the database ) I make the password empty (here you can see:)
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: ''
});
Try this:
<div id="div"></div>
<script language="javascript" type="text/javascript">
var div = document.getElementById('div');
for (var i = 0; i < 10; i++) {
var f = function() {
var link = document.createElement('a');
var j = i; // this j is scoped to our anonymous function
// while i is scoped outside the anonymous function,
// getting incremented by the for loop
link.setAttribute('href', '#');
link.innerHTML = j + '';
link.onclick= function() { onClickLink(j+'');};
div.appendChild(link);
div.appendChild(document.createElement('br')); // lower case BR, please!
}(); // call the function immediately
}
function onClickLink(text) {
alert('Link ' + text + ' clicked');
return false;
}
</script>
global
is a bit of a misnomer in Python, module_namespace
would be more descriptive.
The fully qualified name of foo
is file1.foo
and the global statement is best shunned as there are usually better ways to accomplish what you want to do. (I can't tell what you want to do from your toy example.)
Rolo's answer is excellent, however I had to reinstall Pillow by bypassing pip cache (introduced with pip 7) otherwise it won't get properly recompiled!!! The command is:
pip install -I --no-cache-dir -v Pillow
and you can see if Pillow has been properly configured by reading in the logs this:
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 2.8.2
platform linux 3.4.3 (default, May 25 2015, 15:44:26)
[GCC 4.8.2]
--------------------------------------------------------------------
*** TKINTER support not available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
--- LIBTIFF support available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
as you can see the support for jpg, tiff and so on is enabled, because I previously installed the required libraries via apt (libjpeg-dev libpng12-dev libfreetype6-dev libtiff-dev)
It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.
If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)
If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.
Use the following SQL statement
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND COLUMN_NAME = 'col_name'
If you replace tbl_name and col_name, it displays data type of the particular coloumn that you looking for.