Both Sweet and Slinky seem to be unmaintanted for about a year. Sweet Maven repo sweetsoftwaredesign.com is dead so there's even no way to download dependencies.
In my case, it turned out that I simply had to upgrade my test adapters and test framework. Done.
Example using the NuGet Package Manager:
You will have to go the hard drive for this information in any case, and this alone will trump any object creation and array filling.
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
this command may be help you sir
find -type f -mtime -60
Also, you could try triggering a mouseover.
$("#btn").click(function() {
$("#link").trigger("mouseover");
});
Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.
Assumed you have data frame as below
df1
A B C D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
When you would like create another df2
which is identical to df1
, without copy
df2=df1
df2
A B C D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
And would like modify the df2 value only as below
df2.iloc[0,0]='changed'
df2
A B C D
4 changed -1.0 -1.0 -1.0
5 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
At the same time the df1 is changed as well
df1
A B C D
4 changed -1.0 -1.0 -1.0
5 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
Since two df as same object
, we can check it by using the id
id(df1)
140367679979600
id(df2)
140367679979600
So they as same object and one change another one will pass the same value as well.
If we add the copy
, and now df1
and df2
are considered as different object
, if we do the same change to one of them the other will not change.
df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232
df1.iloc[0,0]='changedback'
df2
A B C D
4 changed -1.0 -1.0 -1.0
5 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
6 -1 -1.0 -1.0 -1.0
Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning
First of all, your variable "isLeapYear" is the same name as the method. That's just bad practice.
Second, you're not declaring "isLeapYear" as a variable.
Java is strongly typed so you need a
boolean isLeapYear;
in the beginning of your method.
This call:
System.out.println(boolean isLeapYear);
is just wrong. There are no declarations in method calls.
Once you have declared isLeapYear to be a boolean variable, you can call
System.out.println(isLeapYear);
UPDATE:
I just saw it's declared as a field. So just remove the line System.out.println(boolean isLeapYear);
You should understand that you can't call isLeapYear from the main() method. You cannot call a non static method from a static method with an instance.
If you want to call it, you need to add
booleanfun myBoolFun = new booleanfun();
System.out.println(myBoolFun.isLeapYear);
I really suggest you use Eclipse, it will let you know of such compilation errors on the fly and its much easier to learn that way.
Head stuck in jq for too long. This will work.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
All you have to do is to delete the "0" in the cells that contain just that and try again. That should work.
Create a new immutable map:
scala> val m1 = Map("k0" -> "v0")
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)
Add a new key/value pair to the above map (and create a new map, since they're both immutable):
scala> val m2 = m1 + ("k1" -> "v1")
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)
If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.
Use this class in your layout :
public class ActionEditText extends EditText
{
public ActionEditText(Context context)
{
super(context);
}
public ActionEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ActionEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs)
{
InputConnection conn = super.onCreateInputConnection(outAttrs);
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
return conn;
}
}
In xml:
<com.test.custom.ActionEditText
android:id="@+id/postED"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:gravity="top|left"
android:hint="@string/msg_type_message_here"
android:imeOptions="actionSend"
android:inputType="textMultiLine"
android:maxLines="5"
android:padding="5dip"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:textColor="@color/white"
android:textSize="20sp" />
Not too hard to explain... This is like typing hello worl
, hitting the left-arrow key twice, typing d
, and hitting the down-arrow key.
At least, that is how I infer your terminal is interpeting the \b
and \n
codes.
Redirect the output to a file and I bet you get something else entirely. Although you may have to look at the file's bytes to see the difference.
[edit]
To elaborate a bit, this printf
emits a sequence of bytes: hello worl^H^Hd^J
, where ^H
is ASCII character #8 and ^J
is ASCII character #10. What you see on your screen depends on how your terminal interprets those control codes.
Try this..
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CABBBBBB"/>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
CREATE TRIGGER clearcamcdr AFTER INSERT ON `asteriskcdrdb`.`cdr`
FOR EACH ROW
BEGIN
SET @INC = (SELECT sip_inc FROM trunks LIMIT 1);
IF NEW.billsec >1 AND NEW.channel LIKE @INC
AND NEW.dstchannel NOT LIKE ""
THEN
insert into `asteriskcdrdb`.`filtre` (id_appel,date_appel,source,destinataire,duree,sens,commentaire,suivi)
values (NEW.id,NEW.calldate,NEW.src,NEW.dstchannel,NEW.billsec,"entrant","","");
END IF;
END$$
Dont try this @ home
Another solution that doesn't not require to hard-code the receiving app and that is therefore safer:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( Uri.fromFile(new File(pathToApk)) );
startActivity(intent);
I'm very surprised nobody has suggested collection initializers. This way can only add objects when the list is created hence the name however it seems like the nicest way of doing it. No need to create an array then convert it to a list.
var list = new List<dynamic>()
{
new { Id = 1, Name = "Foo" },
new { Id = 2, Name = "Bar" }
};
You can always use object
instead of dynamic
but trying to keep it in a true generic way then dynamic
makes more sense.
After trying multiple things,what really worked was: 1. downloading "poi" and "poi-ooxml" manually 2.Adding these d/w jars into "Maven Dependencies"
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
use this library http://dart.googlecode.com/svn/branches/bleeding_edge/dart/lib/math/random.dart provided a good random generator which i think will be included in the sdk soon hope it helps
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.
Instead, you should keep it in text mode, but override the newline as empty. Like so:
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
Running as admin didn't help me. (also got errors with syscall: rename)
Turns out this error can also occur if files are locked by Windows.
This can occur if :
Running as admin doesn't get around windows file locking.
I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error
Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.
Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker
It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.
The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker
You must use a more recent version of tomcat which has support for JDK 8.
I can confirm that apache-tomcat-7.0.35 does NOT have support for JDK8, I can also confirm that apache-tomcat-7.0.50 DOES have support for JDK8.
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
Try to run in another port like 3131. Run the command:
react-native run-android --port=3131
If I understand your question correctly, is it the fact that the required
attribute appears to have default behaviour in Safari that's confusing you? If so, see: http://w3c.github.io/html/sec-forms.html#the-required-attribute
required
is not a custom attribute in HTML 5. It's defined in the spec, and is used in precisely the way you're presently using it.
EDIT: Well, not precisely. As ms2ger has pointed out, the required
attribute is a boolean attribute, and here's what the HTML 5 spec has to say about those:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
See: http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes
I think you should use null
SELECT CustomerName AS Customer, null AS Contact
FROM Customers;
And Remember that Oracle
treats a character value with a length of zero as null.
If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):
bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
"~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
"~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
"~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));
And angular app would appear in bundle unmodified.
If you use maven, check that you have this plugin in your pom.xml
:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<!-- Attach the shade goal into the package phase -->
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
It will put your dependency (the exception reason) to your jar.
FYI: this will include all dependencies inflated in the final jar
It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as
SUM(table.field = 1 AND table2.field = 2)
You can also use this syntax for COUNT
and I am sure other functions as well.
All the other solutions, including the top-voted one with vh
are sub-optimal when compared to the flex model solution.
With the advent of the CSS flex model, solving the 100% height problem becomes very, very easy: use height: 100%; display: flex
on the parent, and flex: 1
on the child elements. They'll automatically take up all the available space in their container.
Note how simple the markup and the CSS are. No table hacks or anything.
The flex model is supported by all major browsers as well as IE11+.
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
body {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.left, .right {_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.left {_x000D_
background: orange;_x000D_
}_x000D_
_x000D_
.right {_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="left">left</div>_x000D_
<div class="right">right</div>
_x000D_
Learn more about the flex model here.
value = value.setScale(2, RoundingMode.CEILING)
For windows add the path for meld is like below:
git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe
Here is the complete procedure for IDEA IntelliJ 2019.3:
File > Project Structure
Under Project Settings > Modules
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
Apply changes.
HTML
<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
</HEAD>
<BODY>
<H2>Multiple Checkbox Select/Deselect - DEMO</H2>
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
<td>Droid X</td>
<td>4.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
<td>HTC Desire</td>
<td>3/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
<td>Apple iPhone 4</td>
<td>5/5</td>
</tr>
</table>
</BODY>
</HTML>
jQuery Code
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
View Demo
Edit: This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by @Hossam Khamis for more details.
Use whichever one you feel suits your needs best.
The find
method is usually used to retrieve a row by ID:
Model.find(1)
It's worth noting that find
will throw an exception if the item is not found by the attribute that you supply. Use where
(as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.
Other uses of find
are usually replaced with things like this:
Model.all
Model.first
find_by
is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name
in your database, you'd use the following syntax:
Model.find_by(name: "Bob")
.where
is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).
Another way of doing it is by using isdigit function. Below is the code for it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
printf ("Given input is a number\n");
}
First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here
For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.
If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.
Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).
For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.
Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).
As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns
I hope this helps.
function ImageX( props){
const [state, setState] = React.useState({v:{height:1}});
useEffect(() => {
if(!props.source || !props.source.uri) return;
Image.prefetch(props.source.uri)
.then(() => {
Image.getSize(props.source.uri, (width, height) => {
let aspectRatio = height/width;
state.v.width=Dimensions.get('window').width;
state.v.height=aspectRatio*state.v.width;
setState({...state});
});
})
.catch(error => console.log(error))
},[props.source && props.source.uri]);
if (state.v.height <=1) //Image not in cache (disk) yet
{
return (
<Image {...props}/>
);
}
else
{
let neededst={v:{width:state.v.width, height:state.v.height}}
let st={v:props.style};
assignObject(neededst, st);
return (
<Image {...props} style={neededst.v}/>
);
}
}
function assignObject(target, source) {
if (!source) return;
for (let k in target) {
let v = target[k];
if (Object(v) === Object) assignObject(v, source[k]);
else {
if (source[k]) {
try {
Object.assign(v, source[k]);
} catch (e) {
alert(e);
}
}
}
}
for (let k in source) {
if (!target[k]) {
target[k] = source[k];
}
}
}
_x000D_
Using Image component from https://reactnativeelements.com/docs/image
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
For impatient, a quick way to disable python unverified HTTPS warning:
export PYTHONWARNINGS="ignore:Unverified HTTPS request"
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
Further to the above excellent comments about trusted constraints:
select * from sys.foreign_keys where is_not_trusted = 1 ;
select * from sys.check_constraints where is_not_trusted = 1 ;
An untrusted constraint, much as its name suggests, cannot be trusted to accurately represent the state of the data in the table right now. It can, however, but can be trusted to check data added and modified in the future.
Additionally, untrusted constraints are disregarded by the query optimiser.
The code to enable check constraints and foreign key constraints is pretty bad, with three meanings of the word "check".
ALTER TABLE [Production].[ProductCostHistory]
WITH CHECK -- This means "Check the existing data in the table".
CHECK CONSTRAINT -- This means "enable the check or foreign key constraint".
[FK_ProductCostHistory_Product_ProductID] -- The name of the check or foreign key constraint, or "ALL".
I just had this error in a bash script. The issue was an accidental \ at the end of the previous line that was giving an error.
Use media queries. Your CSS code would be:
@media screen and (max-width: 1024px) {
.yourClass {
display: none !important;
}
}
I found a solution that worked better for me. Under my home folder I found a workspace/.metadata folder. I copied this folder into my eclipse workspace, replacing the .metadata folder that had been there. When I started Eclipse everything was back to the way I had left it - all projects present, all open files were still open, etc. Just like nothing had happened! I'm using Neon.
Another short oneliner:
mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')
function add_more() {
var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';
for (i = 1; i <= count; i++) {
var cmp_text = document.getElementById('cmp_name_' + i).value;
var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
divContent += '<div id="div_cmp_' + i + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
'</div>';
}
var newCount = count + 1;
if (document.getElementById('div_cmp_' + newCount) == null) {
var newText = '<div id="div_cmp_' + newCount + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>' +
'</div>';
//content = div_cmp.innerHTML;
div_cmp.innerHTML = divContent + newText;
} else {
document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>';
}
document.getElementById('text_count').value = newCount;
}
You have to just check that the object is null or not. AngularJs provide inbuilt directive ng-if
. An example is given below.
<tr ng-repeat="key in object" ng-if="object != 'null'" >
<td>{{object.key}}</td>
<td>{{object.key}}</td>
</tr>
This is code that I have effectively used before, passing "/"
as the strPath parameter.
public static Cookie eraseCookie(String strCookieName, String strPath) {
Cookie cookie = new Cookie(strCookieName, "");
cookie.setMaxAge(0);
cookie.setPath(strPath);
return cookie;
}
Thanks to Ian Henry!
In case if you need to get file from MS SQL Server here is the solution.
public FileResult DownloadDocument(string id)
{
if (!string.IsNullOrEmpty(id))
{
try
{
var fileId = Guid.Parse(id);
var myFile = AppModel.MyFiles.SingleOrDefault(x => x.Id == fileId);
if (myFile != null)
{
byte[] fileBytes = myFile.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, myFile.FileName);
}
}
catch
{
}
}
return null;
}
Where AppModel is EntityFramework
model and MyFiles presents table in your database.
FileData is varbinary(MAX)
in MyFiles table.
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
You can also use -match against a Regular expression. Ex:
if ($dbUserName -match ".{8}" )
{
Write-Output " Please enter more than 8 characters "
$dbUserName=read-host " Re-enter database user name"
}
Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.
Installing CocoaPods on OS X 10.11
These instructions were tested on all betas and the final release of El Capitan.
Custom GEM_HOME
This is the solution when you are receiving above error
$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version
0.38.2
You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site.
Here is a short program that demonstrates it:
class StringCompareExample {
public static void main(String args[]){
String s1 = "Project"; String s2 = "Sunject";
verboseCompare(s1, s2);
verboseCompare(s2, s1);
verboseCompare(s1, s1);
}
public static void verboseCompare(String s1, String s2){
System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");
int comparisonResult = s1.compareTo(s2);
System.out.println("The result of the comparison was " + comparisonResult);
System.out.print("This means that \"" + s1 + "\" ");
if(comparisonResult < 0){
System.out.println("lexicographically precedes \"" + s2 + "\".");
}else if(comparisonResult > 0){
System.out.println("lexicographically follows \"" + s2 + "\".");
}else{
System.out.println("equals \"" + s2 + "\".");
}
System.out.println();
}
}
Here is a live demonstration that shows it works: http://ideone.com/Drikp3
You could use TimeZoneInfo class
The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:
Retrieving a time zone that is already defined by the operating system.
Enumerating the time zones that are available on a system.
Converting times between different time zones.
Creating a new time zone that is not already defined by the operating system.
Serializing a time zone for later retrieval.
You don't need to rely on hardcoded static global Loggers in your class implementation, you can provide a default logger in the default constructor and then use a specific constructor to set a reference to the provided logger.
class MyClassToTest {
private final Logger logger;
public MyClassToTest() {
this(SomeStatic.logger);
};
MyClassToTest(Logger logger) {
this.logger = logger;
};
public void someOperation() {
logger.warn("warning message");
// ...
};
};
class MyClassToTestTest {
@Test
public warnCalled() {
Logger loggerMock = mock(Logger.class);
MyClassTest myClassToTest = new MyClassToTest(logger);
myClassToTest.someOperation();
verify(loggerMock).warn(anyString());
};
}
Here's an excellent class that will copy CSV data into a datatable using the structure of the data to create the DataTable:
A portable and efficient generic parser for flat files
It's easy to configure and easy to use. I urge you to take a look.
If you have MySQL already installed on your windows then go to services.msc file on your windows and right click the MySQL file and stop the service, now open your XAMPP and start MySQL. Now MySQL will start on the port 3306.
Restarting ADB server works for me, but no need to go for it from command line.
Ctrl + Maj + A -> Troubleshoot Device Connections -> Next -> Next -> Restart ADB Server
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
Editing a Parameter The set method of the URLSearchParams object sets the new value of the parameter.
After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The final new url can then be retrieved with the toString() method of the URL object.
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
// new value of "id" is set to "101"
search_params.set('id', '101');
// change the search property of the main url
url.search = search_params.toString();
// the new url string
var new_url = url.toString();
// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);
Source - https://usefulangle.com/post/81/javascript-change-url-parameters
This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!
#include <iostream>
#include <complex>
#define MAX 200
using namespace std;
#define M_PI 3.1415926535897932384
int log2(int N) /*function to calculate the log2(.) of int numbers*/
{
int k = N, i = 0;
while(k) {
k >>= 1;
i++;
}
return i - 1;
}
int check(int n) //checking if the number of element is a power of 2
{
return n > 0 && (n & (n - 1)) == 0;
}
int reverse(int N, int n) //calculating revers number
{
int j, p = 0;
for(j = 1; j <= log2(N); j++) {
if(n & (1 << (log2(N) - j)))
p |= 1 << (j - 1);
}
return p;
}
void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
complex<double> f2[MAX];
for(int i = 0; i < N; i++)
f2[i] = f1[reverse(N, i)];
for(int j = 0; j < N; j++)
f1[j] = f2[j];
}
void transform(complex<double>* f, int N) //
{
ordina(f, N); //first: reverse order
complex<double> *W;
W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
W[1] = polar(1., -2. * M_PI / N);
W[0] = 1;
for(int i = 2; i < N / 2; i++)
W[i] = pow(W[1], i);
int n = 1;
int a = N / 2;
for(int j = 0; j < log2(N); j++) {
for(int i = 0; i < N; i++) {
if(!(i & n)) {
complex<double> temp = f[i];
complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
f[i] = temp + Temp;
f[i + n] = temp - Temp;
}
}
n *= 2;
a = a / 2;
}
free(W);
}
void FFT(complex<double>* f, int N, double d)
{
transform(f, N);
for(int i = 0; i < N; i++)
f[i] *= d; //multiplying by step
}
int main()
{
int n;
do {
cout << "specify array dimension (MUST be power of 2)" << endl;
cin >> n;
} while(!check(n));
double d;
cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
cin >> d;
complex<double> vec[MAX];
cout << "specify the array" << endl;
for(int i = 0; i < n; i++) {
cout << "specify element number: " << i << endl;
cin >> vec[i];
}
FFT(vec, n, d);
cout << "...printing the FFT of the array specified" << endl;
for(int j = 0; j < n; j++)
cout << vec[j] << endl;
return 0;
}
Or to use this in Java 8:
try {
Files.newDirectoryStream( directory ).forEach( file -> {
try { Files.delete( file ); }
catch ( IOException e ) { throw new UncheckedIOException(e); }
} );
}
catch ( IOException e ) {
e.printStackTrace();
}
It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...
If you like to keep records separate and not do the union.
Try query below
SELECT (SELECT name,
games,
goals
FROM tblMadrid
WHERE name = 'ronaldo') AS table_a,
(SELECT name,
games,
goals
FROM tblBarcelona
WHERE name = 'messi') AS table_b
FROM DUAL
To read binary ASCII characters with great speed using only your head:
Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.
New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net
1st January 2012
- OpenSSH for Windows 5.6p1-2 based release created!!
- Happy New Year all! Since COpSSH has started charging I've resurrected this project
- Updated all binaries to current releases
- Added several new supporting DLLs as required by all executables in package
- Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
- Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated
In each example the texts are freely-editable to illustrate how the content would render in different scenarios.
body{ height:100vh; margin:0; }
header{ min-height:50px; background:lightcyan; }
footer{ min-height:50px; background:PapayaWhip; }
/* Trick */
body{
display:flex;
flex-direction:column;
}
footer{
margin-top:auto;
}
_x000D_
<body>
<header contentEditable>Header</header>
<article contentEditable>Content</article>
<footer contentEditable>Footer</footer>
</body>
_x000D_
body{
min-height: 100vh;
margin: 0;
display: grid;
grid-template-rows: auto 1fr auto;
}
header{
min-height:50px;
background:lightcyan;
}
footer{
min-height:50px;
background:PapayaWhip;
}
_x000D_
<body>
<header contentEditable>Header</header>
<article contentEditable>Content</article>
<footer contentEditable>Footer</footer>
</body>
_x000D_
This method below uses a "trick" by placing an ::after
pseudo-element on the body
, and set it to have the exact height of the footer, so it will occupy the exact same space the footer does, so when the footer is absolute
positioned over it, it would appear like the footer is really taking up space and eliminate the negative affects of it's absolute positioning (for example, going over the body's content)
position:absolute
(no dynamic footer height)body{ min-height:100vh; margin:0; position:relative; }
header{ min-height:50px; background:lightcyan; }
footer{ background:PapayaWhip; }
/* Trick: */
body {
position: relative;
}
body::after {
content: '';
display: block;
height: 50px; /* Set same as footer's height */
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 50px;
}
_x000D_
<body>
<header contentEditable>Header</header>
<article contentEditable>Content</article>
<footer contentEditable>Footer</footer>
</body>
_x000D_
html{ height:100%; }
body { min-height:100%; margin:0; }
header {
height: 50px;
background: lightcyan;
}
article {
height: 1%;
}
footer {
height: 50px;
background: PapayaWhip;
}
/**** Trick: ****/
body {
display: table;
width: 100%;
}
body > footer {
display: table-row;
}
_x000D_
<body>
<header contentEditable>Header</header>
<article contentEditable>Content</article>
<footer contentEditable>Footer</footer>
</body>
_x000D_
UPDATE (Sept 4, 2020)
You can now use the ??
operator to validate null
and undefined
"values" and set a default value. For example:
const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value
As a verbose way, if you want to compare null and undefined values ONLY, use the following example code for reference:
const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion
if (somethingToCompare == (undefined || null)) {
console.log(`Incoming value is: ${somethingToCompare}`);
}
If incomingValue
is not declared, TypeScript should return an exception. If this is declared but not defined, the console.log()
will return "Incoming value is: undefined". Note we are not using the strict equals operator.
The "correct" way (check the other answers for details), if the incomingValue
is not a boolean
type, just evaluate if its value is true, this will be evaluated according to the constant/variable type. A true
string have to be defined explicitly as string using the = ''
assignation. If not, it will be evaluated as false
. Let's check this case using the same context:
const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;
if (somethingToCompare0) {
console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}
// Now, we will evaluate the second constant
if (somethingToCompare1) {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}
For future reference, webpack 2 removed everything but modules
as a way to resolve paths. This means root
will not work.
https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
The example configuration starts with:
{
modules: [path.resolve(__dirname, "app"), "node_modules"]
// (was split into `root`, `modulesDirectories` and `fallback` in the old options)
This wiki page has this interesting one-liner, which reminds us that we can push several refs:
git push origin refs/tags/<old-tag>:refs/tags/<new-tag> :refs/tags/<old-tag> && git tag -d <old-tag>
and ask other cloners to do
git pull --prune --tags
So the idea is to push:
<new-tag>
for every commits referenced by <old-tag>
: refs/tags/<old-tag>:refs/tags/<new-tag>
,<old-tag>
: :refs/tags/<old-tag>
See as an example "Change naming convention of tags inside a git repository?".
Here's a MySQL solution:
UPDATE mytable
SET number = (@n := COALESCE(number, @n))
ORDER BY date;
This is concise, but won't necessary work in other brands of RDBMS. For other brands, there might be a brand-specific solution that is more relevant. That's why it's important to tell us the brand you're using.
It's nice to be vendor-independent, as @Pax commented, but failing that, it's also nice to use your chosen brand of database to its fullest advantage.
Explanation of the above query:
@n
is a MySQL user variable. It starts out NULL, and is assigned a value on each row as the UPDATE runs through rows. Where number
is non-NULL, @n
is assigned the value of number
. Where number
is NULL, the COALESCE()
defaults to the previous value of @n
. In either case, this becomes the new value of the number
column and the UPDATE proceeds to the next row. The @n
variable retains its value from row to row, so subsequent rows get values that come from the prior row(s). The order of the UPDATE is predictable, because of MySQL's special use of ORDER BY with UPDATE (this is not standard SQL).
you can swipe the key and the value. For example
String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
int[] v = {341, 273, 278, 329, 445};
TreeMap<Integer,String>a=new TreeMap();
for (int i = 0; i < k.length; i++)
a.put(v[i],k[i]);
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
a.remove(a.firstEntry().getKey());
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
You can also use inline assembly like this:
int i;
__asm {
mov eax, 00000000000000000000000000000000b
mov i, eax
}
std::cout << i;
Okay, it might be somewhat overkill, but it works.
I too, one way or another stumbled on the same dilemma, why the heck Excel VBA doesn't have a Date Picker
. Thanks to Sid, who made an awesome job to create something for all of us.
Nonetheless, I came to a point where I need to create my own. And I am posting it here since a lot of people I'm sure lands on this post and benefit from it.
What I did was very simple as what Sid does except that I do not use a temporary worksheet. I thought the calculations are very simple and straight forward so there's no need to dump it somewhere else. Here's the final output of the calendar:
How to set it up:
Label
controls and name it sequentially and arranged left to right, top to bottom (This labels contains greyed 25
up to greyed 5
above). Change the name of the Label
controls to Label_01,Label_02 and so on. Set all 42 labels Tag
property to dts
.Label
controls for the header (this will contain Su,Mo,Tu...)Label
control, one for the horizontal line (height set to 1) and one for the Month and Year display. Name the Label
used for displaying month and year Label_MthYrImage
controls, one to contain the left icon to scroll previous months and one to scroll next month (I prefer simple left and right arrow head icon). Name it Image_Left
and Image_Right
The layout should be more or less like this (I leave the creativity to anyone who'll use this).
Declaration:
We need one variable declared at the very top to hold the current month selected.
Option Explicit
Private curMonth As Date
Private Procedure and Functions:
Private Function FirstCalSun(ref_date As Date) As Date
'/* returns the first Calendar sunday */
FirstCalSun = DateSerial(Year(ref_date), _
Month(ref_date), 1) - (Weekday(ref_date) - 1)
End Function
Private Sub Build_Calendar(first_sunday As Date)
'/* This builds the calendar and adds formatting to it */
Dim lDate As MSForms.Label
Dim i As Integer, a_date As Date
For i = 1 To 42
a_date = first_sunday + (i - 1)
Set lDate = Me.Controls("Label_" & Format(i, "00"))
lDate.Caption = Day(a_date)
If Month(a_date) <> Month(curMonth) Then
lDate.ForeColor = &H80000011
Else
If Weekday(a_date) = 1 Then
lDate.ForeColor = &HC0&
Else
lDate.ForeColor = &H80000012
End If
End If
Next
End Sub
Private Sub select_label(msForm_C As MSForms.Control)
'/* Capture the selected date */
Dim i As Integer, sel_date As Date
i = Split(msForm_C.Name, "_")(1) - 1
sel_date = FirstCalSun(curMonth) + i
'/* Transfer the date where you want it to go */
MsgBox sel_date
End Sub
Image Events:
Private Sub Image_Left_Click()
If Month(curMonth) = 1 Then
curMonth = DateSerial(Year(curMonth) - 1, 12, 1)
Else
curMonth = DateSerial(Year(curMonth), Month(curMonth) - 1, 1)
End If
With Me
.Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
Build_Calendar FirstCalSun(curMonth)
End With
End Sub
Private Sub Image_Right_Click()
If Month(curMonth) = 12 Then
curMonth = DateSerial(Year(curMonth) + 1, 1, 1)
Else
curMonth = DateSerial(Year(curMonth), Month(curMonth) + 1, 1)
End If
With Me
.Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
Build_Calendar FirstCalSun(curMonth)
End With
End Sub
I added this to make it look like the user is clicking the label and should be done on the Image_Right
control too.
Private Sub Image_Left_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Me.Image_Left.BorderStyle = fmBorderStyleSingle
End Sub
Private Sub Image_Left_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Me.Image_Left.BorderStyle = fmBorderStyleNone
End Sub
Label Events:
All of this should be done for all 42 labels (Label_01
to Lable_42
)
Tip: Build the first 10 and just use find and replace for the remaining.
Private Sub Label_01_Click()
select_label Me.Label_01
End Sub
This is for hovering over dates and clicking effect.
Private Sub Label_01_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Me.Label_01.BorderStyle = fmBorderStyleSingle
End Sub
Private Sub Label_01_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Me.Label_01.BackColor = &H8000000B
End Sub
Private Sub Label_01_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Me.Label_01.BorderStyle = fmBorderStyleNone
End Sub
UserForm Events:
Private Sub UserForm_Initialize()
'/* This is to initialize everything */
With Me
curMonth = DateSerial(Year(Date), Month(Date), 1)
.Label_MthYr = Format(curMonth, "mmmm, yyyy")
Build_Calendar FirstCalSun(curMonth)
End With
End Sub
Again, just for the hovering over dates effect.
Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
With Me
Dim ctl As MSForms.Control, lb As MSForms.Label
For Each ctl In .Controls
If ctl.Tag = "dts" Then
Set lb = ctl: lb.BackColor = &H80000005
End If
Next
End With
End Sub
And that's it. This is raw and you can add your own twist to it.
I've been using this for awhile and I have no issues (performance and functionality wise).
No Error Handling
yet but can be easily managed I guess.
Actually, without the effects, the code is too short.
You can manage where your dates go in the select_label
procedure. HTH.
For me, adding Trusted_Connection=True to the connection string helped.
Taking the answer above as guidance;
I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.
Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.
The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.
Thanks to the guy above for the idea!
In your controller you'd return an HttpStatusCodeResult like this...
[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
// todo: put your processing code here
//If not using MVC5
return new HttpStatusCodeResult(200);
//If using MVC5
return new HttpStatusCodeResult(HttpStatusCode.OK); // OK = 200
}
Let's think a little different, You can use static parameters:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function func() {
echo global::$foo;
}
I got the same issue.
I fixed it by removing line-height from my input. Check if there is some lineheight which is causing the problem
After following the answers above , and did
Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"
It still didn't work until I went to
Project -> Add Reference
And selected System.web
.
And everything worked link a charm.
The below code stores the return value in to the variable retVal
and then MsgBox
can be used to display the value:
Dim retVal As Integer
retVal = test()
Msgbox retVal
Back-button text is taken from parent view-controller's navigation item title. So whatever you set on previous view-controller's navigation item title, will be shown on current view controller's back button text. You can just put "" as navigation item title in parent view-controller's viewWillAppear method.
self.navigationItem.title = ""
Another way is to put
self.navigationController?.navigationBar.topItem?.title = ""
in current view controller's viewWillAppear method. This one will cause some other problem if navigation stack is too nested.
For some reason my push and pull origin was changed to HTTPS-url in stead of SSH-url (probably a copy-paste error on my end), but trying to push would give me the following error after trying to login:
Username for 'https://github.com': xxx
Password for 'https://[email protected]':
remote: Invalid username or password.
Updating the remote origin with the SSH url, solved the problem:
git remote set-url origin [email protected]:<username>/<repo>.git
Hope this helps!
Well, despite the fact that you asked that we not "simply" link to other resources, it's pretty foolish when there already exists a community grown (and growing) resource that's really quite good: the Git Community Book. Seriously, this 20+ questions in a question is going to be anything but concise and consistent. The Git Community Book is available as both HTML and PDF and answers many of your questions with clear, well formatted and peer reviewed answers and in a format that allows you to jump straight to your problem at hand.
Alas, if my post really upsets you then I'll delete it. Just say so.
Here's one sample: http://jsfiddle.net/CUUfb/1/
if you want to look for a div that has more than 1 class try this:
Html:
<div class="class1 class2 class3" id="myDiv">
Jquery:
var check = $( "#myDiv" ).hasClass( "class2" ).toString();
ouput:
true
We use it as a temporary storage area for uploaded csv files. Once uploaded, an ajax method processes and deletes the file.
We are following the below steps in our project for debugging a website on mobile.
The answer is no.
.class {
background-color: none; /* do not do this */
}
.class {
background-color: transparent;
}
background-color: transparent
accomplishes the same thing what you wanted to do with background-color: none
.
Since this is most popular question with regard to this problem, I'll re-post another answer to it here as well:
It looks like there is simpler way to do this (but only in MySQL):
select *
from (select * from mytable order by id, rev desc ) x
group by id
Please credit answer of user Bohemian in this question for providing such a concise and elegant answer to this problem.
Edit: though this solution works for many people it may not be stable in the long run, since MySQL doesn't guarantee that GROUP BY statement will return meaningful values for columns not in GROUP BY list. So use this solution at your own risk!
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
Class which can have both concrete and non-concrete methods i.e. with and without body.
Try:
CREATE TABLE foo SELECT * FROM bar LIMIT 0
Or:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0
You can try this:
return redirect()->back()->withInput(Input::all())->with('message', 'Something
went wrong!');
All you need to do is add:
html {
overflow-y: scroll;
}
In your css file as this will have the scroller whether it is needed or not though you just won't be able to scroll
This means that the viewport will have the same width for both
Your code looks good, in fact it works (apart from the calls themselves) when copied & pasted into a sample jsFiddle: http://jsfiddle.net/VGaWD/
Hard to say what is going on without seeing a more complete example but I hope that the above jsFiddle will be helpful. What I'm suspecting is that you are not initializing your app with the 'productServices' module. It would give the same error, we can see this in another jsFiddle: http://jsfiddle.net/a69nX/1/
If you are planning to work with AngularJS and MongoLab I would suggest using an existing adapter for the $resource and MongoLab: https://github.com/pkozlowski-opensource/angularjs-mongolab It eases much of the pain working with MongoLab, you can see it in action here: http://jsfiddle.net/pkozlowski_opensource/DP4Rh/ Disclaimer! I'm maintaining this adapter (written based on AngularJS examples) so I'm obviously biased here.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
I have had the same problem in two of my programs. My error was this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I'll try to tell you about different approaches and sum them up here.
While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn't work for them! why there are many approaches to this error? It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.
So I suggest you to try all the solutions one by one and don't give up!
Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.
Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:
Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)
Windows: C:**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it's ProgramData, not Program Files)
Uncomment "bind-address" attribute or change it to one of the following IPs:
bind-address="127.0.0.1"
or
bind-address="0.0.0.0"
If there is a "skip-networking" line in your MySQL config file, make it comment by adding "#" sign at the beginning of that line.
Add these lines to the MySQL config file:
wait_timeout = number
interactive_timeout = number
connect_timeout = number
Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6)
This could be avoided by using one of two approaches:
Option #1: In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1
Option #2: Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile:
export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
Make sure the Firewall, or Anti-virus software isn't blocking MySQL service.
Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection.
# Redhat enterprise and CentOS
systemctl stop iptables.service
# Other linux distros
service iptables stop
Stop anti-virus software on Windows.
Check your query string. your connection string should be some thing like this:
dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";
Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.
Try to replace "localhost" with the loopback address 127.0.0.1. Also try to add port number to your connection string, like:
String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";
Usually default port for MySQL is 3306.
Don't forget to change username and password to the username and password of your MySQL server.
"max_allowed_packet" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.
change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no
use validationQuery="select now()" to make sure each query has responses
Add this code to your connection string:
&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.
But what solved my problem?
My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.
There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.
>>> a.argmax(axis=0)
array([1, 1, 0])
Well According to a comment on the shuf answer he shuffed 78 000 000 000 lines in under a minute.
Challenge accepted...
EDIT: I beat my own record
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
The reason it is so fast, well I don't read the whole file and just move the file pointer 10 times and print the line after the pointer.
First I needed a file of 78.000.000.000 lines:
seq 1 78 | xargs -n 1 -P 16 -I% seq 1 1000 | xargs -n 1 -P 16 -I% echo "" > lines_78000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000.txt > lines_78000000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000000.txt > lines_78000000000.txt
This gives me a a file with 78 Billion newlines ;-)
Now for the shuf part:
$ time shuf -n 10 lines_78000000000.txt
shuf -n 10 lines_78000000000.txt 2171.20s user 22.17s system 99% cpu 36:35.80 total
The bottleneck was CPU and not using multiple threads, it pinned 1 core at 100% the other 15 were not used.
Python is what I regularly use so that's what I'll use to make this faster:
#!/bin/python3
import random
f = open("lines_78000000000.txt", "rt")
count = 0
while 1:
buffer = f.read(65536)
if not buffer: break
count += buffer.count('\n')
for i in range(10):
f.readline(random.randint(1, count))
This got me just under a minute:
$ time ./shuf.py
./shuf.py 42.57s user 16.19s system 98% cpu 59.752 total
I did this on a Lenovo X1 extreme 2nd gen with the i9 and Samsung NVMe which gives me plenty read and write speed.
I know it can get faster but I'll leave some room to give others a try.
Line counter source: Luther Blissett
I suspect that the line
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
is causing the problem. Is it possible that the op_Id
value is being set to null by the stored procedure?
To Guard against it use the Convert.IsDBNull
method. For example:
if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else
{
DataTO.Id = ...some default value or perform some error case management
}
Run the commands from your project's root directory:
# run all specs in the project's spec folder
bundle exec rspec
# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers
# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb
# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45
Here is a ZipFileIterator (like a java Iterator, but for zip files):
package ch.epfl.bbp.io;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipFileIterator implements Iterator<File> {
private byte[] buffer = new byte[1024];
private FileInputStream is;
private ZipInputStream zis;
private ZipEntry ze;
public ZipFileIterator(File file) throws FileNotFoundException {
is = new FileInputStream(file);
zis = new ZipInputStream(new BufferedInputStream(is));
}
@Override
public boolean hasNext() {
try {
return (ze = zis.getNextEntry()) != null;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
public File next() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
String filename = ze.getName();
File tmpFile = File.createTempFile(filename, "tmp");
tmpFile.deleteOnExit();// TODO make it configurable
FileOutputStream fout = new FileOutputStream(tmpFile);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
zis.closeEntry();
return tmpFile;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void remove() {
throw new RuntimeException("not implemented");
}
public void close() {
try {
zis.close();
is.close();
} catch (IOException e) {// nope
}
}
}
Below code will add listener for ENTER
key on entire page.
This can be very useful in screens with single Action button eg Login, Register, Submit etc.
<head>
<!--Import jQuery IMPORTANT -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--Listen to Enter key event-->
<script type="text/javascript">
$(document).keypress(function (e) {
if (e.which == 13 || event.keyCode == 13) {
alert('enter key is pressed');
}
});
</script>
</head>
Tested on all browsers.
Its very simple. Just give the below command for listing all keyspaces.
Cqlsh> Describe keyspaces;
If you want to check the keyspace in the system schema using the SQL query
below is the command.
SELECT * FROM system_schema.keyspaces;
Hope this will answer your question...
You can go through the explanation on understanding and creating the keyspaces from below resources.
Documentation:
https://docs.datastax.com/en/cql/3.1/cql/cql_reference/create_keyspace_r.html https://www.i2tutorials.com/cassandra-tutorial/cassandra-create-keyspace/
There is npm module to make a curl like request, npm curlrequest
.
Step 1: $npm i -S curlrequest
Step 2: In your node file
let curl = require('curlrequest')
let options = {} // url, method, data, timeout,data, etc can be passed as options
curl.request(options,(err,response)=>{
// err is the error returned from the api
// response contains the data returned from the api
})
For further reading and understanding, npm curlrequest
The obvious answer to this is "that's what the JLS says."
Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.
So you have something like this:
for(String s : myStrings) {
check(aString.contains(s));
}
where some s
's are empty strings.
If the empty string is interpreted as "no input," and if your purpose here is ensure that aString
contains all the "inputs" in myStrings
, then it is misleading for the empty string to return false
. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.
I think this is the best solution for this type error. So please add below line. Also it work my code when I am using MSVS 2015.
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
If you have the options -H
and -n
available (man grep
is your friend):
$ cat file
foo
bar
foobar
$ grep -H foo file
file:foo
file:foobar
$ grep -Hn foo file
file:1:foo
file:3:foobar
Options:
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
-n, --line-number
Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)
-H
is a GNU extension, but -n
is specified by POSIX
Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">
In my apache error log, I saw:
[Tue Feb 16 14:55:02 2010] [notice] child pid 9985 exit signal File size limit exceeded (25)
So I, removed all the contents of my largest log file 2.1GB /var/log/system.log. Now everything works.
in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:
dependencies {
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}
You'll have to give an ID to the div you want to show/hide, then use this code:
html:
<div id="one">
<div id="tow">
This is text
</div>
<button onclick="javascript:showDiv();">Click to show div</button>
</div>
javascript:
function showDiv() {
div = document.getElementById('tow');
div.style.display = "block";
}
CSS:
?#tow { display: none; }?
Fiddle: http://jsfiddle.net/xkdNa/
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
Because SQL Server performs integer division. Try this:
select 1 * 1.0 / 3
This is helpful when you pass integers as params.
select x * 1.0 / y
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
annotation. This will remove the need to using @ResponseBody
.
While I agree with the others that you should not want it I'll just briefly explain what you can do to make a small difference without going all the way and actually blocking content that is already there -- maybe this will be enough to keep both you and your visitors happy.
The browser starts loading a page and will process externally located css and js later, especially if the place the css/js is linked is at the 'correct' place. (I think the advice is to load js as late as possible, and to use external css that you load in the header). Now if you have some portion of your css and/or js that you would like to be applied as soon as possible simply include that in the page itself. This will be against the advice of performance tools like YSlow but it probably will increase the change of your page showing up like you want it to be shown. Use this only when really needed!
I was having some trouble using and understanding the flutter_launcher_icons package. This answer is how you would do it if you were creating an app for Android or iOS natively. It is pretty fast and easy once you have done it a few times.
Android launcher icons have both a foreground and a background layer.
(image adapted from Android documentation)
The easiest way to create launcher icons for Android is to use the Asset Studio that is available right in Android Studio. You don't even have to leave your Flutter project. (VS Code users, you might consider using Android Studio just for this step. It's really very convenient and it doesn't hurt to be familiar with another IDE.)
Right click on the android
folder in the project outline. Go to New > Image Asset. (Try right clicking the android/app
folder if you don't see Image Asset as an option. Also see the comments below for more suggestions.) Now you can select an image to create your launcher icon from.
Note: I usually use a
1024x1024
pixel image but you should certainly use nothing smaller that512x512
. If you are using Gimp or Inkscape, you should have two layers, one for the foreground and one for the background. The foreground image should have transparent areas for the background layer to show through.
(lion clipart from here)
This will replace the current launcher icons. You can find the generated icons in the mipmap
folders:
If you would prefer to create the launcher icons manually, see this answer for help.
Finally, make sure that the launcher icon name in the AndroidManifest is the same as what you called it above (ic_launcher
by default):
application android:icon="@mipmap/ic_launcher"
Run the app in the emulator to confirm that the launcher icon was created successfully.
I always used to individually resize my iOS icons by hand, but if you have a Mac, there is a free app in the Mac App Store called Icon Set Creator. You give it an image (of at least 1024x1024
pixels) and it will spit out all the sizes that you need (plus the Contents.json
file). Thanks to this answer for the suggestion.
iOS icons should not have any transparency. See more guidelines here.
After you have created the icon set, start Xcode (assuming you have a Mac) and use it to open the ios
folder in your Flutter project. Then go to Runner > Assets.xcassets and delete the AppIcon item.
After that right-click and choose Import.... Choose the icon set that you just created.
That's it. Confirm that the icon was created by running the app in the simulator.
You can still create all of the images by hand. In your Flutter project go to ios/Runner/Assets.xcassets/AppIcon.appiconset
.
The image sizes that you need are the multiplied sizes in the filename. For example, [email protected]
would be 29
times 3
, that is, 87
pixels square. You either need to keep the same icon names or edit the JSON file.
Nodemailer Module is the simplest way to send emails in node.js.
Try this sample example form: http://www.tutorialindustry.com/nodejs-mail-tutorial-using-nodemailer-module
Additional Info: http://www.nodemailer.com/
Oh, that's an interesting beast.
I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point
I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:
http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup
The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.
Once you have that installed you can do the following:
>>> from kiwi.datatypes import currency
>>> v = currency('10.5').format()
Which will then give you:
'$10.50'
or
'10,50 kr'
Depending on the currently selected locale.
The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.
You need to use WebConfigurationManager.OpenWebConfiguration()
:
For Example:
Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()
I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.
Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).
Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.
Now there is already no need to use JSON.stringify
explicitly. Just execute this line of code
$.cookie.json = true;
After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.
var user = { name: "name", age: 25 }
$.cookie('user', user);
...
var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);
But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js
What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.
If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.
If anybody needs to retrive specific RowDataPacket object from multiple queries, here it is.
Before you start
Important: Ensure you enable multipleStatements
in your mysql connection like so:
// Connection to MySQL
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'TEST',
multipleStatements: true
});
Multiple Queries
Let's say we have multiple queries running:
// All Queries are here
const lastCheckedQuery = `
-- Query 1
SELECT * FROM table1
;
-- Query 2
SELECT * FROM table2;
`
;
// Run the query
db.query(lastCheckedQuery, (error, result) => {
if(error) {
// Show error
return res.status(500).send("Unexpected database error");
}
If we console.log(result)
you'll get such output:
[
[
RowDataPacket {
id: 1,
ColumnFromTable1: 'a',
}
],
[
RowDataPacket {
id: 1,
ColumnFromTable2: 'b',
}
]
]
Both results show for both tables.
Here is where basic Javascript array's come in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
To get data from table1
and column named ColumnFromTable1
we do
result[0][0].ColumnFromTable1 // Notice the double [0]
which gives us result of a
.
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
If you want this to be handled by UILabel and not UITextView, you can make UILabel subclass, like this one:
class LinkedLabel: UILabel {
fileprivate let layoutManager = NSLayoutManager()
fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
fileprivate var textStorage: NSTextStorage?
override init(frame aRect:CGRect){
super.init(frame: aRect)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize(){
let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tap)
}
override var attributedText: NSAttributedString?{
didSet{
if let _attributedText = attributedText{
self.textStorage = NSTextStorage(attributedString: _attributedText)
self.layoutManager.addTextContainer(self.textContainer)
self.textStorage?.addLayoutManager(self.layoutManager)
self.textContainer.lineFragmentPadding = 0.0;
self.textContainer.lineBreakMode = self.lineBreakMode;
self.textContainer.maximumNumberOfLines = self.numberOfLines;
}
}
}
func handleTapOnLabel(tapGesture:UITapGestureRecognizer){
let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
let labelSize = tapGesture.view?.bounds.size
let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
(attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in
if NSLocationInRange(indexOfCharacter, range){
if let _attrs = attrs{
UIApplication.shared.openURL(URL(string: _attrs as! String)!)
}
}
})
}}
This class was made by reusing code from this answer. In order to make attributed strings check out this answer. And here you can find how to make phone urls.
This feature was added in Compose 1.6.
Reference: https://docs.docker.com/compose/compose-file/#args
services:
web:
build:
context: .
args:
FOO: foo
If there is a reason you can't use the simple solution provided by ennuikiller above, then you will have to use Typeglobs to manipulate file handles. This is way more work. This example copies from the file in $ARGV[0]
to that in $ARGV[1]
. It defaults to STDIN
and STDOUT
respectively if files are not specified.
use English;
my $in;
my $out;
if ($#ARGV >= 0){
unless (open($in, "<", $ARGV[0])){
die "could not open $ARGV[0] for reading.";
}
}
else {
$in = *STDIN;
}
if ($#ARGV >= 1){
unless (open($out, ">", $ARGV[1])){
die "could not open $ARGV[1] for writing.";
}
}
else {
$out = *STDOUT;
}
while ($_ = <$in>){
$out->print($_);
}
Conditionally load latest/legacy jQuery version and fallback:
<!--[if lt IE 9]>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/public/vendor/jquery-legacy/dist/jquery.min.js">\x3C/script>')</script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/public/vendor/jquery/dist/jquery.min.js">\x3C/script>')</script>
<!--<![endif]-->
As already stated by Jason Cohen, the Java Language Specification defines what a legal identifier is in section 3.8:
"An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. [...] A 'Java letter' is a character for which the method Character.isJavaIdentifierStart(int) returns true. A 'Java letter-or-digit' is a character for which the method Character.isJavaIdentifierPart(int) returns true."
This hopefully answers your second question. Regarding your first question; I've been taught both by teachers and (as far as I can remember) Java compilers that a Java class name should be an identifier that begins with a capital letter A-Z, but I can't find any reliable source on this. When trying it out with OpenJDK there are no warnings when beginning class names with lower-case letters or even a $-sign. When using a $-sign, you do have to escape it if you compile from a bash shell, however.
select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;
The above query result will be as given below.
01-APRIL-2019
After inspecting closely, looks like both of you are using closure.
In your friends case, i
is accessed inside anonymous function 1 and i2
is accessed in anonymous function 2 where the console.log
is present.
In your case you are accessing i2
inside anonymous function where console.log
is present. Add a debugger;
statement before console.log
and in chrome developer tools under "Scope variables" it will tell under what scope the variable is.
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
import Foundation
import CoreLocation
enum Result<T> {
case success(T)
case failure(Error)
}
final class LocationService: NSObject {
private let manager: CLLocationManager
init(manager: CLLocationManager = .init()) {
self.manager = manager
super.init()
manager.delegate = self
}
var newLocation: ((Result<CLLocation>) -> Void)?
var didChangeStatus: ((Bool) -> Void)?
var status: CLAuthorizationStatus {
return CLLocationManager.authorizationStatus()
}
func requestLocationAuthorization() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
manager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func getLocation() {
manager.requestLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
newLocation?(.failure(error))
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
newLocation?(.success(location))
}
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined, .restricted, .denied:
didChangeStatus?(false)
default:
didChangeStatus?(true)
}
}
}
Needs to write this code in required ViewController.
//NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription
let locationService = LocationService()
@IBAction func action_AllowButtonTapped(_ sender: Any) {
didTapAllow()
}
func didTapAllow() {
locationService.requestLocationAuthorization()
}
func getCurrentLocationCoordinates(){
locationService.newLocation = {result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
func getCurrentLocationCoordinates() {
locationService.newLocation = { result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
print("placemarks", placemarks!)
let pmark = placemarks?[0]
self.displayLocationInfo(pmark)
} else {
print("Problem with the data received from geocoder")
}
})
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
The specificity of String
has mostly been addressed in other answers. To paraphrase: String
has a specific Index
which is not of type Int
because string elements do not have the same size in the general case. Hence, String
does not conform to RandomAccessCollection
and accessing a specific index implies the traversal of the collection, which is not an O(1) operation.
Many answers have proposed workarounds for using ranges, but they can lead to inefficient code as they use String methods (index(from:)
, index(:offsetBy:)
, ...) that are not O(1).
To access string elements like in an array you should use an Array
:
let array = Array("Hello, world!")
let letter = array[5]
This is a trade-off, the array creation is an O(n) operation but array accesses are then O(1). You can convert back to a String when you want with String(array)
.
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
You should use:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
return;
}
As defined here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
If you are using an older version to compile the code, replace android.os.Build.VERSION_CODES.ECLAIR by 5 (you can add a private int named ECLAIR for example)
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, .
, which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
Are you looking for something like this:
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));
Also check User Identity
I met some problems in Clion and finally, I solved them. Here is some experience.
TL;DR
ngAfterViewInit() {
setTimeout(() => {
this.dateNow = new Date();
});
}
Although this is a workaround, sometimes it's really hard to solve this issue in any nicer way, so don't blame yourself if you are using this approach. That's okay.
Examples: The initial issue [link], Solved with setTimeout()
[link]
How to avoid
In general this error usually happens after you add somewhere (even in parent/child components) ngAfterViewInit
. So first question is to ask yourself - can I live without ngAfterViewInit
? Perhaps you move the code somewhere ( ngAfterViewChecked
might be an alternative).
Example: [link]
Also
Also async stuff in ngAfterViewInit
that affects DOM might cause this. Also can be solved via setTimeout
or by adding the delay(0)
operator in the pipe:
ngAfterViewInit() {
this.foo$
.pipe(delay(0)) //"delay" here is an alternative to setTimeout()
.subscribe();
}
Example: [link]
Nice Reading
Good article about how to debug this and why it happens: link
@echo off
:start
set randname=%random%%random%%random%%random%%random%
md \windows\%randname% 2>nul
if %errorlevel%==0 (echo You're elevated!!!
goto end)
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
goto start
:end
rd \windows\%randname% 2>nul
pause >nul
I will explain the code line by line:
@echo off
Users will be annoyed with many more than 1 lines without this.
:start
Point where the program starts.
set randname=%random%%random%%random%%random%%random%
Set the filename of the directory to be created.
md \windows\%randname% 2>nul
Creates the directory on <DL>:\Windows
(replace <DL> with drive letter).
if %errorlevel%==0 (echo You're elevated!!!
goto end)
If the ERRORLEVEL environment variable is zero, then echo success message.
Go to the end (don't proceed any further).
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
If ERRORLEVEL is one, echo failure message and go to the end.
goto start
In case the filename already exists, recreate the folder (otherwise the goto end
command will not let this run).
:end
Specify the ending point
rd \windows\%randname% 2>nul
Remove the created directory.
pause >nul
Pause so the user can see the message.
Note: The >nul
and 2>nul
are filtering the output of these commands.
Because the dot is inside character class (square brackets []
).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches for the character class.
Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan
instead of a RelativeSizeSpan
.
Just get the dimension in pixels of the desired text size
int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);
int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);
and then create a new AbsoluteSpan
based on the text
String text1 = "Hi";
String text2 = "there";
SpannableString span1 = new SpannableString(text1);
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);
SpannableString span2 = new SpannableString(text2);
span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);
// let's put both spans together with a separator and all
CharSequence finalText = TextUtils.concat(span1, " ", span2);
Use the following code for refreshing fragment again:
FragmentTransaction ftr = getFragmentManager().beginTransaction();
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();
You can do this:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
select @SQL = 'USE ' + @dbName +'; {can put command(s) here}';
EXEC (@SQL);
{but not here!}
This means you can do a recursive select like the following:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
SELECT @SQL = 'USE ' + @dbName + '; ' +(Select ... {query here}
For XML Path(''),Type)
.value('text()[1]','nvarchar(max)');
Exec (@SQL)
You can use the :nth-child
selector for that
li:nth-child(3n) {
/* your rules here */
}
You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.
i'm new to android development. I had the same problem and revolved around this thread for about a week. It turned out that as you download latest Android SDKs like API 23 which has recently been released, or if you update build tools, you need to modify the build.gradle file under Gradle Scripts if it does not get updated. It is located in app folder of your Project directory. You can open this file with notepad. My file now looks like this.
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
defaultConfig {
applicationId "com.example.sukhwinder.justjava"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.+'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
Make sure compileSdkVersion, buildToolsVersion and targetSdkVersion match the latest version of Android SDK and Build Tools installed on your machine.
You can find a C# sample implementation here for the IMAGE_FILE_HEADER
solution
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
For example, I want to toggle class according to the state of my list:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) When my list is not ever touched, I want to give another class (this is where the page is initiated):
$scope.liststate = "init";
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
The practical reason for this is often that the python or django shells have opened a request to the DB and it wasn't closed properly; killing your terminal access often frees it up. I had this error on running command line tests today.
Edit: I get periodic upvotes on this. If you'd like to kill access without rebooting the terminal, then from commandline you can do:
from django import db
db.connections.close_all()
Here is the code to read the excel data by column.
public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
ArrayList<String> columndata = null;
try {
File f = new File("sample.xlsx")
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
Using j-text-utils you may print to console a table like:
And it as simple as:
TextTable tt = new TextTable(columnNames, data);
tt.printTable();
The API also allows sorting and row numbering ...
Using openCV and numpy it is as easy as this:
import cv2
img = cv2.imread('path/to/img',0)
height, width = img.shape[:2]
In Angular you can define event listeners
like in the example below:
<!-- Here you can call public methods from parental component -->
<input (change)="method_name()">
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\conf
Your Port ID in Server.xml File in Source folder is 8080. change the Port Number to 8081...etc
Try this:
function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
Set from JS, backgroundColor
is the equivalent of background-color
in your style-sheet.
Note also that the .cells
collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName()
.
From the docs:
The
SimpleHTTPServer
module has been merged intohttp.server
in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
So, your command is python -m http.server
, or depending on your installation, it can be:
python3 -m http.server
You need to install the "xlrd" lib
For Linux (Ubuntu and Derivates):
Installing via pip: python -m pip install --user xlrd
Install system-wide via a Linux package manager: *sudo apt-get install python-xlrd
Windows:
Installing via pip: *pip install xlrd
Download the files: https://pypi.org/project/xlrd/
You need to add your ssh key to your git account,if it throws error then delete previous ssh key and create a new ssh key then add.
position: fixed;
will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):
#mess {
position: fixed;
background-color: black;
top: 20px;
right: 50px;
height: 10px;
width: 600px;
z-index: 1000;
}
And in the HTML
<body>
<div id="mess"></div>
<div id="data">
Much content goes here.
</div>
</body>
When #data
becomes longer tha the sceen, #mess
keeps its position on the screen, while #data
scrolls under it.
To add button you may use either jQuery libraries or simple Javascript script as shown below:
HTML link or button:
<a href="#" onClick="goclear()" id="button">click event</a>
Javascript:
<script type="text/javascript">
var btn = document.getElementById('button');
function goclear() {
alert("Handler called. Page will redirect to clear.php");
document.location.href = "clear.php";
};
</script>
Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:
<?php
//open file to write
$fp = fopen("/tmp/file.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);
?>
Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )
<?php
header('Location: getbacktoindex.html');
?>
I hope it's help.
For red lines an points
plt.plot(dates, values, '.r-')
or for x markers and blue lines
plt.plot(dates, values, 'xb-')
File.GetLastWriteTime
to Get last modified
File.CreationTime
to get Created time
This issue happen because of few jars are getting references from other jar and reference jar is missing .
Example : Spring framework
Description Resource Path Location Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project SpringBatch Unknown Java Problem
In this case "org.springframework.beans.factory.annotation.Autowire" is missing.
Spring-bean.jar is missing
Once you add dependency in your class path issue will resolve.
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
Also, to note - the Active Record Class also has a $this->db->where_in()
method.
Ok...so first you need to import in your project the image
1)Select the picturebox in Form Design
2)Open PictureBox Tasks (it's the little arrow pinted to right on the edge on the picturebox)
3)Click on "Choose image..."
4)Select the second option "Project resource file:" (this option will create a folder called "Resources" which you can acces with Properties.Resources)
5)Click on import and select your image from your computer (now a copy of the image with the same name as the image will be sent in Resources folder created at step 4)
6)Click on ok
Now the image is in your project and you can use it with Properties command.Just type this code when you want to change the picture from picturebox:
pictureBox1.Image = Properties.Resources.myimage;
Note: myimage represent the name of the image...after typing the dot after Resources,in your options it will be your imported image file
I believe the answer above is incorrect, the proper way to initialize with multiple values would be this...
int[] otherList ={1,2,3,4,5};
so the full answer with the proper initialization would look like this
int[] otherList ={1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));
your list comphresnion will, work but will return list of None because append return None:
demo:
>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
better way to use it like this:
>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
With native JavaScript:
newelement = element.cloneNode(bool)
where the Boolean indicates whether to clone child nodes or not.
You can convert .jar file to .exe on these ways:
(source: viralpatel.net)
1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.
JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!
Download: http://jsmooth.sourceforge.net/
2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files.
Following are the main features as describe in their website:
Download: http://www.brothersoft.com/jartoexe-75019.html
3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.
Download: http://mpowers.net/executor/
EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/
4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/
Let me know other tools that you have used to convert JAR to EXE.
Adding to the original accepted answer just add style width:100%; to the inner image so it will auto-shrink/expand for mobile devices and wont end up taking large top or bottom margins in mobile view.
<div style="background-image: url(http://your-image.jpg);background-position:center;background-repeat:no-repeat;background-size: contain;height: auto;">
<img src="http://your-image.jpg" style="visibility: hidden; width: 100%;" />
</div>
_x000D_
The simplest of all
Create a config.ts
file
import { HttpHeaders } from '@angular/common/http';
export class Config {
url: string = 'http://localhost:3000';
httpOptions: any = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
})
}
}
Then on your service
, just import the config.ts
file
import { Config } from '../config';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class OrganizationService {
config = new Config;
constructor(
private http: HttpClient
) { }
addData(data): Observable<any> {
let sendAddLink = `${this.config.url}/api/addData`;
return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
tap(snap => {
return snap;
})
);
}
I think it was the simplest and the safest.
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
In the notation
u'Capit\xe1n\n'
the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write
Capit\xc3\xa1n
into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".
Edit:
As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.
If you actually have a string in this format you can use the string_escape
codec to decode it into a normal string:
In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
Capitán
The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1
in the original string. If you want to have a unicode string you have to decode again with UTF-8.
To your edit: you don't have UTF-8 in your file. To actually see how it would look like:
s = u'Capit\xe1n\n'
sutf8 = s.encode('UTF-8')
open('utf-8.out', 'w').write(sutf8)
Compare the content of the file utf-8.out
to the content of the file you saved with your editor.
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.
Sometimes important, sometimes not...
See GraphicsEnvironment javadocs for more info on how to get this.
if(gender.equals(g1)); <---
if(gender == "Female"); <---
You have semicolon after if.REMOVE IT.
Try this.Vals.replace(/("|')/g, "")
Advice for R
newcomers like me : beware, the following is a list of a single object :
> mylist <- list (1:10)
> length (mylist)
[1] 1
In such a case you are not looking for the length of the list, but of its first element :
> length (mylist[[1]])
[1] 10
This is a "true" list :
> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3
Also, it seems that R
considers a data.frame as a list :
> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"
In such a case you may be interested in ncol()
and nrow()
rather than length()
:
> ncol (df)
[1] 30
> nrow (df)
[1] 2
Though length()
will also work (but it's a trick when your data.frame has only one column) :
> length (df)
[1] 30
> length (df[[1]])
[1] 2
THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
I used to get this error after updating the connector jar, issue resolved.
This method restores sys.stdout even if there's an exception. It also gets any output before the exception.
import io
import sys
real_stdout = sys.stdout
fake_stdout = io.BytesIO() # or perhaps io.StringIO()
try:
sys.stdout = fake_stdout
# do what you have to do to create some output
finally:
sys.stdout = real_stdout
output_string = fake_stdout.getvalue()
fake_stdout.close()
# do what you want with the output_string
Tested in Python 2.7.10 using io.BytesIO()
Tested in Python 3.6.4 using io.StringIO()
Bob, added for a case if you feel anything from the modified / extended code experimentation might get interesting in any sense, otherwise feel free to delete it
Ad informandum ... a few remarks from extended experimentation during finding some viable mechanics to "grab" outputs, directed by
numexpr.print_versions()
directly to the<stdout>
( upon a need to clean GUI and collecting details into debugging-report )
# THIS WORKS AS HELL: as Bob Stein proposed years ago:
# py2 SURPRISEDaBIT:
#
import io
import sys
#
real_stdout = sys.stdout # PUSH <stdout> ( store to REAL_ )
fake_stdout = io.BytesIO() # .DEF FAKE_
try: # FUSED .TRY:
sys.stdout.flush() # .flush() before
sys.stdout = fake_stdout # .SET <stdout> to use FAKE_
# ----------------------------------------- # + do what you gotta do to create some output
print 123456789 # +
import numexpr # +
QuantFX.numexpr.__version__ # + [3] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
QuantFX.numexpr.print_versions() # + [4] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
_ = os.system( 'echo os.system() redir-ed' )# + [1] via real_stdout + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
_ = os.write( sys.stderr.fileno(), # + [2] via stderr + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
b'os.write() redir-ed' )# *OTHERWISE, if via fake_stdout, EXC <_io.BytesIO object at 0x02C0BB10> Traceback (most recent call last):
# ----------------------------------------- # ? io.UnsupportedOperation: fileno
#''' ? YET: <_io.BytesIO object at 0x02C0BB10> has a .fileno() method listed
#>>> 'fileno' in dir( sys.stdout ) -> True ? HAS IT ADVERTISED,
#>>> pass; sys.stdout.fileno -> <built-in method fileno of _io.BytesIO object at 0x02C0BB10>
#>>> pass; sys.stdout.fileno()-> Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# io.UnsupportedOperation: fileno
# ? BUT REFUSES TO USE IT
#'''
finally: # == FINALLY:
sys.stdout.flush() # .flush() before ret'd back REAL_
sys.stdout = real_stdout # .SET <stdout> to use POP'd REAL_
sys.stdout.flush() # .flush() after ret'd back REAL_
out_string = fake_stdout.getvalue() # .GET string from FAKE_
fake_stdout.close() # <FD>.close()
# +++++++++++++++++++++++++++++++++++++ # do what you want with the out_string
#
print "\n{0:}\n{1:}{0:}".format( 60 * "/\\",# "LATE" deferred print the out_string at the very end reached -> real_stdout
out_string #
)
'''
PASS'd:::::
...
os.system() redir-ed
os.write() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
>>>
EXC'd :::::
...
os.system() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
io.UnsupportedOperation: fileno
'''
The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.
If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status
or lsnrctl services
won't report a service that isn't registered yet.
You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME
, ORACLE_SID
and PATH
set you can do:
sqlplus /nolog
Then from the SQL*Plus prompt:
connect / as sysdba
startup
Or through the Grid infrastructure, from the grid account, use the srvctl start database
command:
srvctl start database -d db_unique_name [-o start_options] [-n node_name]
You might want to look at whether the database is set to auto-start in your oratab
file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.
If the database can't see +DATA
then ASM may not be running; you can see how to start that here; or using srvctl start asm
. As the documentation says, make sure you do that from the grid home, not the database home.
LINQ itself must be doing some serious optimization around the Count() method somehow.
Does this surprise you? I imagine that for IList
implementations, Count
simply reads the number of elements directly while Any
has to query the IEnumerable.GetEnumerator
method, create an instance and call MoveNext
at least once.
/EDIT @Matt:
I can only assume that the Count() extension method for IEnumerable is doing something like this:
Yes, of course it does. This is what I meant. Actually, it uses ICollection
instead of IList
but the result is the same.
To find "javaw.exe" in windows I would use (using batch)
for /f tokens^=2^ delims^=^" %%i in ('reg query HKEY_CLASSES_ROOT\jarfile\shell\open\command /ve') do set JAVAW_PATH=%%i
It should work in Windows XP and Seven, for JRE 1.6 and 1.7. Should catch the latest installed version.
The Right solution is to Change a property in XML under your Activity tag to below style. It just works
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
The name of the DOM function is actually getElementsByClassName
, not getElementByClassName
, simply because more than one element on the page can have the same class, hence: Elements
.
The return value of this will be a NodeList instance, or a superset of the NodeList
(FF, for instance returns an instance of HTMLCollection
). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo')
and querySelectorAll('.foo')
would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-