172.17.0.0/16
as IP address range, not 172.17.0.0/32
.localhost
to connect to the PostgreSQL database on your host, but the host's IP instead. To keep the container portable, start the container with the --add-host=database:<host-ip>
flag and use database
as hostname for connecting to PostgreSQL.localhost
. Look for the setting listen_addresses
in PostgreSQL's configuration file, typically found in /etc/postgresql/9.3/main/postgresql.conf
(credits to @DazmoNorton).172.17.0.0/32
is not a range of IP addresses, but a single address (namly 172.17.0.0
). No Docker container will ever get that address assigned, because it's the network address of the Docker bridge (docker0
) interface.
When Docker starts, it will create a new bridge network interface, that you can easily see when calling ip a
:
$ ip a
...
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
valid_lft forever preferred_lft forever
As you can see, in my case, the docker0
interface has the IP address 172.17.42.1
with a netmask of /16
(or 255.255.0.0
). This means that the network address is 172.17.0.0/16
.
The IP address is randomly assigned, but without any additional configuration, it will always be in the 172.17.0.0/16
network. For each Docker container, a random address from that range will be assigned.
This means, if you want to grant access from all possible containers to your database, use 172.17.0.0/16
.
You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.
Here is the command:
version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus
curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz
I've been in this situation, but I found a solution with the Handler Object.
In my case, I want to update a ProgressDialog with the observer pattern. My view implements observer and overrides the update method.
So, my main thread create the view and another thread call the update method that update the ProgressDialop and....:
Only the original thread that created a view hierarchy can touch its views.
It's possible to solve the problem with the Handler Object.
Below, different parts of my code:
public class ViewExecution extends Activity implements Observer{
static final int PROGRESS_DIALOG = 0;
ProgressDialog progressDialog;
int currentNumber;
public void onCreate(Bundle savedInstanceState) {
currentNumber = 0;
final Button launchPolicyButton = ((Button) this.findViewById(R.id.launchButton));
launchPolicyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading");
progressDialog.setCancelable(true);
return progressDialog;
default:
return null;
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case PROGRESS_DIALOG:
progressDialog.setProgress(0);
}
}
// Define the Handler that receives messages from the thread and update the progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int current = msg.arg1;
progressDialog.setProgress(current);
if (current >= 100){
removeDialog (PROGRESS_DIALOG);
}
}
};
// The method called by the observer (the second thread)
@Override
public void update(Observable obs, Object arg1) {
Message msg = handler.obtainMessage();
msg.arg1 = ++currentPluginNumber;
handler.sendMessage(msg);
}
}
This explanation can be found on this page, and you must read the "Example ProgressDialog with a second thread".
First, you do not need android:process=":remote"
, so please remove it, since all it will do is take up extra RAM for no benefit.
Second, since the <service>
element contains an action string, use it:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=new Intent("com.sample.service.serviceClass");
this.startService(intent);
}
@vagoberto's answer seems the best IMHO if you need positional arguments, and I have a small improvement to add.
vagoberto's suggestion:
#!/usr/local/bin/gnuplot --persist
THIRD=ARG3
print "script name : ", ARG0
print "first argument : ", ARG1
print "third argument : ", THIRD
print "number of arguments: ", ARGC
which gets called by:
$ gnuplot -c script.gp one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
for those lazy typers like myself, one could make the script executable (chmod 755 script.gp
)
then use the following:
#!/usr/bin/env gnuplot -c
THIRD=ARG3
print "script name : ", ARG0
print "first argument : ", ARG1
print "third argument : ", THIRD
print "number of arguments: ", ARGC
and execute it as:
$ ./imb.plot a b c d
script name : ./imb.plot
first argument : a
third argument : c
number of arguments: 4
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
how about window.location.replace(window.location.href);
Simple solution with an example :
<div id="id_div">
<p>content<p>
</div>
Move this DIV to other DIV with id = "other_div_id"
$('#other_div_id').prepend( $('#id_div') );
Finish
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
The application/x-www-form-urlencoded
Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:
curl -X DELETE "http://localhost:5000/locations?id=3"
or
curl -X GET "http://localhost:5000/locations?id=3"
I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready
opened the httpd.conf and changed the listen port from 80 to 1234 in both places
Listen 1234
Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234
That worked.
Make sure there are no spaces in your Xcode application name (can happen if you keep older versions around - for example renaming it 'Xcode 4.app'); build tools will be referenced within the Xcode bundle paths, and many scripts can't handle references with spaces properly.
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
For Java 8 you can use the following command line to get the heap space utilization in kB:
jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'
The command basically sums up:
You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.
I had a long-running next-version
branch with tons of deletions to files that had changed on develop
, files that had been added in different places on both branches, etc.
I wanted to take the entire contents of the next-version
branch into develop
, all in one whopping merge commit.
The combination of the above commands that worked for me was:
git merge -X theirs next-version
# lots of files left that were modified on develop but deleted on next-version
git checkout next-version .
# files removed, now add the deletions to the commit
git add .
# still have files that were added on develop; in my case they are all in web/
git rm -r web
Not a new answer, just combining bits from many answers, partly to reassure that you might need all of these answers.
Summary: Instead of a.f();
it should be a->f();
In main you have defined a as a pointer to object of A, so you can access functions using the ->
operator.
An alternate, but less readable way is (*a).f()
a.f()
could have been used to access f(), if a was declared as:
A a;
If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.
package main
import (
"fmt"
"reflect"
)
type Student struct {
Fname string
Lname string
City string
Mobile int64
}
func main() {
s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
v := reflect.ValueOf(s)
typeOfS := v.Type()
for i := 0; i< v.NumField(); i++ {
fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
}
}
Run in playground
Note: If the Fields in your struct are not exported then the v.Field(i).Interface()
will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.
For me it was a fresh NetCore application that was just not loading via IIS. When run standalone it was OK though.
I removed the <aspNetCore
line and then I got a normal error message from IIS saying that NetCoreModule could not be loaded. That module is required to understand this new web.config line.
The error message 0x8007000d
actually says that the web.config is malformed and that error shows up before the error loading module making this error message really crap. (and an unfortunate race condition problem)
I installed the NetCoreSDK and stopped and started IIS (restart didnt work)
The NetCore API started working via IIS as expected.
Don't know if this will help anyone, but I solved a similar problem by specifying specific width sizes in percentage for each column. Obviously, this would work best if each column has content with width that doesn't vary too widely.
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
<asp:TextBox runat="server" ID="txtPassword" placeholder="Password">
This will work you might some time feel that it is not working due to Intellisence not showing placeholder
I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like
I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context
kubectl config get-contexts
I know this is quite a few years later but here are some interesting plugins. I have not tried either of these yet so YMMV.
https://github.com/mikelue/vim-maven-plugin
https://github.com/vim-scripts/maven-ide
EDIT: Oh an BTW, i've tried eclim off and on, but the reason I like vim is its lightness. Executing eclipse even on headless mode is just too much mental lifting for me.
EDIT2: I've been using playframework lately and this will probably work with maven builds too:
For compiling, you can configure VIM's make to run maven or in my case, run a build script, tee that to a file.
autocmd Filetype java setl makeprg=play_compile
autocmd Filetype java setl efm=%A\ %#[error]\ %f:%l:\ %m,%-Z\ %#[error]\ %p^,%-C%.%#
"play_compile" is just a compile script. It uses SBT so Maven should work just fine here. Even direct javac will work. This way, you can use VIM"s quickfix buffer (:cnext, :clist: cprev, etc).
For jumping around the classes, I use ctrl-p. Its beautiful. Use it. Faster than eclipse in jumping around files.
For jumping around methods, I use tagsearch with exuberant c-tags. Jump into method declarations by using ctrl-]. Go back using Ctrl-o. Doesnt work as good as eclipse, but it works good enough.
I use supertab for code completion. Javacomplete is pretty slow, so I stick with omni-complete. Again, not as accurate as eclipse, but its fast and works good enough for me.
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Windows Batch File Looping Through Directories to Process Files?
By using document.getElementById()
function you don't have to pass #
before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo: JSFiddle
Just /
refers to the root of your website from the public html folder. DOCUMENT_ROOT
refers to the local path to the folder on the server that contains your website.
For example, I have EasyPHP setup on a machine...
$_SERVER["DOCUMENT_ROOT"]
gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www
but any file I link to with just /
will be relative to my www
folder.
If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT
. if you want to give the absolute path to a file from your website's root, use just /
.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
if(!file3.exists()){
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null) fop.write(nodeValue.getBytes());
fop.write("\n".getBytes());
fop.flush();
fop.close();
You need to add a newline at the end of each write.
One way to do it is to check what mysql_num_rows
returns. A minimal complete example would be the following:
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
// there are results in $result
} else {
// no results
}
But it's recommended that you check the return value of mysql_query
and handle it properly in the case it's false
(which would be caused by an error); probably by also calling mysql_error
and logging the error somewhere.
Use:
.content {
background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
}
.displaybg {
text-align: center;
color: #FFF;
}
If you are using systemd I just found out that you seem to have to add them to the systemd unit file. This on Ubuntu 16. Putting them into the .profile and .bashrc (even the /etc/profile) resulted in the ENV Vars not being available in the juypter notebooks.
I had to edit:
/lib/systemd/system/jupyer-notebook.service
and put in the variable i wanted to read in the unit file like:
Environment=MYOWN_VAR=theVar
and only then could I read it from within juypter notebook.
http://wiki.bash-hackers.org/scripting/posparams
It explains the use of shift
(if you want to discard the first N parameters) and then implementing Mass Usage
Python 3: new exec (execfile dropped) !
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0's changelog and Hi-Angels comment suggest:
use
exec(open(<filename.py>).read())
instead of
execfile(<filename.py>)
{=FIND("cell I want to search","list of words I want to search for")}
{=SUM(FIND($A$1:$A$100&"|";A3))}
this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)From the Android Developer Site link
"adjustResize"
The activity's main window is always resized to make room for the soft keyboard on screen.
"adjustPan"
The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.
according to your comment, use following in your activity manifest
<activity android:windowSoftInputMode="adjustResize"> </activity>
Rails got ActiveSupport::CoreExtensions::String::Inflections
module that provides such methods. They're all worth looking at. For your example:
'Book Author Title'.parameterize.underscore.to_sym # :book_author_title
If you want to restrict it to one line, use white-space: nowrap;
on the div.
This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.
The problem was in the JDK source code for WindowsPreferences.java
. In this class, both nodes userRoot
and systemRoot
were declared static as in:
/**
* User root node.
*/
static final Preferences userRoot =
new WindowsPreferences(USER_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
/**
* System root node.
*/
static final Preferences systemRoot =
new WindowsPreferences(SYSTEM_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
(= system tree) will be attempted to be created if it doesn't already exist.
So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot
, thus causing the warning. It is an interesting subtle bug.
There's a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There's also a backport for Java8 which is in u202.
What you see is really a warning from the JDK's internal logger. It is not an exception. I believe that the warning can be safely ignored .... unless the user code is indeed wanting the system preferences, but that is very rarely the case.
The bug did not reveal itself in versions prior to Java 1.7.21, because up until then the JRE installer would create Registry key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
for you and this would effectively hide the bug. On the other hand you've never really been required to run an installer in order to have a JRE on your machine, or at least this hasn't been Sun/Oracle's intent. As you may be aware Oracle has been distributing the JRE for Windows in .tar.gz
format for many years.
For some reasons above mentioned approaches did now work for me, before I followed the advice to add .default
like this:
<div>
<img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>
Simply, this should do the task:
import pandas as pd
grouped_df = df1.groupby( [ "Name", "City"] )
pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
Here, grouped_df.size()
pulls up the unique groupby count, and reset_index()
method resets the name of the column you want it to be.
Finally, the pandas Dataframe()
function is called upon to create a DataFrame object.
Use SelectList to bind @HtmlDropdownListFor and specify selectedValue parameter in it.
http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx
Example : you can do like this for getting venderid
@Html.DropDownListFor(m => m.VendorId,Model.Vendor)
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public int VenderID{get;set;}
}
[HttpPost]
public ActionResult Action(MobileViewModel model)
{
var Id = model.VenderID;
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
All you need is a DTO with a constructor :
public class User2DTO implements Serializable {
/** pode ser email ou id do Google comecando com G ou F para Facebook */
private String username;
private String password;
private String email;
private String name;
private Integer loginType;
public User2DTO(Object...fields) {
super();
this.username = (String) fields[0];
this.name = (String) fields[1];
this.email = (String) fields[2];
this.password = (String) fields[3];
this.loginType = (Integer) fields[4];
}
and call it :
EntityManager em = repo.getEntityManager();
Query q = em.createNativeQuery("SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u");
List<Object[]> objList = q.getResultList();
List<User2DTO> ooBj = objList.stream().map(User2DTO::new).collect(Collectors.toList());
This works too:
var exeBlk = {
() -> Void in
}
exeBlk = {
//do something
}
//instead of nil:
exeBlk = {}
I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT
(instead of SHOW
). Below query easily narrows down the search to tables that contain "keyword"
SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"
For anyone using Koa and koa-passport:
Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:
this.session.passport.user
When you set in done(null, user)
in deserializeUser where 'user' is some user object from your database:
this.req.user
OR
this.passport.user
for some reason this.user
Koa context never gets set when you call done(null, user) in your deserializeUser method.
So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:
app.use(function * setUserInContext (next) {
this.user = this.req.user
yield next
})
If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher
use zzz instead of TZD
Example:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
Response:
2011-08-09T11:50:00:02+02:00
My approach. Tricky, but works well for me
<p> </p>
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
private void buttonHook_Click(object sender, EventArgs e)
{
// Hooks only into specified Keys (here "A" and "B").
// (***) Use this constructor
_globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });
// Hooks into all keys.
// (***) Or this - not both
_globalKeyboardHook = new GlobalKeyboardHook();
_globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}
And then is working fine.
Center-block is also an option not referred in above answers
<div class="center-block" style="width:200px;background-color:#ccc;">...</div>
All the class center-block
does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from, so it will not center itself as anticipated.
So text-center is a better option.
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
Using the FM
format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.
. You can use rtrim
to get rid of that:
select to_char(a, '99D90'),
to_char(a, '90D90'),
to_char(a, 'FM90D99'),
rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
select 50 a from dual
union all select 50.57 from dual
union all select 5.57 from dual
union all select 0.35 from dual
union all select 0.4 from dual
)
order by a;
TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
.35 0.35 0.35 0.35
.40 0.40 0.4 0.4
5.57 5.57 5.57 5.57
50.00 50.00 50. 50
50.57 50.57 50.57 50.57
Note that I'm using to_char(0, 'D')
to generate the character to trim, to match the decimal separator - so it looks for the same character, ,
or .
, as the first to_char
adds.
The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad
, which starts to make it look a bit complicated:
...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...
TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
.35 0.35 0.35 0.35 0.35
.40 0.40 0.4 0.4 0.4
5.57 5.57 5.57 5.57 5.57
50.00 50.00 50. 50 50
50.57 50.57 50.57 50.57 50.57
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript
Basically:
daySelect = document.getElementById('daySelect');
daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');
probably graded as a non-pythonic way to do this but this'll give the result you want in a line:
new_df = pd.DataFrame(zip(email,list))
Result:
email list
0 [email protected] [1.0, 0.0, 0.0]
1 [email protected] [2.0, 0.0, 0.0]
2 [email protected] [1.0, 0.0, 0.0]
3 [email protected] [4.0, 0.0, 3.0]
4 [email protected] [1.0, 5.0, 0.0]
The scenario is like that: The user requests a file to do something. Then, if the user sends the same request again, it informs the user that the second request is not done until the first request finishes. That's why, I use lock-mechanism to handle this issue.
Here is my working code:
from lockfile import LockFile
lock = LockFile(lock_file_path)
status = ""
if not lock.is_locked():
lock.acquire()
status = lock.path + ' is locked.'
print status
else:
status = lock.path + " is already locked."
print status
return status
There is a constructor accepting two pointer parameters, so the code is simply
std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));
this is also going to be as efficient as std::string cppstr(cstr)
if the length is smaller than max_length
.
The issue is that you are trying to have multiple statements in an if
without using {}
.
What you currently have is interpreted like:
if( choice==5 )
{
System.out.println( ... );
}
break;
else
{
//...
}
You really want:
if( choice==5 )
{
System.out.println( ... );
break;
}
else
{
//...
}
Also, as Farce has stated, it would be better to use else if
for all the conditions instead of if
because if choice==1
, it will still go through and check if choice==5
, which would fail, and it will still go into your else block.
if( choice==1 )
//...
else if( choice==2 )
//...
else if( choice==3 )
//...
else if( choice==4 )
//...
else if( choice==5 )
{
//...
}
else
//...
A more elegant solution would be using a switch
statement. However, break
only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:
LOOP:
for(;;)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch( choice )
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
case 2:
options();
break;
case 4:
credits();
break;
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
break LOOP;
default:
System.out.println( ... );
}
}
Instead of labeling the loop, you could also use a flag to tell the loop to stop.
bool finished = false;
while( !finished )
{
switch( choice )
{
// ...
case 5:
System.out.println( ... )
finished = true;
break;
// ...
}
}
Yes, reload the css tag. And remember to make the new url unique (usually by appending a random query parameter). I have code to do this but not with me right now. Will edit later...
edit: too late... harto and nickf beat me to it ;-)
This is a stupid/hacky way
print count,
print conv
I think about it in terms of information. Any problem consists of learning a certain number of bits.
Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log2 of the inverse probability of that branch. That's how much you learn by executing that decision.
For example, an if
statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.
Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.
That's what you get with binary search.
Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.
Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.
Now think about sorting. You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.
So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.
I've found that nearly all algorithmic performance issues can be looked at in this way.
If your building that SQL in a tool like TOAD or other SQL oriented IDE they often have copy markup to the clipboard. For example, TOAD has a CTRL+M which takes the SQL in your editor and does exactly what you have in your code above. It also covers the reverse... when your grabbing a formatted string out of your Java and want to execute it in TOAD. Pasting the SQL back into TOAD and perform a CTRL+P to remove the multi-line quotes.
You need to go into your Attribute Inspector and add a name for your cells Identifier:
Then you need to make your identifier match with your dequeue like this:
let cell2 = tableView.dequeueReusableCellWithIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCell
Alternatively
If you're working with a nib you may need to register your class in your cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwitchCell")
// included for context
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell
//... continue
}
Apples's UITableView Class Reference says:
Prior to dequeueing any cells, call this method or the registerNib:forCellReuseIdentifier: method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.
If you previously registered a class or nib file with the same reuse identifier, the class you specify in the cellClass parameter replaces the old entry. You may specify nil for cellClass if you want to unregister the class from the specified reuse identifier.
Here's the code from Apples Swift 2.0 framework:
// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.
@available(iOS 5.0, *)
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String)
@available(iOS 6.0, *)
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String)
<center><form></form></center>
does work in most cases like The Wobbuffet mentioned above...
This is what solved my problem. ^M is a carriage return, and it can be easily avoided in a Perl script.
while(<INPUTFILE>)
{
chomp;
chop($_) if ($_ =~ m/\r$/);
}
Your getElementById
is looking for an element with id "myclass", but in your html the id of the DIV is showhide
. Change to:
<script>
function changeclass() {
var NAME = document.getElementById("showhide")
NAME.className="mynewclass"
}
</script>
Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
this solved it to me:
sudo apt-get update
sudo apt-get install libglfw3
sudo apt-get install libglfw3-dev
taken from https://github.com/glfw/glfw/issues/808
To let MySql generate sequence numbers for an AUTO_INCREMENT
field you have three options:
...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
These three statements will produce the same result:
$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";
bool is a fundamental datatype in C++. Converting true
to an integer type will yield 1, and converting false
will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like
enum bool {
false, true
};
So did the Windows API. Starting with C99, we have _Bool
as a basic data type. Including stdbool.h
will typedef #define
that to bool
and provide the constants true
and false
. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.
qImageView.setImageResource(R.drawable.img2);
I think this will help you
You can give this a try. I am quite new to the forum but wanted to offer something that worked for me since I've gotten so much help from this site in the past. This is essentially a variation of the above, but I found it simpler.
Just paste this into the Userform_Initialize section of your userform code. Note you must already have a listbox on the userform or have it created dynamically above this code. Also please note the Array is a list of headings (below as "Header1", "Header2" etc. Replace these with your own headings. This code will then set up a heading bar at the top based on the column widths of the list box. Sorry it doesn't scroll - it's fixed labels.
More senior coders - please feel free to comment or improve this.
Dim Mywidths As String
Dim Arrwidths, Arrheaders As Variant
Dim ColCounter, Labelleft As Long
Dim theLabel As Object
[Other code here that you would already have in the Userform_Initialize section]
Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
With theLabel
.Left = ListBox1.Left
.Top = ListBox1.Top - 10
.Width = ListBox1.Width - 1
.Height = 10
.BackColor = RGB(200, 200, 200)
End With
Arrheaders = Array("Header1", "Header2", "Header3", "Header4")
Mywidths = Me.ListBox1.ColumnWidths
Mywidths = Replace(Mywidths, " pt", "")
Arrwidths = Split(Mywidths, ";")
Labelleft = ListBox1.Left + 18
For ColCounter = LBound(Arrwidths) To UBound(Arrwidths)
If Arrwidths(ColCounter) > 0 Then
Header = Header + 1
Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
With theLabel
.Caption = Arrheaders(Header - 1)
.Left = Labelleft
.Width = Arrwidths(ColCounter)
.Height = 10
.Top = ListBox1.Top - 10
.BackColor = RGB(200, 200, 200)
.Font.Bold = True
End With
Labelleft = Labelleft + Arrwidths(ColCounter)
End If
Next
click link get example file upload clint java with apache HttpComponents
and library downalod link
https://hc.apache.org/downloads.cgi
use 4.5.3.zip it's working fine in my code
and my working code..
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");
FileBody bin = new FileBody(new File("E:\\meter.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
You can use the utility method in Collections
class
public static <T extends Comparable<? super T>> void sort(List<T> list)
or
public static <T> void sort(List<T> list,Comparator<? super T> c)
Refer to Comparable
and Comparator
interfaces for more flexibility on sorting the object.
You can use this method to log the exception stack to String
public String stackTraceToString(Throwable e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace()) {
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
Close any other node servers that are running, even if they are in other terminal windows or running on different ports. That should fix the problem.
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
http://greptweet.com/ is an attempt to surpass the 3200 limit by backing up tweets, and besides that is useful for simple searches.
Extract numbers from any string at beginning position.
x <- gregexpr("^[0-9]+", years) # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))
Extract numbers from any string INDEPENDENT of position.
x <- gregexpr("[0-9]+", years) # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))
User can use this
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date
yyyy/MM/dd HH:mm:ss
You should preferably only have your component depend on state and props and it will work as expected, but if you really need a function to force the component to re-render, you could use the useState
hook and call the function when needed.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
function Foo() {_x000D_
const [, forceUpdate] = useState();_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(forceUpdate, 2000);_x000D_
}, []);_x000D_
_x000D_
return <div>{Date.now()}</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Foo />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
EDIT: If this is happening on mint/ubuntu, it is likely because you installed vscode through the software manager. This will cause other problems during debugging. Instead install it using the .deb file on the vscode website.
If you really want to use the software manager, the solution below still works:
use find / -name code 2> /dev/null
to find the path to the visual studio bin file. It should end in /extra/vscode/bin/code
If you're using the mint software manager, you might only find paths with a ridiculously long name in the middle like this:
".../stable/7a22830d9e8fbbdc9627e43e072005eef66c14d2a4dd19992427ef4de060186a/..."
Just replace the long part with "/active/"
Once you have it, create a sym link:
ln -s path_you_found/extra/vscode/bin/code /usr/local/bin/code
If you don't have the rights, or only want it to be accessible for yourself, simply add this line to your .bashrc / .zshrc:
export PATH="$PATH:path_you_found/extra/vscode/bin/
Note that I removed the 'code' filename at the end
use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them
window.location is an object, not a string so you need to use window.location.href to get the actual string url
if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
alert("found it");
}
Spot on!!
You can use below query to remove all the tables from database
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
Happy coding !
The same problem occurred for me when iI was installing a python library and it said unable to find the path of Visual Studio 2008/10. I have change the PATH from environmental variables. So to change it you the following process can be adopted: Start=> Computer=>Properties=>Advance System Settings=>Environment Variables=>System Variables. Here you will find path variable. If some already some path is set then you can use semicolon(;) to add the given path "C:\Windows\System32" else directly add the same.
Your condition is wrong. myChar != 'n' || myChar != 'N'
will always be true.
Use myChar != 'n' && myChar != 'N'
instead
My project was using pipenv
. The following command worked for me:
pipenv install mysql-connector-python
<a href="…" style="cursor: pointer;"><div> … </div></a>
If you want it to work in browsers that don't support history.pushState
and history.popState
yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the window.location.hash
property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange
(IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval
for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched
overflow-y: scroll;
to
overflow-y: auto;
Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.
xhtml below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Div in table</title>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<style type="text/css" media="all">
th {border-bottom: 2px solid #ccc; }
th,td {padding: 0.5em 1em;
margin: 0;
border-collapse: collapse;
}
tr td:first-child
{border-right: 2px solid #ccc; }
td > div {width: 249px;
height: 299px;
background-color:Gray;
overflow-y: auto;
max-width:230px;
max-height:100px;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div>
<table>
<thead>
<tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
</thead>
<tbody>
<tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
<tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
<tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
<tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
<tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
<tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
<tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
</body>
</table>
</div>
</body>
</html>
For those who use java/android and struggle with this matter try:
"^\\p{L}+[\\p{L}\\p{Z}\\p{P}]{0,}"
This works with names like
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
When you use useState
, you can get an update method for the state item:
const [theArray, setTheArray] = useState(initialArray);
then, when you want to add a new element, you use that function and pass in the new array or a function that will create the new array. Normally the latter, since state updates are asynchronous and sometimes batched:
setTheArray(oldArray => [...oldArray, newElement]);
Sometimes you can get away without using that callback form, if you only update the array in handlers for certain specific user events like click
(but not like mousemove
):
setTheArray([...theArray, newElement]);
The events for which React ensures that rendering is flushed are the "discrete events" listed here.
Live Example (passing a callback into setTheArray
):
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
_x000D_
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
_x000D_
Because the only update to theArray
in there is the one in a click
event (one of the "discrete" events), I could get away with a direct update in addEntry
:
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray([...theArray, `Entry ${theArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
_x000D_
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
_x000D_
That may be overhead but should work.
double yourDouble = 1.05;
string stringForm = yourDouble.ToString();
int dotPosition = stringForm.IndexOf(".");
decimal decimalPart = Decimal.Parse("0" + stringForm.Substring(dotPosition));
Console.WriteLine(decimalPart); // 0.05
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:
? Open With ? Windows PowerShell
When you right-click a .ps1 file and choose Open With
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
? Run with PowerShell
When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.
It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:
try
{
# Do your script's stuff
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
Your Action is expecting string parameters, but you're sending a composite object.
You need to create an object that matches what you're sending.
public class Data
{
public string username { get;set; }
public string password { get;set; }
}
public JsonResult Login(Data data)
{
}
EDIT
In addition, toStringify() is probably not what you want here. Just send the object itself.
data: data,
The ^
negates a character class:
SELECT * FROM mytable WHERE REGEXP_LIKE(column_1, '[^A-Za-z]')
I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.
Note: Despite the spec being quite emphatic that you must use \r\n to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV
<?php
# $args must be an associative array
# required keys: from, to, body
# body can be a string or a [tree of] associative arrays. See examples below
# optional keys: subject, reply_to, cc, bcc
# EXAMPLES:
# # text-only email:
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# # body will be text/plain because we're passing a string that doesn't start with '<'
# 'body' => 'Hi, testing 1 2 3',
# ));
#
# # html-only email
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# # body will be text/html because we're passing a string that starts with '<'
# 'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
# ));
#
# # text-only email (explicitly, in case first character is dynamic or something)
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# # body will be text/plain because we're passing a string that doesn't start with '<'
# 'body' => array(
# 'type' => 'text',
# 'body' => $message_text,
# )
# ));
#
# # email with text and html alternatives (auto-detected mime types)
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# 'body' => array(
# 'type' => 'alternatives',
# 'body' => array(
# "Hi!\n\nI like cheese",
# '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
# )
# )
# ));
#
# # email with text and html alternatives (explicit types)
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# 'body' => array(
# 'type' => 'alternatives',
# 'body' => array(
# array(
# 'type' => 'text',
# 'body' => "Hi!\n\nI like cheese",
# ),
# array(
# 'type' => 'html',
# 'body' => '<h1>Hi!</h1><p>I like cheese</p>',
# ),
# )
# )
# ));
#
# # email with an attachment
# email2(array(
# 'from' => '[email protected]',
# 'to' => '[email protected]',
# 'subject' => 'test',
# 'body' => array(
# 'type' => 'mixed',
# 'body' => array(
# "Hi!\n\nCheck out this (inline) image",
# array(
# 'type' => 'image/png',
# 'disposition' => 'inline',
# 'body' => $image_data, # raw file contents
# ),
# "Hi!\n\nAnd here's an attachment",
# array(
# 'type' => 'application/pdf; name="attachment.pdf"',
# 'disposition' => 'attachment; filename="attachment.pdf"',
# 'body' => $pdf_data, # raw file contents
# ),
# "Or you can use shorthand:",
# array(
# 'type' => 'application/pdf',
# 'attachment' => 'attachment.pdf', # name for client (not data source)
# 'body' => $pdf_data, # raw file contents
# ),
# )
# )
# ))
function email2($args) {
if (!isset($args['from'])) { return 1; }
$from = $args['from'];
if (!isset($args['to'])) { return 2; }
$to = $args['to'];
$subject = isset($args['subject']) ? $args['subject'] : '';
$reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
$cc = isset($args['cc']) ? $args['cc'] : '';
$bcc = isset($args['bcc']) ? $args['bcc'] : '';
#FIXME should allow many more characters here (and do Q encoding)
$subject = isset($args['subject']) ? $args['subject'] : '';
$subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);
$headers = "From: $from";
if($reply_to) {
$headers .= PHP_EOL . "Reply-To: $reply_to";
}
if($cc) {
$headers .= PHP_EOL . "CC: $cc";
}
if($bcc) {
$headers .= PHP_EOL . "BCC: $bcc";
}
$r = email2_helper($args['body']);
$headers .= PHP_EOL . $r[0];
$body = $r[1];
if (mail($to, $subject, $body, $headers)) {
return 0;
} else {
return 5;
}
}
function email2_helper($body, $top = true) {
if (is_string($body)) {
if (substr($body, 0, 1) == '<') {
return email2_helper(array('type' => 'html', 'body' => $body), $top);
} else {
return email2_helper(array('type' => 'text', 'body' => $body), $top);
}
}
# now we can assume $body is an associative array
# defaults:
$type = 'application/octet-stream';
$mime = false;
$boundary = null;
$disposition = null;
$charset = false;
# process 'type' first, because it sets defaults for others
if (isset($body['type'])) {
$type = $body['type'];
if ($type === 'text') {
$type = 'text/plain';
$charset = true;
} elseif ($type === 'html') {
$type = 'text/html';
$charset = true;
} elseif ($type === 'alternative' || $type === 'alternatives') {
$mime = true;
$type = 'multipart/alternative';
} elseif ($type === 'mixed') {
$mime = true;
$type = 'multipart/mixed';
}
}
if (isset($body['disposition'])) {
$disposition = $body['disposition'];
}
if (isset($body['attachment'])) {
if ($disposition == null) {
$disposition = 'attachment';
}
$disposition .= "; filename=\"{$body['attachment']}\"";
$type .= "; name=\"{$body['attachment']}\"";
}
# make headers
$headers = array();
if ($top && $mime) {
$headers[] = 'MIME-Version: 1.0';
}
if ($mime) {
$boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
$type .= "; boundary=$boundary";
}
if ($charset) {
$type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
}
$headers[] = "Content-Type: $type";
if ($disposition !== null) {
$headers[] = "Content-Disposition: {$disposition}";
}
$data = '';
# return array, first el is headers, 2nd is body (php's mail() needs them separate)
if ($mime) {
foreach ($body['body'] as $sub_body) {
$data .= "--$boundary" . PHP_EOL;
$r = email2_helper($sub_body, false);
$data .= $r[0] . PHP_EOL . PHP_EOL; # headers
$data .= $r[1] . PHP_EOL . PHP_EOL; # body
}
$data .= "--$boundary--";
} else {
if(preg_match('/[^\x09\x0A\x0D\x20-\x7E]/', $body['body'])) {
$headers[] = "Content-Transfer-Encoding: base64";
$data .= chunk_split(base64_encode($body['body']));
} else {
$data .= $body['body'];
}
}
return array(join(PHP_EOL, $headers), $data);
}
Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
.Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
.Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
.Select(kvp => kvp.Key)
.ToList();
foreach(string theKey in keys)
{
source.Remove(theKey);
}
To avoid deprecated opts
and theme_rect
use:
myplot + theme(panel.background = element_rect(fill='green', colour='red'))
To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):
theme_jack <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.text = element_text(colour = "white"),
axis.title.x = element_text(colour = "pink", size=rel(3)),
axis.title.y = element_text(colour = "blue", angle=45),
panel.background = element_rect(fill="green"),
panel.grid.minor.y = element_line(size=3),
panel.grid.major = element_line(colour = "orange"),
plot.background = element_rect(fill="red")
)
}
To make your custom theme the default when ggplot is called in future, without masking:
theme_set(theme_jack())
If you want to change an element of the currently set theme:
theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))
To store the current default theme as an object:
theme_pink <- theme_get()
Note that theme_pink
is a list whereas theme_jack
was a function. So to return the theme to theme_jack use theme_set(theme_jack())
whereas to return to theme_pink use theme_set(theme_pink)
.
You can replace theme_gray
by theme_bw
in the definition of theme_jack
if you prefer. For your custom theme to resemble theme_bw
but with all gridlines (x, y, major and minor) turned off:
theme_nogrid <- function (base_size = 12, base_family = "") {
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid = element_blank()
)
}
Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.
theme_map <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(0.3, "lines"),
axis.ticks.margin=unit(0.5, "lines"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.background=element_rect(fill="white", colour=NA),
legend.key=element_rect(colour="white"),
legend.key.size=unit(1.2, "lines"),
legend.position="right",
legend.text=element_text(size=rel(0.8)),
legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.margin=unit(0, "lines"),
plot.background=element_blank(),
plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
plot.title=element_text(size=rel(1.2)),
strip.background=element_rect(fill="grey90", colour="grey50"),
strip.text.x=element_text(size=rel(0.8)),
strip.text.y=element_text(size=rel(0.8), angle=-90)
)
}
There is now (Chrome 76+ & FF 69+) a Blob.prototype.arrayBuffer() method which will return a Promise resolving with an ArrayBuffer representing the Blob's data.
(async () => {_x000D_
const blob = new Blob(['hello']);_x000D_
const buf = await blob.arrayBuffer();_x000D_
console.log( buf.byteLength ); // 5_x000D_
})();
_x000D_
In my case it was a simple type
$_SESSION['role' == 'ge']
I was missing the correct closing bracket
$_SESSION['role'] == 'ge'
min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:
cLower = *min_element(C.begin(), C.end());
As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.
1) Use this chrome extension, Requestly to redirect your url from the https
version of your url to the http
version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.
2) Change the code of your app to optionally make your endpoint redirect to the http
version of your url instead of the https
version (or vice versa). If you do this, the request will fail with status code 0.
In case some one wants to know how to set up Environment variables
Once you have done that you can run using the command from the start->command line as below
php <path to file location>
PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself
const buildSortedQuery = (args) => {_x000D_
return Object.keys(args)_x000D_
.sort()_x000D_
.map(key => {_x000D_
return window.encodeURIComponent(key)_x000D_
+ '='_x000D_
+ window.encodeURIComponent(args[key]);_x000D_
})_x000D_
.join('&');_x000D_
};_x000D_
_x000D_
console.log(buildSortedQuery({_x000D_
foo: "hi there",_x000D_
bar: "100%"_x000D_
}));_x000D_
_x000D_
//bar=100%25&foo=hi%20there
_x000D_
Define your target to
1) take an argument q
2) replace any statements return foo
with q.put(foo); return
so a function
def func(a):
ans = a * a
return ans
would become
def func(a, q):
ans = a * a
q.put(ans)
return
and then you would proceed as such
from Queue import Queue
from threading import Thread
ans_q = Queue()
arg_tups = [(i, ans_q) for i in xrange(10)]
threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]
_ = [t.start() for t in threads]
_ = [t.join() for t in threads]
results = [q.get() for _ in xrange(len(threads))]
And you can use function decorators/wrappers to make it so you can use your existing functions as target
without modifying them, but follow this basic scheme.
It is important that the Main
method is placed in the class that is properly configured in Visual Studio as a start-up object:
SimpleAIMLEditor.Program
from the drop-down for your start-up objectNow run your application again. The error will disappear.
I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.
Another approach is to
and then
garbage collection (GC) is a form of automatic memory management by removing the objects that no needed anymore.
any process deal with memory follow these steps:
1 - allocate your memory space you need
2 - do some processing
3 - free this memory space
there are two main algorithm used to detect which objects no needed anymore.
Reference-counting garbage collection: this algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it", the object will removed if no reference point to it
Mark-and-sweep algorithm: connect each objects to root source. any object doesn't connect to root or other object. this object will be removed.
currently most modern browsers using the second algorithm.
If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:
select column_name,
case
when domain_name is not null then domain_name
when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
else data_type
end as myType
from information_schema.columns
where table_name='test'
with result:
column_name | myType
-------------+-------------------
test_id | test_domain
test_vc | varchar(15)
test_n | numeric(15,3)
big_n | bigint
ip_addr | inet
In my case the culprit was the lone opening <?php
tag in the last line of the file. Apparently it works on some configurations with no problems but causes problems on others.
try that :
declare @t nvarchar(max)
set @t='aaaa'
select len(@t)-len(replace(@t,'a',''))
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
or better:
baos.toString( codepage );
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.
I'm using Firefox, and my working solution is very close to obysky. The only difference is that the method you call in an svg element will return multiple rects and you need to select the first one.
var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;
in swift 3.0:
@IBOutlet weak var selectionButton: UIButton!
selectionButton.setImage(UIImage.addBlueIcon, for: .selected)
\ = \\
" = \"
new line = \r\n
OR \n\r
OR \n
(depends on OS) bun usualy \n
enough.
taabulator = \t
I was facing the same problem as mentioned in the question. The following steps solved my problem.
I upgraded the nodejs package link with following steps
Clear NPM's cache:
npm cache clean -f
Install a little helper called 'n'
npm install -g n
Then I went to node.js website, downloaded the latest node js package, installed it, and my problem was solved.
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Slicing of arrays is done with [first:last+1]
.
One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:
if len(s) <= 100:
print s
else:
print "%s..."%(s[:97])
And yes, I know ()
is superfluous in this case for the %
formatting operator, it's just my style.
I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:
Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!
static final String EMPTY = "";
static final String POINT = '.';
static final String COMMA = ',';
static final String POINT_AS_STRING = ".";
static final String COMMA_AS_STRING = ",";
/**
* Converts a String to a BigDecimal.
* if there is more than 1 '.', the points are interpreted as thousand-separator and will be removed for conversion
* if there is more than 1 ',', the commas are interpreted as thousand-separator and will be removed for conversion
* the last '.' or ',' will be interpreted as the separator for the decimal places
* () or - in front or in the end will be interpreted as negative number
*
* @param value
* @return The BigDecimal expression of the given string
*/
public static BigDecimal toBigDecimal(final String value) {
if (value != null){
boolean negativeNumber = false;
if (value.containts("(") && value.contains(")"))
negativeNumber = true;
if (value.endsWith("-") || value.startsWith("-"))
negativeNumber = true;
String parsedValue = value.replaceAll("[^0-9\\,\\.]", EMPTY);
if (negativeNumber)
parsedValue = "-" + parsedValue;
int lastPointPosition = parsedValue.lastIndexOf(POINT);
int lastCommaPosition = parsedValue.lastIndexOf(COMMA);
//handle '1423' case, just a simple number
if (lastPointPosition == -1 && lastCommaPosition == -1)
return new BigDecimal(parsedValue);
//handle '45.3' and '4.550.000' case, only points are in the given String
if (lastPointPosition > -1 && lastCommaPosition == -1){
int firstPointPosition = parsedValue.indexOf(POINT);
if (firstPointPosition != lastPointPosition)
return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY));
else
return new BigDecimal(parsedValue);
}
//handle '45,3' and '4,550,000' case, only commas are in the given String
if (lastPointPosition == -1 && lastCommaPosition > -1){
int firstCommaPosition = parsedValue.indexOf(COMMA);
if (firstCommaPosition != lastCommaPosition)
return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY));
else
return new BigDecimal(parsedValue.replace(COMMA, POINT));
}
//handle '2.345,04' case, points are in front of commas
if (lastPointPosition < lastCommaPosition){
parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY);
return new BigDecimal(parsedValue.replace(COMMA, POINT));
}
//handle '2,345.04' case, commas are in front of points
if (lastCommaPosition < lastPointPosition){
parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY);
return new BigDecimal(parsedValue);
}
throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal.");
}
return null;
}
Of course i've tested the method:
@Test(dataProvider = "testBigDecimals")
public void toBigDecimal_defaultLocaleTest(String stringValue, BigDecimal bigDecimalValue){
BigDecimal convertedBigDecimal = DecimalHelper.toBigDecimal(stringValue);
Assert.assertEquals(convertedBigDecimal, bigDecimalValue);
}
@DataProvider(name = "testBigDecimals")
public static Object[][] bigDecimalConvertionTestValues() {
return new Object[][] {
{"5", new BigDecimal(5)},
{"5,3", new BigDecimal("5.3")},
{"5.3", new BigDecimal("5.3")},
{"5.000,3", new BigDecimal("5000.3")},
{"5.000.000,3", new BigDecimal("5000000.3")},
{"5.000.000", new BigDecimal("5000000")},
{"5,000.3", new BigDecimal("5000.3")},
{"5,000,000.3", new BigDecimal("5000000.3")},
{"5,000,000", new BigDecimal("5000000")},
{"+5", new BigDecimal("5")},
{"+5,3", new BigDecimal("5.3")},
{"+5.3", new BigDecimal("5.3")},
{"+5.000,3", new BigDecimal("5000.3")},
{"+5.000.000,3", new BigDecimal("5000000.3")},
{"+5.000.000", new BigDecimal("5000000")},
{"+5,000.3", new BigDecimal("5000.3")},
{"+5,000,000.3", new BigDecimal("5000000.3")},
{"+5,000,000", new BigDecimal("5000000")},
{"-5", new BigDecimal("-5")},
{"-5,3", new BigDecimal("-5.3")},
{"-5.3", new BigDecimal("-5.3")},
{"-5.000,3", new BigDecimal("-5000.3")},
{"-5.000.000,3", new BigDecimal("-5000000.3")},
{"-5.000.000", new BigDecimal("-5000000")},
{"-5,000.3", new BigDecimal("-5000.3")},
{"-5,000,000.3", new BigDecimal("-5000000.3")},
{"-5,000,000", new BigDecimal("-5000000")},
{null, null}
};
}
I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:
I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.
Choose Second Method of Authentication while installing.
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:
var myMappings = {
"Name": 0.1,
"Phone": 0.1,
"Address": 0.5,
"Zip": 0.1,
"Comments": 0.2
};
for (var col in myMappings) {
alert((myMappings[col] * 100) + "%");
}
if you are using it in windows, be sure to add the path to the db in "" and also to use double slash \ in the path to make sure windows understands it.
It seems like you're actually trying to extract a name vice simply find a match. If this is the case, having span indexes for your match is helpful and I'd recommend using re.finditer
. As a shortcut, you know the name
part of your regex is length 5 and the is valid
is length 9, so you can slice the matching text to extract the name.
Note - In your example, it looks like s
is string with line breaks, so that's what's assumed below.
## covert s to list of strings separated by line: s2 = s.splitlines() ## find matches by line: for i, j in enumerate(s2): matches = re.finditer("name (.*) is valid", j) ## ignore lines without a match if matches: ## loop through match group elements for k in matches: ## get text match_txt = k.group(0) ## get line span match_span = k.span(0) ## extract username my_user_name = match_txt[5:-9] ## compare with original text print(f'Extracted Username: {my_user_name} - found on line {i}') print('Match Text:', match_txt)
Based on the documentation you should be able to use auto
in combination with the preferred placement e.g. auto left
http://getbootstrap.com/javascript/#popovers: "When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right."
I was trying to do the same thing and then realised that this functionality already existed.
Just use Analyze | Inspect Code
with appropriate inspection enabled (Unused declaration under Declaration redundancy group).
Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"
Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate
. The predicate is a user defined condition to select rows of user's choice.
Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT
Operation.
See more : Relational Algebra and its operations
I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).
This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.
To demonstrate, see this example:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground):
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]
We created a "backing" array a
with length 10
. Then we create the x
destination slice by slicing this a
array, y
slice is created using the composite literal []int{3, 4}
. Now when we append y
to x
, the result is the expected [1 2 3 4]
, but what may be surprising is that the backing array a
also changed, because capacity of x
is 10
which is sufficient to append y
to it, so x
is resliced which will also use the same a
backing array, and append()
will copy elements of y
into there.
If you want to avoid this, you may use a full slice expression which has the form
a[low : high : max]
which constructs a slice and also controls the resulting slice's capacity by setting it to max - low
.
See the modified example (the only difference is that we create x
like this: x = a[:2:2]
:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground)
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]
As you can see, we get the same x
result but the backing array a
did not change, because capacity of x
was "only" 2
(thanks to the full slice expression a[:2:2]
). So to do the append, a new backing array is allocated that can store the elements of both x
and y
, which is distinct from a
.
LIMIT n,1 doesn't work in MS SQL Server. I think it's just about the only major database that doesn't support that syntax. To be fair, it isn't part of the SQL standard, although it is so widely supported that it should be. In everything except SQL server LIMIT works great. For SQL server, I haven't been able to find an elegant solution.
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("")
.
Displaying an image from MySql Db.
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
Swift 3 & Swift 4:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let indexPath = collectionView.indexPathForItem(at: visiblePoint) else { return }
print(indexPath[1])
}
If you want to show actual number than you can add +1
Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?
e.g.
<p dir="rtl">
In my case, I needed to Edit Inbound Rules
on my AWS RDS instance to accept All Traffic
. The default TCP/IP
constraint prevented me from creating a database from my local machine otherwise.
I've been struggling with this on mobile and tablet. My solution was to use absolute
positioning on the spinners, so I'm just posting it in case it helps anyone else:
<html><head>_x000D_
<style>_x000D_
body {padding: 10px;margin: 10px}_x000D_
input[type=number] {_x000D_
/*for absolutely positioning spinners*/_x000D_
position: relative; _x000D_
padding: 5px;_x000D_
padding-right: 25px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button,_x000D_
input[type=number]::-webkit-outer-spin-button {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-outer-spin-button, _x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: inner-spin-button !important;_x000D_
width: 25px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
}_x000D_
</style>_x000D_
<meta name="apple-mobile-web-app-capable" content="yes"/>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0"/>_x000D_
</head>_x000D_
<body >_x000D_
<input type="number" value="1" step="1" />_x000D_
_x000D_
</body></html>
_x000D_
select max(id) from Customers
Only works in IE:
window.open ("mapage.html","","fullscreen=yes");
window.open('','_parent','');
window.close();
also, make sure the server is listening for ur mobile device! for example, by default jekyll only answers requests made by the host machine. this solved my problem:
Connect to a locally built Jekyll Server using mobile devices in the LAN
Easier option is to
use ./eclipse -clean
Yes! Finally! I just tried it with Chrome, Version 66.0.3359.170 (Official Build) (64-bit) on Mac.
You can change the values in the scopes as in the first picture, or with the console as in the second picture.
In our experience, with Apache falling over on request of favicon.ico, we commented out extra headers in the .htaccess file.
For example we had Header set X-XSS-Protection "1; mode=block"
... but we had forgotten to sudo a2enmod headers beforehand. Commenting out extra headers being sent resolved our favicon.ico issue.
We also had several virtual hosts set up for development, and only failed out with 500 Internal Server Error when using http://localhost and fetching /favicon.ico. If you run "curl -v http://localhost/favicon.ico" and get a warning about the host name not being in the resolver cache or something to that effect, you might experience problems.
It could be as simple as not fetching (we tried that and it didn't work, because our root cause was different) or look around for directives in apache2.conf or .htaccess which might be causing strange 500 Internal Server Error messages.
We found it failed so quickly there was nothing useful in Apache's error logs whatsoever and spent an entire morning changing small things here and there until we resolved the problem of setting extra headers when we had forgotten to have mod_headers loaded!
Have you tried somethig like this?
.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}
<div class="showhim">HOVER ME
<div class="showme">hai</div>
<div class="hideme">bye</div>
</div>
I dont know any reason why it shouldn't be possible.
If you are talking about the scrollbar that automatically appears on a div
with overflow: scroll
(or auto
), then no, that's still a native scrollbar rendered by the browser using normal OS widgets, and not something that can be styled(*).
Whilst you can replace it with a proxy made out of stylable divs and JavaScript as suggested by Matt, I wouldn't recommend it for the general case. Script-driven scrollbars never quite behave exactly the same as real OS scrollbars, causing usability and accessibility problems.
(*: Except for the IE colouring styles, which I wouldn't really recommend either. Apart from being IE-only, using them forces IE to fall back from using nice scrollbar images from the current Windows theme to ugly old Win95-style scrollbars.)
Thanks ProfoundlyOblivious,
No SendKeys, check
No VBA Extensibility, check
No 3rd Party Executables, check
One minor problem:
Localised Office versions use another caption for the immediate window. In Dutch it is named "Direct".
I have added one line to get the localised caption in case FindWindowExA fails. For those who use both the English and Dutch version of MS-Office.
+1 for you for doing most of the work!
Option Explicit
Private Declare PtrSafe Function FindWindowA Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function FindWindowExA Lib "user32" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
Private Declare PtrSafe Function PostMessageA Lib "user32" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As Long
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As LongPtr)
Private Const WM_ACTIVATE As Long = &H6
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_CONTROL = &H11
Public Sub ClearImmediateWindow()
Dim hwndVBE As LongPtr
Dim hwndImmediate As LongPtr
hwndVBE = FindWindowA("wndclass_desked_gsk", vbNullString)
hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Immediate") ' English caption
If hwndImmediate = 0 Then hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Direct") ' Dutch caption
PostMessageA hwndImmediate, WM_ACTIVATE, 1, 0&
keybd_event VK_CONTROL, 0, 0, 0
keybd_event vbKeyA, 0, 0, 0
keybd_event vbKeyA, 0, KEYEVENTF_KEYUP, 0
keybd_event VK_CONTROL, 0, KEYEVENTF_KEYUP, 0
keybd_event vbKeyDelete, 0, 0, 0
keybd_event vbKeyDelete, 0, KEYEVENTF_KEYUP, 0
End Sub
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }
For OS X Yosemite and above, and Xcode 6+
Open Xcode > Window > Devices
Choose your device. You can see the installed application list and add a new one by hitting +
Make sure to use cascade
constraint at the end to automatically drop all objects that depend on the table (such as views and projections).
drop table if exists tableName cascade;
As the error notes, the problem is in the line:
if guess[i] == winning_numbers[i]
The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:
for i in range(tickets):
bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
guess.append(bubble)
print(bubble)
The size of how many guesses you are giving your user is based on
# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))
So if the number of tickets they want is less than 5, then your code here
for i in range(5):
if guess[i] == winning_numbers[i]:
match = match+1
return match
will throw an error because there simply aren't that many elements in the guess
list.
The -i
option is the one that you want:
curl -i http://localhost
-i, --include Include protocol headers in the output (H/F)
Alternatively you can use the verbose option:
curl -v http://localhost
-v, --verbose Make the operation more talkative
You need the change those double quotation marks into singles.
ie. if (answer == 'y')
returns true
;
Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx
aggfunc=pd.Series.nunique
will only count unique values for a series - in this case count the unique values for a column. But this doesn't quite reflect as an alternative to aggfunc='count'
For simple counting, it better to use aggfunc=pd.Series.count
There's a definite need to get the last element of a dictionary, for example to confirm whether the latest element has been appended to the dictionary object or not.
We need to convert the dictionary keys to a list object, and use an index of -1 to print out the last element.
mydict = {'John':'apple','Mat':'orange','Jane':'guava','Kim':'apple','Kate': 'grapes'}
mydict.keys()
output: dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])
list(mydict.keys())
output: ['John', 'Mat', 'Jane', 'Kim', 'Kate']
list(mydict.keys())[-1]
output: 'Kate'
Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:
String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:
System.out.println(Arrays
.stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
.map(s -> Character.toString((char)Integer.parseInt(s, 16)))
.collect(Collectors.joining()));
Either way, this gives a few lines starting with the following:
uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3
Hmmm... :-)
To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:
function log(args) {_x000D_
var str = "";_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
if (typeof arguments[i] === "object") {_x000D_
str += JSON.stringify(arguments[i]);_x000D_
} else {_x000D_
str += arguments[i];_x000D_
}_x000D_
}_x000D_
var div = document.createElement("div");_x000D_
div.innerHTML = str;_x000D_
document.body.appendChild(div);_x000D_
}_x000D_
_x000D_
Number.prototype.addCommas = function (str) {_x000D_
if (str === undefined) {_x000D_
str = this;_x000D_
}_x000D_
_x000D_
var parts = (str + "").split("."),_x000D_
main = parts[0],_x000D_
len = main.length,_x000D_
output = "",_x000D_
first = main.charAt(0),_x000D_
i;_x000D_
_x000D_
if (first === '-') {_x000D_
main = main.slice(1);_x000D_
len = main.length; _x000D_
} else {_x000D_
first = "";_x000D_
}_x000D_
i = len - 1;_x000D_
while(i >= 0) {_x000D_
output = main.charAt(i) + output;_x000D_
if ((len - i) % 3 === 0 && i > 0) {_x000D_
output = "," + output;_x000D_
}_x000D_
--i;_x000D_
}_x000D_
// put sign back_x000D_
output = first + output;_x000D_
// put decimal part back_x000D_
if (parts.length > 1) {_x000D_
output += "." + parts[1];_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
var testCases = [_x000D_
1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,_x000D_
-1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1_x000D_
];_x000D_
_x000D_
for (var i = 0; i < testCases.length; i++) {_x000D_
log(testCases[i].addCommas());_x000D_
}_x000D_
_x000D_
/*for (var i = 0; i < testCases.length; i++) {_x000D_
log(Number.addCommas(testCases[i]));_x000D_
}*/
_x000D_
My favourite UI tutorials all come from zetcode.com:
These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.
You can use the Build Class to get the device information.
For example:
String myDeviceModel = android.os.Build.MODEL;
I found a solution for this in my case, try to update the NuGet Package Manager.
To do this:
This let me install packages without problem again.
Hope this helps!
I recalled reading about this in the standard, so here goes:
See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.
ISO/IEC 9899:201x
7.21.3 §7
At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
7.21.3 §3
When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.
This means that std::cout
and std::cin
are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.
However, if std::cout.sync_with_stdio(false)
is called, then '\n'
will not cause a flush even to interactive devices. Otherwise '\n'
is equivalent to std::endl
unless piping to files: c++ ref on std::endl.
Yes you can use them, for example I use them to more easily style groups of data, like this:
thead th { width: 100px; border-bottom: solid 1px #ddd; font-weight: bold; }_x000D_
tbody:nth-child(odd) { background: #f5f5f5; border: solid 1px #ddd; }_x000D_
tbody:nth-child(even) { background: #e5e5e5; border: solid 1px #ddd; }
_x000D_
<table>_x000D_
<thead>_x000D_
<tr><th>Customer</th><th>Order</th><th>Month</th></tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr><td>Customer 1</td><td>#1</td><td>January</td></tr>_x000D_
<tr><td>Customer 1</td><td>#2</td><td>April</td></tr>_x000D_
<tr><td>Customer 1</td><td>#3</td><td>March</td></tr>_x000D_
</tbody>_x000D_
<tbody>_x000D_
<tr><td>Customer 2</td><td>#1</td><td>January</td></tr>_x000D_
<tr><td>Customer 2</td><td>#2</td><td>April</td></tr>_x000D_
<tr><td>Customer 2</td><td>#3</td><td>March</td></tr>_x000D_
</tbody>_x000D_
<tbody>_x000D_
<tr><td>Customer 3</td><td>#1</td><td>January</td></tr>_x000D_
<tr><td>Customer 3</td><td>#2</td><td>April</td></tr>_x000D_
<tr><td>Customer 3</td><td>#3</td><td>March</td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
You can view an example here. It'll only work in newer browsers, but that's what I'm supporting in my current application, you can use the grouping for JavaScript etc. The main thing is it's a convenient way to visually group the rows to make the data much more readable. There are other uses of course, but as far as applicable examples, this one is the most common one for me.
Simple program
import java.io.*;
class Aclass
{
public int a;
}
public class test
{
public static void foo_obj(Aclass obj)
{
obj.a=5;
}
public static void foo_int(int a)
{
a=3;
}
public static void main(String args[])
{
//test passing an object
Aclass ob = new Aclass();
ob.a=0;
foo_obj(ob);
System.out.println(ob.a);//prints 5
//test passing an integer
int i=0;
foo_int(i);
System.out.println(i);//prints 0
}
}
From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.
In my opinion, the issue is because the environment variable is not set up to recognize pip as a valid command.
In general, the pip in Python is at this location:
C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts > pip
So all we need to do is go to Computer Name> Right Click > Advanced System Settings > Select Env Variable then under system variables > reach to Path> Edit path and add the Path by separating this path by putting a semicolon after the last path already was in the Env Variable.
Now run Python shell, and this should work.
Hope this will help you. I am using this solution for Search on some columns but i don't want to display them on frontend.
$(document).ready(function() {
$('#example').dataTable({
"scrollY": "500px",
"scrollCollapse": true,
"scrollX": false,
"bPaginate": false,
"columnDefs": [
{
"width": "30px",
"targets": 0,
},
{
"width": "100px",
"targets": 1,
},
{
"width": "100px",
"targets": 2,
},
{
"width": "76px",
"targets": 5,
},
{
"width": "80px",
"targets": 6,
},
{
"targets": [ 7 ],
"visible": false,
"searchable": true
},
{
"targets": [ 8 ],
"visible": false,
"searchable": true
},
{
"targets": [ 9 ],
"visible": false,
"searchable": true
},
]
});
});
Why not use LIKE?
SELECT * FROM items WHERE items.xml LIKE '%123456%'
Update maven version to 3.6.3 and run
mvn -Dhttps.protocols=TLSv1.2 install
it worked on centos 6.9
Background Image from API in swift 4 (with Kingfisher) :
import UIKit
import Kingfisher
extension UIView {
func addBackgroundImage(imgUrl: String, placeHolder: String){
let backgroundImage = UIImageView(frame: self.bounds)
backgroundImage.kf.setImage(with: URL(string: imgUrl), placeholder: UIImage(named: placeHolder))
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.insertSubview(backgroundImage, at: 0)
}
}
Usage:
someview.addBackgroundImage(imgUrl: "yourImgUrl", placeHolder: "placeHolderName")
FileStorage
contains stream
field. This object must extend IO or file object, so it must contain read
and other similar methods. FileStorage
also extend stream
field object attributes, so you can just use file.read()
instead file.stream.read()
. Also you can use save
argument with dst
parameter as StringIO
or other IO or file object to copy FileStorage.stream
to another IO or file object.
See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.
var str1 = "150:05:05",
var str2 = "80:04:59";
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
for (var i = 0; i < time1.length; i++) {
if(time1[i] > time2[i]){
return 1;
} else if(time1[i] < time2[i]) {
return -1;
}
}
}
If you are familiar with gcc, as you indicated in the question, you can install MinGW, which will set a linux-like compile environment in Win7. Otherwise, Visual Studio 2010 Express is the best choice.
You could analyse the user agent ($_SERVER['HTTP_USER_AGENT']
) or compare the client’s IP address ($_SERVER['REMOTE_ADDR']
) with a list of IP addresses of search engine bots.
Program to get the current working directory=user.dir
public class CurrentDirectoryExample {
public static void main(String args[]) {
String current = System.getProperty("user.dir");
System.out.println("Current working directory in Java : " + current);
}
}
If we are using EF and reading the database element in while loop then,
using( var idr = connection, SP.......)
{
while(idr.read())
{
if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
//do something
}
}
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.
This should get you the desired output:
mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }'
If you want a simple integer rounding, you can use printf:
mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }'
The sender is the control that the action is for (say OnClick, it's the button).
The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.
What Chris is saying is you can do this:
protected void someButton_Click (object sender, EventArgs ea)
{
Button someButton = sender as Button;
if(someButton != null)
{
someButton.Text = "I was clicked!";
}
}
For Spring Boot 2.1.0 and later you can use
mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar
proxy issue can cause this. IIS webconfig put this in
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" />
</defaultProxy>
I had the same issue when I've modified .project xml-file. When I reverted files to original version the project was created, then I was able to import project. Maybe it helps someone who has the same kind of problem ;)
Why be easy when it can be complicated? Why use third-party applications like netdom.exe when correct interogations is the way? Try 2 interogations:
wmic computersystem where caption='%computername%' get caption, UserName, Domain /format:value
wmic computersystem where "caption like '%%%computername%%%'" get caption, UserName, Domain /format:value
or in a batch file use loop
for /f "tokens=2 delims==" %%i in ('wmic computersystem where "Caption like '%%%currentname%%%'" get UserName /format:value') do (echo. UserName- %%i)
As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.
You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.
If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date
constructor is not supported pre IE9:
var queryDate = '2009-11-01',
dateParts = queryDate.match(/(\d+)/g)
realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
// months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');
$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);
Check the above example here.